<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" 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="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="edit(scope.row)">
                编辑
              </el-button>
              <el-popconfirm placement="left" title="确认删除该数据?" @confirm="removeAgency(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="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right: 30px">
        <el-form-item label="请求秘钥：" required prop="apiKey">
          <el-input v-model="formEdit.apiKey" type="number" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="请求密令：" required prop="apiSecret">
          <el-input v-model="formEdit.apiSecret" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="渠道ID：" required prop="channelId">
          <el-input v-model="formEdit.channelId" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="渠道名称：" required prop="channelName">
          <el-input v-model="formEdit.channelName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="渠道账号：" required prop="channelAccount">
          <el-input v-model="formEdit.channelAccount" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="渠道密码：" required prop="channelPwd">
          <el-input v-model="formEdit.channelPwd" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="渠道状态：" required prop="channelStatus">
          <el-input v-model="formEdit.channelStatus" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="登录类型：" required prop="loginType">
          <el-input v-model="formEdit.loginType" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="备注：" required prop="remark">
          <el-input v-model="formEdit.remark" placeholder="请输入" clearable />
        </el-form-item>
      </el-form>
    </Layer>
  </div>
</template>
<script setup>
  import { onBeforeMount, ref, reactive } from "vue";
  import { ElMessage } from "element-plus";
  import { useStore } from "vuex";
  import { useGetDictList } from "@/hooks/useGetDictList.js";
  import { channelAddOne, channelDeleteOne, channelUpdateOne, appList,} 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 store = useStore();
  const { dictData, loadDictData, getOptions, getDictionaryName } = useGetDictList();
  const form = ref(null);
  const tableData = ref([
  ]);

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

  const formSearch = ref({
    channelId: null, // 渠道ID
    channelName: null, // 渠道名称
    channelAccount: "", // 渠道账号
    channelStatus: null, // 渠道状态
    loginType: null, // 登录类型

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

  const dynamicFormItems = ref([]);

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

  // 获取缓存数据设置筛选数据
  const settingData = () => {
    loadDictData().then(() => {
      dynamicFormItems.value = [
        {
          label: "渠道ID",
          prop: "channelId",
          type: "input",
        },
        {
          label: "渠道名称",
          prop: "channelName",
          type: "input",
        },
        {
          label: "渠道账号",
          prop: "channelAccount",
          type: "input",
        },
        {
          label: "渠道状态",
          prop: "channelStatus",
          type: "select",
          options: [
            {
              label: "全部",
              value: null,
            },
            {
              label: "是",
              value: 0,
            },
            {
              label: "否",
              value: 1,
            },
          ],
        },
        {
          label: "登录类型",
          prop: "loginType",
          type: "select",
          options: [
            {
              label: "全部",
              value: null,
            },
            {
              label: "账号密码",
              value: 1,
            },
            {
              label: "微信",
              value: 2,
            },
          ],
        },
        // { label: '登录日期', prop: 'loginTime', type: 'daterange' },
      ];
    });
  };

  // 分页数据
  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 handleFormSubmitted = (formData) => {
    // console.log("接收到子组件传递的数据", formData);
    formSearch.value.page = 1;
    formSearch.value.pageSizes = 20;
    formSearch.value.limit = 20;

    formSearch.value.channelId = formData.channelId;
    formSearch.value.channelName = formData.channelName;
    formSearch.value.channelAccount = formData.channelAccount;
    formSearch.value.channelStatus = formData.channelStatus;
    formSearch.value.loginType = formData.loginType;
    formSearch

    getList();
  };

  // 表单重置
  const handleFormReset = () => {
    formSearch.value = {
      channelId: null, // 渠道ID
      channelName: null, // 渠道名称
      channelAccount: "", // 渠道账号
      channelStatus: null, // 渠道状态
      loginType: null, // 登录类型

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

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

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

  const formEdit = ref({
    apiKey: "", //请求秘钥
    apiSecret: "", //请求密令
    channelAccount: "", //渠道账号
    channelId: "", //渠道ID
    channelName: "", //渠道名称
    channelPwd: "", //渠道密码
    channelStatus: 0, //渠道状态
    loginType: 0, //登录类型 1-账号密码 2-微信
    remark: "", //备注
  });

  const edit = (row) => {
    ruleForm.value?.resetFields();
    if (row) {
      layer.value.title = "编辑代理";
      layer.value.edit = true;
      formEdit.value = row;
    } else {
      layer.value.title = "新增代理";
      layer.value.edit = false;
      formEdit.value = {};
    }
    layer.value.show = true;
  };

  const ruleForm = ref(null);

  const rules = reactive({
    /*  formEditbannedLimit: [
               { required: true, message: "请输入封禁期限", trigger: "blur" },
           ],
           bannedReason: [
               {
                   required: true,
                   message: "请输入封禁原因",
                   trigger: "blur",
               },
           ], */
  });

  const submit = async (formEl) => {
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        // 提交内容
        if (layer.value.edit) {
          await channelUpdateOne({ ...formEdit.value });
        } else {
          await channelAddOne({ ...formEdit.value });
        }
        ElMessage.success("新增成功");
        layer.value.show = false;
      } else {
        console.log("error submit!", fields);
      }
    });
  };

  // 删除
  const removeAgency = async (row) => {
    await channelDeleteOne({ channelId: row.channelId }).then((res) => {
      ElMessage.success("删除成功");
    });
  };
</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>