<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" :is_add_button="checkPermission('permission') ? '新增风控配置' : null" @addForm="edit" @formSubmitted="handleFormSubmitted"
      @formReset="handleFormReset" />

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column prop="index" label="序号" width="60" /> -->
        <el-table-column prop="enabled" label="是否启用" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.enabled === 1 ? 'success' : 'danger'" effect="dark">
              {{ getDictionaryName('enabled',scope.row.enabled) || '未启用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="appNames" label="关联应用" width="120">
          <template #default="scope">
            {{scope.row.canModify? scope.row.appNames : '系统配置全应用生效'}}
          </template>
        </el-table-column>
        <el-table-column prop="appIds" label="关联应用ID" width="150">
          <template #default="scope">
            {{scope.row.canModify? scope.row.appIds : '系统配置全应用生效'}}
          </template>
        </el-table-column>
        <el-table-column prop="templateCode" label="配置编码" width="180" />
        <el-table-column prop="templateContent" label="配置内容" width="200">
          <template #default="scope">
            <el-popover
              class="box-item"
              :title="`${scope.row.templateName}的配置内容`"
              :width="400"
              placement="top-start"
            >
              <template #reference>
                {{ scope.row.templateContent }}
              </template>
              <div v-html="scope.row.templateContent.split(',').filter(Boolean).map(item => item.trim()).join('<br/>')"></div>
          </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="allSatisfy" label="条件范围" width="100">
            <template #default="scope">
              {{getDictionaryName('all_satisfy', scope.row.allSatisfy)}}
            </template>
        </el-table-column>
        <el-table-column prop="effectNode" label="业务节点" width="100">
            <template #default="scope">
              {{getDictionaryName('effect_node', scope.row.effectNode)}}
            </template>
        </el-table-column>
        <el-table-column prop="templateId" label="配置模版ID" width="160" />
        <el-table-column prop="templateName" label="配置名称" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="创建人" width="90" />
        <el-table-column prop="updateTime" label="修改时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateNickName" label="修改者" width="90" />

        <el-table-column label="操作" width="170" v-permission="'permission'">
          <template #default="scope">
            <div class="button">
              <el-link v-if="scope.row.canModify" class="button-item" type="primary" @click="edit(scope.row)">
                编辑
              </el-link>
              <el-link v-if="scope.row.canModify" class="button-item" type="success" @click="relativeApp(scope.row)">
                关联应用
              </el-link>
              <el-link v-if="scope.row.canModify" :type="scope.row.enabled ? 'danger' : ''" class="button-item"
                @click="enabledConfig(scope.row)">
                {{scope.row.enabled ? '关闭' : '开启'}}
              </el-link>
            </div>
          </template>
        </el-table-column>
      </Table>
    </div>

    <!-- 操作弹窗 -->
    <ConfigForm :layer="layer" @confirm="submit" @close="close" />

    <Layer :layer="layer1" @confirm="submit1(ruleForm)" @close="layer1.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="160px" style="margin-right:30px;">
        <el-form-item required label="应用列表：" prop="appList">
          <el-select multiple v-model="formEdit.appList" placeholder="请选择类型" filterable style="width: 400px;">
            <el-option v-for="item in appListData" :key="item.appId" :label="item.appName"
              :value="item.appId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </Layer>


  </div>
</template>

<script setup>
  import { onBeforeMount, ref, nextTick, reactive } from "vue";
  import From from "@/components/from/index.vue";
  import Table from "@/components/table/index.vue";
  import Layer from '@/components/layer/index.vue'
  import ConfigForm from './components/configForm.vue'

  import { ElMessage } from 'element-plus'
  import {
    riskConfigList, riskRelativeApps, riskSaveConfig, riskOptions,
    riskEnabledConfig, riskTemplateView, riskUpdateConfig
  } from '@/api/riskModule.js'
  import { getEnabledList } from '@/api/userModule.js'
  import { convertUTCToBeijing } from '@/utils/index.js'
  import { useGetDictList } from '@/hooks/useGetDictList.js'
  import { useStore } from 'vuex'
  import { usePermission } from '@/hooks/usePermission.js'

  const { checkPermission } = usePermission()
  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({
    appId: '',// 渠道来源关联的应用ID
    available: null,//是否生效-

    configList: null,// 风控配置列表
    channelId: null,//渠道商ID
    configId: '',// 配置ID
    configType: 0,// 配置类型 1-输入框 2-选择框 3-日期
    configVal: '',// 配置值
    fieldDesc: '',// 字段描述
    fieldName: '',// 字段名称
    multy: null, //是否多个

    createTime: '',// 创建时间
    createUserId: '',// 创建人ID－
    defaultParam: '',// 默认参数-
    updateParam: null,// 用户类型
    updateTime: null,// 用户类型
    updateUserId: null,// 用户类型

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

  const dynamicFormItems = ref([])

  onBeforeMount(async () => {
    await getEnabledListData()
    await settingData()
    await getList();
    await getRiskOptions()
  });

  // 获取缓存数据设置筛选数据
  const settingData = () => {
    loadDictData().then(() => {
      dynamicFormItems.value = [
        {
          label: 'APP应用',
          prop: 'appId',
          type: 'select',
          options: appListOptions.value,
        },
      ]
    })
  }

  const appListData = ref([])
  const appListOptions = ref([])
  const getEnabledListData = async () => {
    let res = await getEnabledList()
    // appListData.value = res.data
    appListOptions.value = res.data.map(item => ({
      label: item.appName,
      value: item.appId
    }))

    appListData.value = res.data.map(item => ({
      appName: item.appName,
      appId: item.appId
    }))

    dynamicFormItems.value = [
      {
        label: 'APP应用',
        prop: 'appId',
        type: 'select',
        options: appListOptions.value,
      },
    ]
  }


  // 分页数据
  const getList = async () => {
    let res = await riskConfigList({ ...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.appId = formData.appId

    getList();
  };

  // 表单重置
  const handleFormReset = () => {
    formSearch.value = {
      appId: '',// 渠道来源关联的应用ID
      available: null,//
      channelId: null,//
      configId: '',// 配置ID
      configList: null,// 风控配置列表
      configType: 0,// 配置类型 1-输入框 2-选择框 3-日期
      configVal: '',// 配置值
      createTime: '',// 
      createUserId: '',// 
      defaultParam: '',// 
      fieldDesc: '',// 字段描述
      fieldName: '',// 字段名称
      limit: 20,// 当前页数量(查询量)
      multy: null, //是否多个
      updateParam: null,// 用户类型
      updateTime: null,// 用户类型
      updateUserId: null,// 用户类型

      page: 1,// 当前页码
      pageSizes: 20,// 总页数
      superAdmin: null,//
      total: null,// 总条数
    };
    page.pageNum = 1
    page.pageSize = 20
    page.total = 0
    
    getList();
  };

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

  // #region 新增/编辑风控配置

  // 弹窗
  const layer = ref({
    show: false,
    title: "配置风控表单",
    showButton: true,
    width: '60%',
    height: '60vh',
    optionsData: [],
    configDataList: {},
    templateId: '',
    disabled: false
  });

  // 查询配置字段选项列表
  const riskOptionsData = ref([])
  const getRiskOptions = async () => {
    let res = await riskOptions({appIds: appListData.value.map(item=>item.appId).join(",")})
    riskOptionsData.value = res.data
    layer.value.optionsData = res.data
  }

  const edit = async (row) => {
    layer.value.show = true
    if (row) {
      layer.value.title = '编辑配置'
      layer.value.disabled = true
      layer.value.templateId = row.templateId
    } else {
      layer.value.title = '配置风控表单'
      layer.value.disabled = false
    }
  }

  const close = () => {
    layer.value.show = false
  }

  const submit = async (data, isEdit) => {
    data.channelId = store.state.user.info.userId //渠道id就是用户的userId
    data.configList.forEach((item, index) => {
      data.configList[index].configType = Number(item.configType)
      data.configList[index].configVal = String(item.configVal)
      data.configList[index].multy = Number(item.multy)
    })

    // 编辑
    if (isEdit) {
      let res = await riskUpdateConfig({ ...data })
      if (res.code === 200) {
        ElMessage.success('配置保存成功')
        getList();
      }
    } else {
      let res = await riskSaveConfig(
        {
          configList: data.configList,
          templateName: data.templateName,
          templateContent: data.templateContent,
          templateCode: data.templateCode,
          allSatisfy: data.allSatisfy,
          effectNode: data.effectNode
        })
      if (res.code === 200) {
        ElMessage.success('配置保存成功')
        getList();
      }
    }
  }

  // #endregion

  // #region  风控配置关联应用
  const layer1 = ref({
    show: false,
    title: "关联应用",
    showButton: true,
    width: 300,
  });

  const formEdit = ref({
    appList: {}, //appId list
    operator: '',//操作人
    operatorName: '',//操作人名称
    templateId: '', //关联的配置模版ID
  })

  const relativeApp = (row) => {
    ruleForm.value?.resetFields()
    layer1.value.show = true
    formEdit.value.operator = store.state.user.info.loginName
    formEdit.value.operatorName = store.state.user.info.nickName
    formEdit.value.templateId = row.templateId
    formEdit.value.appList = []
  }

  const ruleForm = ref(null);

  const rules = reactive({
    appList: [
      {
        required: true,
        message: "请选择应用",
        trigger: "change",
      },
    ],
  });

  const submit1 = async (formEl) => {
    const result = appListData.value.filter(app => formEdit.value.appList.includes(app.appId));
    // console.log('result', result)

    formEdit.value.appList = result
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        // 提交内容
        riskRelativeApps(formEdit.value).then((res) => {
          ElMessage.success('关联应用成功')
          layer1.value.show = false;
          getList();
        })
      } else {
        console.log("error submit!", fields);
      }
    })
  }
  // #endregion

  // 启用或关闭配置
  const enabledConfig = async (row) => {
    let res = await riskEnabledConfig({ templateId: row.templateId })
    if (res.code == 200) {
      ElMessage.success('更改成功')
      getList();
    }
  }


</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>