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

  <a-modal v-model:visible="deleteShow" title="删除原因" @ok="handleDeleteOk" @cancel="deleteShow = false">
     <a-textarea v-model:value="deleteForm.scyy" placeholder="请输入删除原因" :rows="4"  style="margin:20px;width:90%;"/>
  </a-modal>

  <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, deleteZjYj } 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();

const deleteShow = ref(false)
const deleteForm = ref({
  zjcyId: '',
  cqdkId: '',
  scyy: ''
})
  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) {
    // console.log(record,'信息')
    deleteShow.value = true
    deleteForm.value = {
      zjcyId: record.id,
      cqdkId: cqdkId.value,
      scyy: ''
    }
  }

  async function handleDeleteOk() {
    if (!deleteForm.value.scyy) {
      createMessage.warning('删除原因不能为空');
      return
    }

    deleteZjYj(deleteForm.value).then(res => {
      console.log(res,'是的发生的')
      if (res) {
        dataList.value.forEach((v: any, index) => {
          if (v.id == deleteForm.value.zjcyId) {
            dataList.value.splice(index, 1);
            deleteShow.value = false
            deleteForm.value = {
              zjcyId: '',
              cqdkId: '',
              scyy: ''
            }
          }
        });
      }
    })
    
  }

  //提交事件
  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>
