<template>
  <BasicDrawer v-bind="$attrs" :title="pageTitle" @close="closeDrawer" @register="registerDrawer" width="100%" destroyOnClose>
    <div class="drawer-content">
      <vxe-toolbar ref="toolbarRef" :buttons="toolbarButtons" @button-click="handleToolbarClick" custom export :refresh="{ queryMethod }" print />

      <vxe-table
        border
        keep-source
        ref="tableRef"
        size="small"
        :custom-config="{}"
        :print-config="{}"
        :export-config="{}"
        height="100%"
        :data="tableData"
        :show-radio="true"
        :row-config="{ isCurrent: true, isHover: true }"
        :column-config="{ resizable: true }"
        :scroll-y="{ enabled: true, gt: 50 }"
        :radio-config="{ labelField: 'name', highlight: true }"
        :loading="loading"
      >
        <vxe-column type="checkbox" width="50" />

        <vxe-column field="targitTp" width="10%" sortable title="分类">
          <template #default="{ row }">
            <span>{{ formattargitTp(row) }}</span>
          </template>
        </vxe-column>
        <vxe-column field="tname" sortable title="监管要求" />
        <vxe-column field="comeFrom" width="10%" title="来源" />
        <vxe-column field="createBy" title="" :visible="false" />
        <vxe-column field="createTime" title="" :visible="false" />
        <vxe-column field="id" title="" :visible="false" />
        <vxe-column title="操作" fixed="right" width="10%">
          <template #default="{ row }">
            <vxe-button @click="handleDetail(row)">详情</vxe-button>
            <vxe-button @click="handleDelete(row)">删除</vxe-button>
          </template>
        </vxe-column>
      </vxe-table>

      <vxe-pager v-model:currentPage="pageVO.currentPage" v-model:pageSize="pageVO.pageSize" :total="pageVO.total" @page-change="handlePageChange" />

      <vxe-modal
        resize
        destroy-on-close
        show-confirm-button
        show-cancel-button
        v-model="showAuditWindow"
        title="内控要求库列表"
        width="60vw"
        height="80vh"
        :confirm-closable="false"
      >
        <vxe-grid ref="refAuditGrid" v-bind="gridAuditOptions" keep-source :radio-config="{ highlight: true }" size="small">
          <template #toolbar_buttons>
            <vxe-button status="primary" @click="insertAuditEvent">保存</vxe-button>
            <vxe-input
              v-model="srhContent"
              type="search"
              placeholder="请输入"
              clearable
              @keyup.enter="handleSearch()"
              style="width: 35%; margin-left: 100px"
            />
            <a-button type="link" @click="handleSearch()">搜索</a-button>
            <a-button type="link" @click="handleRefresh()">刷新</a-button>
          </template>
        </vxe-grid>
      </vxe-modal>
    </div>
  </BasicDrawer>
  <!-- 选择依据组件 -->
  <BasicCtrlSelector ref="selectorRef" @save="insertAuditEvent" />
  <!-- 依据详情抽屉 -->
  <AuditInnerDetailDrawer ref="AuditInnerDetailDrawerRef" :visible="showDetailDrawer" @close="showDetailDrawer = false" />
  <!-- 发起计划 -->
  <StPlanManModal @register="registerInnerModal" :showSelectorBtn="false" />
</template>

<script lang="ts" setup>
  import { ref, reactive, h } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { getAllCheckMethod, alllist, deleteOne, batchDelete, saveBatch, queryAllMetric, saveOrUpdate } from '../WbCheckItem.api';
  import { VxePagerEvents } from 'vxe-pc-ui';
  import { VxeUI, VxeToolbarPropTypes, VxeToolbarEvents, VxeToolbarInstance, VxeTableInstance, VxeGridProps, VxeColumnPropTypes } from 'vxe-table';
  import { list } from '/@/views/newlib/components/api/AuditInnerCtrl.api';
  import { listAll } from '/@/views/newlib/components/api/AuditInnerCtrlItem.api';
  import AuditInnerDetailDrawer from '/@/views/newlib/components/modal/AuditInnerDetailDrawer.vue';
  import StPlanManModal from '/@/views/project/plan/components/StPlanManModal.vue';
  //注册model
  const [registerInnerModal, { openModal }] = useModal();
  interface RowVO {
    id: number;
    auditName: string;
    name: string;
    method: string;
    des: string;
    mtrcIds?: string;
  }

  interface MetricItem {
    value: string | number;
    label: string;
  }

  const pageTitle = ref('');
  const wbCheck = ref<{ id: number; name: string }>();
  const loading = ref(false);
  const showAuditWindow = ref(false);
  const AuditInnerDetailDrawerRef = ref();
  const showDetailDrawer = ref(false);
  const tp = 1;

  const allData = ref<RowVO[]>([]);
  const tableData = ref<RowVO[]>([]);

  const toolbarRef = ref<VxeToolbarInstance>();
  const tableRef = ref<VxeTableInstance>();
  const refAuditGrid = ref();

  const emit = defineEmits(['rowChangeEvent', 'selector-click']);

  const pageVO = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 15,
  });

  const toolbarButtons = ref<VxeToolbarPropTypes.Buttons>([
    { name: '添加内控要求', code: 'addAudit', status: 'primary' },
    { name: '发起工作计划', code: 'addPlan', status: 'primary' },
    { name: '批量删除', code: 'del', status: 'error' },
  ]);

  const gridAuditOptions = reactive<VxeGridProps<RowVO>>({
    border: true,
    height: 'auto',
    columnConfig: {
      resizable: true,
    },
    columns: [
      { type: 'checkbox', visible: true, width: '50', showOverflow: false },
      {
        field: 'tpname',
        title: '分类',
        width: '10%',
        sortable: true,
      },
      {
        field: 'name',
        title: '内控要求',
        editRender: { name: 'input' },
        sortable: true,
        type: 'html',
      },
      {
        field: 'des',
        title: '说明',
        editRender: { name: 'input' },
        minWidth: '30%',
        type: 'html',
      },
      {
        field: 'id',
        title: '',
        visible: false,
      },
    ],
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    data: [],
  });

  const [registerDrawer] = useDrawerInner(async (data) => {
    wbCheck.value = data;
    pageTitle.value = `${data.name}-添加内控要求`;
    await Promise.all([iniData()]);
  });

  const handlePageData = async () => {
    loading.value = true;
    try {
      const { pageSize, currentPage } = pageVO;
      pageVO.total = allData.value.length;
      tableData.value = allData.value.slice((currentPage - 1) * pageSize, currentPage * pageSize);
    } finally {
      loading.value = false;
    }
  };

  const handlePageChange: VxePagerEvents.PageChange = ({ pageSize, currentPage }) => {
    pageVO.currentPage = currentPage;
    pageVO.pageSize = pageSize;
    handlePageData();
  };

  const closeDrawer = () => {
    // Handle drawer close if needed
  };
  const handleDetail = (item: any) => {
    const data = {
      name: item.tname,
      comeFrom: 2,
    };
    AuditInnerDetailDrawerRef.value?.open(data);
    showDetailDrawer.value = true;
  };
  const iniData = async () => {
    loading.value = true;
    try {
      if (!wbCheck.value?.id) return;

      const checkId = wbCheck.value.id;
      const data = await alllist({ checkId: checkId, tp: tp });
      allData.value = data;
      tableData.value = data;
      await handlePageData();
      await connectTable();
    } finally {
      loading.value = false;
    }
  };

  const queryMethod = async () => {
    await iniData();
  };

  const handleSuccess = async () => {
    await queryMethod();
  };

  const connectTable = async () => {
    const $table = tableRef.value;
    const $toolbar = toolbarRef.value;
    if ($table && $toolbar) {
      $table.connect($toolbar);
    }
  };

  const allAuditDatas = ref([]);
  const handleToolbarClick: VxeToolbarEvents.ButtonClick = async ({ code }) => {
    if (code === 'del') {
      await handleBatchDelete();
    } else if (code === 'addAudit') {
      await openBasisSelector();
    } else {
      await selectEvent();
    }
  };
  const selectEvent = async () => {
    const $table = tableRef.value;
    if ($table) {
      const selectRecords = $table.getCheckboxRecords();
      console.log(selectRecords, 'selectRecords');
      if (selectRecords.length > 0) {
        openModal(true, {
          isUpdate: false,
          showFooter: true,
          record: selectRecords,
        });
      } else {
        VxeUI.modal.message({
          content: '请选择数据',
          status: 'info',
        });
      }
    }
  };
  const handleDelete = async (row: RowVO) => {
    try {
      await deleteOne({ id: row.id }, handleSuccess);
    } catch (error) {
      VxeUI.modal.message({ content: '删除失败', status: 'error' });
    }
  };

  const handleBatchDelete = async () => {
    const ids = getSelectIds();
    if (ids.length === 0) {
      VxeUI.modal.message({ content: '请选择记录！', status: 'warning' });
      return;
    }
    try {
      batchDelete({ ids: ids.join(',') }, handleSuccess);
    } catch (error) {
      VxeUI.modal.message({ content: '批量删除失败', status: 'error' });
    }
  };
  const selectorRef = ref();
  const basisSelectorConfig = {
    title: '选择依据',
    columns: [
      { title: '内控文件名称', dataIndex: 'name' },
      { title: '说明', dataIndex: 'des' },
      { title: '创建时间', dataIndex: 'createTime' },
      { title: '创建人', dataIndex: 'createUser' },
      {
        title: '操作',
        key: 'action',
        customRender: ({ record }) => {
          return h(
            'a',
            {
              onClick: async () => {
                // 加载二级数据并更新组件中的表格
                const detailData = await listAll({ checkid: record.id });
                selectorRef.value.setDetail({
                  title: '详细内容',
                  columns: [
                    { title: '分类', dataIndex: 'tp', customRender: ({ record }) => formatTp(record) },
                    { title: '监管要求', dataIndex: 'name' },
                    { title: '来源', dataIndex: 'comeForm', customRender: ({ record }) => formatComeFrom(record) },
                    { title: '执行规则', dataIndex: 'exeRule', customRender: ({ record }) => formatExeRules(record) },
                  ],
                  data: detailData,
                  enableRowSelection: true,
                });
              },
            },
            '查看详情'
          );
        },
      },
    ],
    fetchData: async () => {
      const res = await list({ pageNo: 1, pageSize: 10 });
      return {
        records: res.records,
        total: res.total,
      };
    },
  };
  const openBasisSelector = async () => {
    const selected = await selectorRef.value.openSelector({
      multiple: true,
      config: basisSelectorConfig,
    });
  };

  const getSelectIds = (): number[] => {
    const ids: number[] = [];
    const $table = tableRef.value;
    if ($table) {
      const selRecords = $table.getCheckboxRecords();
      selRecords.forEach((ele) => {
        if (ele.id) {
          ids.push(ele.id);
        }
      });
    }
    return ids;
  };

  const insertAuditEvent = async (idAry) => {
    try {
      const params = idAry.map((id) => ({
        tid: id,
        checkId: wbCheck.value.id,
        tp: tp,
      }));
      await saveBatch(params);
      await handleSuccess();
    } catch (error) {
      VxeUI.modal.message({ content: '保存失败', status: 'error' });
    }
  };

  const formattargitTp = (row) => {
    return row.targitTp == 1 ? '工具要求' : row.targitTp == 2 ? '记录要求' : '制度要求';
  };
  const formatTp = (row) => {
    return row.tp == 1 ? '工具要求' : row.tp == 2 ? '记录要求' : '制度要求';
  };
  const formatComeFrom = (row) => {
    return row.comeFrom == 1 ? '自建' : row.tp == 2 ? '合规库' : '内控制度';
  };
  const formatExeRules = (row) => {
    return row.comeFrom == 1 ? '每发生' : row.tp == 2 ? '周期性' : '一次性';
  };

  const srhContent = ref();

  const handleSearch = () => {
    let srhTxt = srhContent.value;
    const filterSrhTxt = String(srhTxt).trim().toLowerCase();
    if (filterSrhTxt) {
      const filterRE = new RegExp(filterSrhTxt, 'gi');
      const searchProps = ['name', 'des'];
      let rest = allAuditDatas.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterSrhTxt) > -1));
      gridAuditOptions.data = rest.map((row) => {
        const item = Object.assign({}, row);
        searchProps.forEach((key) => {
          item[key] = String(item[key]).replace(filterRE, (match) => `<span style="color:red">${match}</span>`);
        });
        return item;
      });
    } else {
      gridAuditOptions.data = allData.value;
    }
  };

  const handleRefresh = async () => {
    const retData = await getAllCheckMethod({});
    allAuditDatas.value = retData;
    gridAuditOptions.data = retData;
  };
</script>

<style scoped>
  .drawer-content {
    max-height: calc(100vh - 200px);
    min-height: calc(50vh - 200px);
    margin: 0;
    background-color: #fff;
  }
</style>
