<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset"
          is_add_button="新增" @addForm="edit"/>

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
             @selection-change="handleSelectionChange">
        <el-table-column prop="appId" label="应用ID" width="140"/>
        <el-table-column prop="appName" label="应用名称"/>
        <el-table-column prop="appKey" label="应用秘钥">
          <template #default="scope">
            <label>{{ scope.row.showKey ? scope.row.appKey : "******" }}</label>
            <span style="margin-left: 15px">
              <el-icon v-if="scope.row.showKey" @click="()=>{scope.row.showKey = !scope.row.showKey}"><View/></el-icon>
              <el-icon v-if="!scope.row.showKey" @click="()=>{scope.row.showKey = !scope.row.showKey}"><Hide/></el-icon>
            </span>
            <span style="margin-left: 5px">
              <el-icon v-copy="scope.row.appKey"><CopyDocument/></el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="channelName" label="广告渠道名称" width="150"/>
        <el-table-column prop="networkAppName" label="关联渠道应用" width="150"/>
        <el-table-column prop="nickName" label="所属用户"/>
        <el-table-column prop="appType" label="应用类型" width="100">
          <template #default="scope">
            {{ getDictionaryName("app_type", scope.row.appType) }}
          </template>
        </el-table-column>
        <el-table-column prop="apkUrl" label="下载链接">
          <template #default="scope">
            <a :href="scope.row.apkUrl" target="_blank">{{ scope.row.appName }}.apk</a>
          </template>
        </el-table-column>
        <el-table-column prop="qrCode" min-width="150" label="二维码">
          <template #default="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.qrCode" fit="fill"
                      :preview-src-list="[scope.row.qrCode]"/>
          </template>
        </el-table-column>
        <el-table-column prop="request" label="广告源请求数"/>
        <el-table-column prop="fillrate" label="广告源填充率"/>
        <el-table-column prop="impression" label="展示数"/>
        <el-table-column prop="click" label="点击数"/>
        <el-table-column prop="ecpm" label="ECPM"/>
        <el-table-column prop="revenue" label="收益"/>
        <el-table-column prop="impression_api" label="广告平台展示数"/>
        <el-table-column prop="click_api" label="广告平台点击数"/>
        <el-table-column prop="ecpm_api" label="广告平台ECPM"/>
        <el-table-column prop="updateTips" label="更新提示"/>
        <el-table-column prop="enabled" label="是否启用">
          <template #default="scope">
            {{ getDictionaryName("enabled", scope.row.enabled) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <div class="button">
              <el-button class="button-item" type="primary" style="margin-bottom: 5px" @click="openChannelLayer(scope.row)">
                关联渠道
              </el-button>
              <el-button class="button-item" type="primary" style="margin-bottom: 5px"
                         @click="edit(scope.row)">
                编辑
              </el-button>
              <el-popconfirm placement="left" title="确认删除该数据?" @confirm="removeApp(scope.row)">
                <template #reference>
                  <el-button class="button-item" style="margin-bottom: 5px" type="warning">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </Table>
    </div>

    <Layer :layer="channelLayer" @confirm="submit" @close="channelLayer.show=false">
      <Table
          @getTableData="getChanelData"
          v-model:page="channelPage"
          ref="channelTable"
          :data="channelData"
          @selection-change="handleChannelSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>

      <!-- 原有列 -->
      <el-table-column prop="channelId" label="渠道ID"/>
      <el-table-column prop="channelName" label="渠道名称"/>
      <el-table-column prop="loginType" label="登录类型">
        <template #default="scope">
          {{ getDictionaryName("login_type", scope.row.loginType) }}
        </template>
      </el-table-column>
      <el-table-column prop="channelAccount" label="渠道账号"/>
      <el-table-column prop="channelPwd" label="渠道密码"/>
      <el-table-column prop="channelStatus" label="渠道状态">
        <template #default="scope">
          {{ getDictionaryName("channel_status", scope.row.channelStatus) }}
        </template>
      </el-table-column>
      </Table>
    </Layer>

    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right: 30px">
        <el-row :gutter="5">
          <el-col :span="10" v-if="formEdit.appId">
            <el-form-item label="应用ID" required prop="appId">
              <el-input v-model="formEdit.appId" disabled placeholder="请输入" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="2" v-if="formEdit.appId"></el-col>
          <el-col :span="10">
            <el-form-item label="应用名称：" required prop="appName">
              <el-input v-model="formEdit.appName" placeholder="请输入" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="应用类型" required prop="appType">
              <el-select v-model="formEdit.appType">
                <el-option :value="1" label="Android"/>
                <el-option :value="2" label="IOS"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="是否上架" required prop="store_on_sale">
              <el-select v-model="formEdit.store_on_sale">
                <el-option :value="1" label="否"/>
                <el-option :value="2" label="是"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="上架商店" required prop="store_type">
              <el-select v-model="formEdit.store_type" placeholder="请选择上架应用商店">
                <el-option :value="1" label="App Store"/>
                <el-option :value="2" label="Google Play"/>
                <el-option :value="3" label="华为商店"/>
                <el-option :value="4" label="小米应用商店"/>
                <el-option :value="5" label="OPPO商店"/>
                <el-option :value="6" label="vivo商店"/>
                <el-option :value="7" label="应用宝"/>
                <el-option :value="8" label="TapTap"/>
                <el-option :value="9" label="Amazon应用商店"/>
                <el-option :value="10" label="三星应用商店"/>
                <el-option :value="11" label="小米海外应用商店"/>
                <el-option :value="12" label="华为海外应用市场"/>
                <el-option :value="13" label="Roku"/>
                <el-option :value="14" label="Samsung Smart TV"/>
                <el-option :value="15" label="Microsoft"/>
                <el-option :value="16" label="LG Smart TV"/>
                <el-option :value="17" label="Vizio"/>
                <el-option :value="99" label="其他"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="商店链接" required prop="store_url">
              <el-input v-model="formEdit.store_url" placeholder="请输入上架商店链接" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="应用域名" prop="domain" required>
              <el-input v-model="formEdit.domain" placeholder="请输入应用域名" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="应用包名" required prop="package_name">
              <el-input v-model="formEdit.package_name" placeholder="请输入应用包名" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="一级分类" prop="category">
              <el-select v-model="formEdit.category" placeholder="请选择上架应用商店">
                <el-option value="App" label="App"/>
                <el-option value="Game" label="Game"/>
                <el-option value="Family" label="Family"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="二级分类" required prop="sub_category">
              <el-select v-model="formEdit.sub_category" placeholder="请选择上架应用商店">
                <el-option value="Daydream" label="Daydream"/>
                <el-option value="Wear" label="Android Wear"/>
                <el-option value="Design" label="Art & Design"/>
                <el-option value="Vehicles" label="Auto & Vehicles"/>
                <el-option value="Beauty" label="Beauty"/>
                <el-option value="Books" label="Books & Reference"/>
                <el-option value="Business" label="Business"/>
                <el-option value="Comics" label="Comics"/>
                <el-option value="Communication" label="Communication"/>
                <el-option value="Dating" label="Dating"/>
                <el-option value="Education" label="Education"/>
                <el-option value="Entertainment" label="Entertainment"/>
                <el-option value="Events" label="Events"/>
                <el-option value="Finance" label="Finance"/>
                <el-option value="Drink" label="Food & Drink"/>
                <el-option value="Fitness" label="Health & Fitness"/>
                <el-option value="House" label="House & Home"/>
                <el-option value="Libraries" label="Libraries & Demo"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="屏幕方向" prop="screen_orientation">
              <el-select v-model="formEdit.screen_orientation" placeholder="请选择屏幕方向">
                <el-option :value="1" label="竖屏"/>
                <el-option :value="2" label="横屏"/>
                <el-option :value="3" label="所有"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="版本号" required prop="versionCode">
              <el-input v-model="formEdit.versionCode" placeholder="请输入版本号" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="遵守美国COPPA" prop="coppa">
              <el-switch v-model="formEdit.coppa"
                         :active-value="2"
                         :inactive-value="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="遵守美国CCPA" required prop="ccpa">
              <el-switch v-model="formEdit.ccpa"
                         :active-value="2"
                         :inactive-value="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="二维码链接：" required prop="qrCode">
          <el-input v-model="formEdit.qrCode" placeholder="请输入" clearable/>
        </el-form-item>
        <el-form-item label="apk应用包地址：" required prop="apkUrl">
          <el-input v-model="formEdit.apkUrl" placeholder="请输入" clearable/>
        </el-form-item>
        <el-form-item label="更新提示：" required prop="updateTips">
          <el-input v-model="formEdit.updateTips" placeholder="请输入" clearable/>
        </el-form-item>
      </el-form>
    </Layer>
  </div>
</template>
<script setup>
import {onBeforeMount, ref, reactive} from "vue";
import {ElMessage} from "element-plus";
import {useGetDictList} from "@/hooks/useGetDictList.js";
import {
  channelAddOne,
  channelDeleteOne,
  channelUpdateOne,
  appList,
  saveOrUpdate,
  delApp, channelList,
} from "@/api/formworkErection.js";
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import Layer from "@/components/layer/index.vue";
import {CopyDocument, Hide, View} from "@element-plus/icons-vue";
import vCopy from '@/directive/copy'

const {loadDictData, getDictionaryName} = useGetDictList();
const tableData = ref([]);
const channelData = ref([]);
// 在 setup() 中
const selectRow = ref([]); // 存储选中的行

// 分页参数, 供table使用
const page = reactive({
  pageNum: 1,
  pageSize: 20,
  limit: 20,
  total: 0,
});


const channelPage = reactive({
  pageNum: 1,
  pageSize: 20,
  limit: 20,
  total: 0,
});

const formSearch = ref({
  appName: null,
  channelName: null,
  appType: null,

  limit: 20, // 当前页数量(查询量)
  page: 1, // 当前页码
  pageSizes: 20, // 总页数
});

const channelSearch = ref({
  limit: 20, // 当前页数量(查询量)
  page: 1, // 当前页码
  pageSizes: 20, // 总页数
});

const dynamicFormItems = ref([]);

onBeforeMount(() => {
  settingData();
  getList();
  getChannelList();
});



// 获取缓存数据设置筛选数据
const settingData = () => {
  loadDictData().then(() => {
    dynamicFormItems.value = [
      {
        label: "应用名称",
        prop: "appName",
        type: "input",
      },
      {
        label: "广告渠道",
        prop: "channelName",
        type: "input",
      },
      {
        label: "应用类型",
        prop: "appType",
        type: "select",
        options: [
          {
            label: "全部",
            value: null,
          },
          {
            label: "Android",
            value: 1,
          },
          {
            label: "IOS",
            value: 2,
          },
        ],
      },
    ];
  });
};

// 分页数据
const getList = async () => {
  let res = await appList({...formSearch.value});
  tableData.value = res.data;
  page.total = res.pageMeta.total;
};

const changeTableData = () => {
  formSearch.value.pageNum = page.pageNum;
  formSearch.value.pageSize = page.pageSize;
  formSearch.value.limit = page.limit;
  // 分页切换
  getList();
};


const getChanelData = () => {
  channelSearch.value.pageNum = channelPage.pageNum;
  channelSearch.value.pageSize = channelPage.pageSize;
  channelSearch.value.limit = channelPage.limit;
  // 分页切换
  getChannelList();
};

// 分页数据
const getChannelList = async () => {
  let res = await channelList({ ...channelSearch.value });
  channelData.value = res.data;
  channelPage.total = res.pageMeta.total;
};


// 搜索
const handleFormSubmitted = (formData) => {
  console.log("接收到子组件传递的数据", formData);
  formSearch.value.page = 1;
  formSearch.value.pageSizes = 20;
  formSearch.value.limit = 20;

  formSearch.value.channelName = formData?.channelName;
  formSearch.value.appName = formData?.appName;
  formSearch.value.appType = formData?.appType;

  getList();
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    appName: null,
    channelName: null,
    appType: null,

    limit: 20, // 当前页数量(查询量)
    page: 1, // 当前页码
    pageSizes: 20, // 总页数
  };
  getList();
};

// 选择监听器
const handleSelectionChange = (val) => {
  context.emit("selection-change", val);
};

const handleChannelSelectionChange = (val) => {
  console.log("获取渠道", val);
  selectRow.value = val;
  console.log(selectRow.value)
};

// 弹窗
const layer = ref({
  show: false,
  title: "新增App",
  showButton: true,
  width: "50vw",
  edit: false,
});

const channelLayer = ref({
  show: false,
  title: "关联渠道",
  showButton: true,
  width: "50vw",
  edit: false,
});

const formEdit = ref({
  store_on_sale: "",
  store_type: null,
  store_url: "",
  category: "",
  sub_category: "",
  screen_orientation: "",
  versionCode: "",
  updateTips: "",
  apiSecret: "", //请求密令
  channelAccount: "", //渠道账号
  channelId: "", //渠道ID
  channelName: "", //渠道名称
  channelPwd: "", //渠道密码
  channelStatus: 0, //渠道状态
  loginType: 0, //登录类型 1-账号密码 2-微信
  remark: "", //备注
  appId: "",
  apiKey: "", //请求秘钥
  appName: "",
  coppa: 0,
  ccpa: 0,
  qrCode: "",
  apkUrl: "",
  package_name: "",
});

const edit = (row) => {
  ruleForm.value?.resetFields();
  if (row) {
    layer.value.title = "编辑APP";
    layer.value.edit = true;
    formEdit.value = row;
    formEdit.value.store_on_sale = row.storeOnSale;
    formEdit.value.store_type = row.storeType;
    formEdit.value.package_name = row.packageName;
    formEdit.value.store_url = row.storeUrl;
    formEdit.value.sub_category = row.subCategory;
    formEdit.value.screen_orientation = row.screenOrientation;
  } else {
    layer.value.title = "新增APP";
    layer.value.edit = false;
    formEdit.value = {};
  }
  layer.value.show = true;
};

const openChannelLayer = (row) => {
  if (row) {
    channelLayer.value.show = true;
  }

}

const ruleForm = ref(null);

const rules = reactive({});

const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 提交内容
      if (layer.value.edit) {
        //api修改需要uuid
        formEdit.uuid = formEdit.appId;
      }
      const result = await saveOrUpdate({...formEdit.value});
      console.log(result)
      if (result.code === 200) {
        if (layer.value.edit) {
          ElMessage.success("修改成功");
          layer.value.show = false;
        } else {
          ElMessage.success("新增成功");
          layer.value.show = false;
        }
        handleFormSubmitted();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 删除
const removeApp = async (row) => {
  await delApp({appId: row.appId}).then((res) => {
    ElMessage.success("删除成功");
    handleFormSubmitted();
  });
};
</script>

<style scoped lang="scss">
.layout-container {
  .card {
    .title {
      margin-bottom: 10px;
      font-weight: 600;
    }

    display: flex;
    flex-direction: column;
    align-items: start;
    width: calc(100% - 60px);
    margin: 30px 30px 0;
  }

  .button {
    display: flex;
    flex-direction: column;

    .button-item {
      margin: 4px;
    }
  }
}
</style>