<template>
  <BasicModal v-bind="$attrs" @register="registerModal" @cancel="handleCancel" title="抽取" width="70%">
    <a-space wrap class="py-5">
      <a-button type="primary" @click="handle('')"> 随机抽取</a-button>
      <a-button type="primary" @click="handle('add')"> 添加</a-button>
    </a-space>
    <a-table :columns="sjcolumns" :data-source="dataList">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'opera'">
          <a-space wrap>
            <a-button type="primary" @click="handleDelete(record)"> 删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <template #footer>
      <div class="w-full text-center">
        <a-space wrap>
          <a-button type="primary" class="mr-8" @click="handleSubmit('save')">保存</a-button>
          <a-button type="primary" class="mr-8" @click="handleSubmit('')">提交</a-button>
          <a-button @click="closeModal()">取消</a-button>
        </a-space>
      </div>
    </template>
  </BasicModal>

  <SjcqModal @register="registerSjModal" @success="handleSuccess"></SjcqModal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import SjcqModal from './SjcqModal.vue';
  import { Modal } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { sjcolumns } from '../GZjcyb.data';
  import { getCqZjList, sjcq, saveOrUpdateCc } from '../GZjcyb.api';
  import { decryptData } from '/@/api/common/api';

  const cqdkId = ref();
  const dataList = ref<any>([]);
  const zyfxCodes = ref('');
  const emit = defineEmits(['register', 'success']);
  // 提示
  const { createMessage } = useMessage();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    // 刷新列表
    console.log(data.record);
    cqdkId.value = data.record.cqdkId;
    zyfxCodes.value = data.record.cqzyfx;
    init();
  });
  //注册model
  const [registerSjModal, { openModal }] = useModal();

  async function init() {
    const res = await getCqZjList({ cqdkId: cqdkId.value });
    dataList.value = res.records;
    decry();
  }
  // 事件
  async function handle(v) {
    if (v == 'add') {
      let noZjIds;
      if (dataList.value.length > 0) {
        noZjIds = dataList.value.filter((item: any) => item.id).map((item: any) => item.id);
      }

      openModal(true, {
        record: { cqdkId: cqdkId.value, zyfxCodes: zyfxCodes.value, noZjIds: noZjIds ? noZjIds.toString() : '' },
        showFooter: true,
      });
    } else {
      dataList.value = await sjcq({ cqdkId: cqdkId.value });
      decry();
    }
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    dataList.value.forEach((v: any, index) => {
      if (v.id == record.id) {
        dataList.value.splice(index, 1);
      }
    });
  }

  //提交事件
  async function handleSubmit(v) {
    if (dataList.value.length == 0) {
      createMessage.info('请选择需要处理的内容');
      return;
    }

    try {
      let noZjIds;
      setModalProps({ confirmLoading: true });
      noZjIds = dataList.value.filter((item: any) => item.id || item.zjcyId).map((item: any) => item.id || item.zjcyId);
      const params = {
        cqdkId: cqdkId.value,
        zjcyId: noZjIds.toString(),
      };
      if (!v) {
        Modal.confirm({
          title: '确认提交',
          content: '提交之后，此次抽取结束！如未确认最终名单，请点击保存！',
          centered: true,
          okText: '确认',
          cancelText: '取消',
          onOk: async () => {
            await saveOrUpdateCc(params, v);
            //刷新列表
            emit('success');
          },
        });
      } else {
        await saveOrUpdateCc(params, v);
        //刷新列表
        emit('success');
      }

      //关闭弹窗
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  // 获取子组件的选中的值
  function handleSuccess(v) {
    console.log(v.value, 'v');
    if (v.value && v.value.length > 0) {
      dataList.value = [...dataList.value, ...v.value];
      decry();
    }
  }
  // 解密
  function decry() {
    dataList.value.forEach((record) => {
      const rule = /^[0-9]+$/.test(record.lxdh);

      if (record.lxdh) {
        if (!rule) {
          const regex = /[*]/.test(record.lxdh);

          if (!regex) {
            decryptData({ str: record.lxdh }).then((res) => {
              record.lxdh = res.replace(res.substring(3, 7), '****');
            });
          }
        } else {
          record.lxdh = record.lxdh.replace(record.lxdh.substring(3, 7), '****');
        }
      }
    });
  }
  function handleCancel() {
    closeModal();
    dataList.value = [];
  }
</script>
