<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="channelId" label="平台ID" />
        <el-table-column prop="channelName" label="平台名称" width="100" />
        <el-table-column prop="loginType" label="登录类型" width="100" >
          <template #default="scope">
            {{getDictionaryName("login_type",scope.row.loginType)}}
          </template>
        </el-table-column>
        <el-table-column prop="channelAccount" label="平台账号" width="150" />
        <el-table-column prop="channelPwd" label="平台密码" width="120" />
        <el-table-column prop="channelStatus" label="平台状态" width="100" >
          <template #default="scope">
            {{getDictionaryName("channel_status", scope.row.channelStatus)}}
          </template>
        </el-table-column>
        <el-table-column prop="apiKey" label="API秘钥"  />
        <el-table-column prop="apiSecret" label="API密令" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <div class="button">
              <el-link class="button-item" type="primary" style="margin-bottom: 5px;" @click="edit(scope.row)">
                编辑
              </el-link>
              <el-popconfirm placement="left" title="确认删除该数据?" @confirm="removeItem(scope.row)">
                <template #reference>
                  <el-link class="button-item" style="margin-bottom: 5px;" type="danger">删除</el-link>
                </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-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="登陆类型" required  prop="loginType">
              <el-select v-model="formEdit.loginType">
                <el-option :value="1" label="账号密码"/>
                <el-option :value="2" label="微信"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="广告平台类型" required prop="adPlatformType">
              <el-select v-model="formEdit.adPlatformType">
                <el-option :value="15" label="穿山甲"/>
                <el-option :value="8" label="腾讯广告"/>
                <el-option :value="22" label="百度联盟"/>
                <el-option :value="28" label="快手"/>
                <el-option :value="29" label="Sigmob"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="平台账号：" required prop="channelAccount">
              <el-input v-model="formEdit.channelAccount" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="平台密码：" required prop="channelPwd">
              <el-input v-model="formEdit.channelPwd" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="平台状态：" required prop="channelStatus">
              <el-select v-model="formEdit.channelStatus">
                <el-option :value="1" label="正常"/>
                <el-option :value="2" label="锁定"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="请求密钥：" required prop="apiKey">
              <el-input v-model="formEdit.apiKey" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="请求密令：" required prop="apiSecret">
              <el-input v-model="formEdit.apiSecret" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="备注：" required prop="remark">
              <el-input v-model="formEdit.remark" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Layer>
  </div>
</template>

<script setup>
  import { onBeforeMount, ref, reactive } from "vue";
  import From from "@/components/from/index.vue";
  import Table from "@/components/table/index.vue";
  import { useGetDictList } from '@/hooks/useGetDictList.js'
  import { useStore } from 'vuex'
  import {channelAddOne, channelDeleteOne, channelList, channelUpdateOne, delApp} from "@/api/formworkErection";
  import Layer from "@/components/layer/index.vue";
  import {ElMessage} from "element-plus";

  const store = useStore()
  const { dictData, loadDictData, getOptions, getDictionaryName } = useGetDictList();
  const form = ref(null);
  const tableData = ref([]);

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

  const formSearch = ref({
    channelId: null,//平台ID
    channelName:null,//平台名称
    loginType:null,//登录类型
    channelStatus: null,//平台状态
    page: 1,// 当前页码
    limit: 20,// 当前页数量(查询量)
  });

  const dynamicFormItems = ref([])

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

  // 获取缓存数据设置筛选数据
  const settingData = () => {
    loadDictData().then(() => {
      dynamicFormItems.value = [
        {
          label: '平台ID',
          prop: 'channelId',
          type: 'input',
          needEnterEvent: true
        },
        {
          label: '平台名称',
          prop: 'channelName',
          type: 'input',
          needEnterEvent: true
        },
        {
          label: '平台状态',
          prop: 'channelType',
          type: 'select',
          options: getOptions('channel_status')
        },
      ]
    })
  }

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

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

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

    getList();
  };

  // 表单重置
  const handleFormReset = () => {
    formSearch.value = {
      channelId: null,//平台ID
      channelName:null,//平台名称
      loginType:null,//登录类型
      channelStatus: null,//平台状态
      page: 1,// 当前页码
      limit: 20,// 当前页数量(查询量)
    };
    page.pageNum = 1
    page.pageSize = 20
    page.total = 0
    getList();
  };

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

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

  const formEdit = ref({
    channelId: '',
    channelName: '',
    loginType: undefined,
    adPlatformType:undefined,
    channelAccount:undefined,
    channelPwd:undefined,
    channelStatus:undefined,
    apiKey:undefined,
    apiSecret:undefined,
    remark:undefined
  })
  const reset = () => {
    formEdit.value = {
      channelId: '',
      channelName: '',
      loginType: undefined,
      adPlatformType: undefined,
      channelAccount: undefined,
      channelPwd: undefined,
      channelStatus: undefined,
      apiKey: undefined,
      apiSecret: undefined,
      remark: undefined
    }
  }

  const edit = (row) => {
    ruleForm.value?.resetFields()
    if (row) {
      formEdit.value = { ...row }
      layer.value.edit = true;
      layer.value.title = '编辑广告渠道'
    } else {
      reset();
      layer.value.title = '新增广告渠道'
    }
    layer.value.show = true
  }

  const ruleForm = ref(null);

  const rules = reactive({
    loginType: [
      { required: true, message: "请选择登陆类型", trigger: "change" },
    ],
    adPlatformType: [
      { required: true, message: "请选择广告平台类型", trigger: "change" },
    ],
    channelAccount: [
      { required: true, message: "请输入渠道账号", trigger: "blur" },
    ],
    channelPwd: [
      { required: true, message: "请输入渠道密码", trigger: "blur" },
    ],
    channelStatus: [
      { required: true, message: "请选择渠道状态", trigger: "change" },
    ],
    apiKey: [
      { required: true, message: "请输入请求密钥", trigger: "blur" },
    ],
    apiSecret: [
      { required: true, message: "请输入请求密令", trigger: "blur" },
    ],
    remark: [
      { required: true, message: "请输入备注", trigger: "blur" },
    ],
  });

  const submit = async (formEl) => {
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        // 提交内容
        let result = null;
        if (layer.value.edit) {
          result=await channelUpdateOne({...formEdit.value});
        }
        else {
          console.log(formEdit.value);
          result=await channelAddOne({...formEdit.value})
        }
        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 removeItem = async (row) => {
    console.log('删除', row)
    await channelDeleteOne({channelId: row.channelId}).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>