<template>
  <div style="height: calc(80vh - 60px)">
    <vxe-grid
      size="small"
      ref="tableRef"
      auto-resize
      keep-source
      height="auto"
      v-bind="gridOptions"
      :loading="loading"
      :edit-config="{ trigger: 'dblclick', mode: 'row' }"
      :columnConfig="{ resizable: true }"
      :row-config="{ isCurrent: true, isHover: true,useKey: true }"
      v-on="gridEvents"
      @filter-change="filterChangeEvent"
    >
      <template #caName_default="{ row }">
        <template v-for="(item, ind) in row.caName?.split(',')" :key="ind">
          <a-popover placement="topRight">
            <template #content>
              <a-row style="max-width: 300px; text-align: center; overflow: auto; max-height: 30vh">
                <a-col v-for="(ite, idx) in row.caName?.split(',')" :key="idx" style="">
                  <vxe-button mode="text" @click="handleClickCaName(ite)">{{ ite }}</vxe-button>
                </a-col>
              </a-row>
            </template>
            <vxe-button mode="text" @click="handleClickCaName(item)">{{ item }}</vxe-button>
          </a-popover>
        </template>
      </template>

      <template #labels_default="{ row }">
        <template v-for="(item, ind) in row.labelNames?.split(',')" :key="ind">
          <vxe-button mode="text" size="small" @click="handleClickLabelName(item)">
            <span v-html="item"></span>
          </vxe-button>
        </template>
      </template>

      <template #fileName_default="{ row }">
        <vxe-button mode="text" size="small" status="primary" @click="showFileContent(row)">
          <span v-html="row.fileName"></span>
        </vxe-button>
      </template>

      <template #toolbar_buttons>
        <div v-show="isFileList">
          <blockquote>
            <span @click="showFileContent" v-html="fileDoc?.fileName"> </span>
            <span @click="showFile()" style="color: black; margin-left: 20px"> 返回 </span>
          </blockquote>
        </div>
      </template>

      <template #operate="{ row }">
        <vxe-button v-if="curtp == 8" mode="text" size="small" content="添加子分类" @click="addChild(row)" />
        <template v-if="hasActiveEditRow(row)">
          <vxe-button mode="text" size="small" content="取消" @click="clearRowEvent(row)" />
          <vxe-button mode="text" size="small" status="primary" content="保存" @click="saveRowEvent(row)" />
        </template>
        <template v-else>
          <vxe-button mode="text" size="small" content="编辑" @click="editRowEvent(row)" />
        </template>
        <vxe-button mode="text" size="small" content="删除" @click="removeRowEvent(row)" />
        <vxe-button mode="text" size="small" content="详情" @click="handleDetail(row)" />
        <vxe-button v-if="gzltp=='4'" mode="text" size="small" content="风险跟踪" @click="handleFLow(row)" />
        <!-- <vxe-button mode="text" size="small" content="分配任务" @click="sendTask(row)" /> -->
      </template>
      <template #text_edit="{ row, column }">
        <vxe-input v-model="row[column.field]" />
      </template>

      <template #pager>
        <vxe-pager
          v-show="gridOptions.pagerConfig.enabled"
          :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          v-model:page-sizes="tablePage.pageSizes"
          :total="tablePage.total"
          @page-change="handlePageChange"
        />
      </template>
    </vxe-grid>
  </div>

  <component :is="currentComponent" @register="registerModal" @success="handleSuccess" @callback="callback" />
  <AuditActListModal @register="refAuditActListModal" @saveRel="handleSaveRel" />
  <AuditSetLableModal @register="regAddLableModal" modalTitle="添加标签" @saveLabel="saveLabels" />
  <MergeActModal @register="registerMergeActModal" @success="handleSuccess" />
  <ShowFileContentModal @register="registerShowFileContentModal" />

  <a-drawer
    title="节点流程"
    placement="right"
    width="70%"
    :closable="true"
    :visible="showDrawerFlow"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    :body-style="{ padding: '0px' }"
    @close="onCloseDrawer"
  >
    <div style="width: 100%; height: 100%">
      <iframe :src="flowUrl" scrolling="auto" frameborder="no" style="width: 100%; height: 100%"></iframe>
    </div>
  </a-drawer>
  <AuditProblemDetailFlowModal ref="refStPlanManFlow"></AuditProblemDetailFlowModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue';

  import { auditCols, srhCond } from './data/AuditCommon.data';
  import { useModal } from '/@/components/Modal';
  import { VxeUI } from 'vxe-table';

  import AuditRiskEventModal from './modal/AuditRiskEventModal.vue';
  import AuditCheckMethodModal from './modal/AuditCheckMethodModal.vue';
  import AuditComplianeItemModal from './modal/AuditComplianeItemModal.vue';
  import AuditInnerCtrlModal from './modal/AuditInnerCtrlModal.vue';
  import AuditInnerOrderModal from './modal/AuditInnerOrderModal.vue';
  import AuditBestPracticeModal from './modal/AuditBestPracticeModal.vue';
  import AuditProblemModal from './modal/AuditProblemModal.vue';
  import AuditScenarioModal from './modal/AuditRiskScenarioModal.vue';
  import AuditActModal from './modal/AuditActModal.vue';
  import AuditLableModal from './modal/AuditLableModal.vue';

  import AuditSetLableModal from './modal/AuditSetLableModal.vue';
  import AuditActListModal from './modal/AuditActListModal.vue';
  import MergeActModal from './modal/MergeActModal.vue';
  import ShowFileContentModal from './modal/ShowFileContentModal.vue';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import { saveOrUpdateByTp, deleteByTp, saveBatchLabels, saveBatchActRels, queryActByIds, queryLabelByCodes } from '../index.api';
 
  import { cloneDeep } from 'lodash-es';
  import AuditProblemDetailFlowModal from '/@/views/newlib/AuditProblemDetailFlowModal.vue';

  const flowUrl = ref();
  const showDrawerFlow = ref();
  const emit = defineEmits(['showFileList', 'success', 'callBackAct']);
  const [registerModal, { openModal }] = useModal();
  const [regAddLableModal, { openModal: openSetLabelModal }] = useModal();
  const [refAuditActListModal, { openModal: openActLisModal }] = useModal();
  const [registerMergeActModal, { openModal: openMergeActModel }] = useModal();
  const [registerShowFileContentModal, { openModal: openFileContentModel }] = useModal();
  const user = useUserStoreWithOut();

  const currentComponent = ref();
  const currentComponentAry = ref({
    1: AuditComplianeItemModal,
    2: AuditInnerCtrlModal,
    3: AuditInnerOrderModal,
    4: AuditProblemModal,
    5: AuditCheckMethodModal,
    6: AuditRiskEventModal,
    7: AuditBestPracticeModal,
    8: AuditScenarioModal,
    9: AuditActModal,
    10: AuditLableModal,
  });
  const curtp = ref(0);
  const fileDoc = ref();
  const isFileList = ref(false);
  const tableRef = ref();
  const loading = ref(false);
  const tableData = ref([]);

  const listData = ref([]);

  const curPageData = ref([]);
  const gridOptions = reactive({
    border: true,
    loading: false,
    showOverflow: true,
    printConfig: {},
    scrollY: {
      enabled: true,
      gt: 50,
    },
    checkboxConfig: {
      highlight: true,
      checkStrictly: false,
    },
    columnConfig: {
      useKey: true,
      resizable: true,
    },
    editConfig: {
      trigger: 'manual',
      mode: 'row',
      showStatus: true,
    },
    treeConfig: {
      transform: true,
      rowField: 'id',
      parentField: 'pid',
    },
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      export: false,
      print: false,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    pagerConfig: {
      enabled: true,
    },
    columns: [],
    data: curPageData,
  });

  function handleClickCaName(caName) {
    emit('callBackAct', caName, 2);
  }

  function callback(tp, obj) {
    if (tp == 5) {
      emit('callBackAct', obj, 3);
    }
  }

  function handleClickLabelName(labelNames) {
    emit('callBackAct', labelNames, 1);
  }

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

  function getSelectDatas() {
    const $table = tableRef.value;
    const selRecords = $table?.getCheckboxRecords();
    return selRecords;
  }

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 30, 50, 100, 300, 500, 1000],
  });

  const handlePageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage || 1;
    tablePage.pageSize = pageSize || 10;
    tablePage.total = tableData.value.length;
    let st = (tablePage.currentPage - 1) * tablePage.pageSize;
    let end = st + tablePage.pageSize;
    curPageData.value = tableData.value.slice(st, end);
  };
  const gzltp = ref<string>('0');;
  async function setTableData(tp, list) {

    gzltp.value = tp;
    curtp.value = tp;
    currentComponent.value = currentComponentAry.value[tp];
    tableData.value = listData.value = list;
    gridOptions.columns = auditCols[tp];
    if (tp != 8) {
      handlePageChange({ currentPage: 1, pageSize: 10 });
      gridOptions.pagerConfig.enabled = true;
    } else {
      curPageData.value = list;
      gridOptions.pagerConfig.enabled = false;
    }

    await setFilterOptions();
  }

  let curEditData = {};

  function showForm(isUpdate, tp, allData) {
    allData.value = allData;
    curtp.value = tp;
    if (isUpdate) {
      const $table = tableRef.value;
      let selRecords = $table.getCheckboxRecords();

      if (selRecords.length == 0) {
        VxeUI.modal.message({ content: '请选择待编辑的记录', status: 'warning' });
        return;
      }
      if (selRecords.length > 1) {
        VxeUI.modal.message({ content: '一次只能编辑一条记录', status: 'warning' });
        return;
      }

      curEditData = Object.assign({}, selRecords[0]);
      if (!fileDoc.value && curEditData.fileId) {
        fileDoc.value = {
          id: curEditData.fileId,
          fileName: curEditData.fileName,
          filePath: curEditData.filePath,
          fileTp: curEditData.fileTp,
        };
      }
    }

    nextTick(() => {
      openModal(true, {
        allData: allData,
        docFile: fileDoc.value,
        record: curEditData,
        isUpdate: isUpdate,
        isDetail: false,
        showFooter: false,
      });
    });
  }

  function addChild(row) {
    nextTick(() => {
      openModal(true, {
        docFile: null,
        pid: row.id,
        record: {},
        isUpdate: false,
        isDetail: false,
        showFooter: false,
      });
    });
  }

  async function handleSuccess(isUpdate, newValue) {
    emit('success');
  }

  async function handleLabelSuccess(newValue, selRow) {
    let oldLabelCodes = selRow['labels'];
    let newLabelCodes = newValue['labels'];
    if (oldLabelCodes !== newLabelCodes) {
      let labelList = await queryLabelByCodes({ labelCodes: newLabelCodes });
      selRow['labels'] = labelList.map((label) => label.lableCode).join(',');
      selRow['labelNames'] = labelList.map((label) => label.lableName).join(',');
    }
  }

  async function handleActSuccess(newValue, selRow) {
    if (curtp.value == 1) {
      let newActIds = [];
      const checkMethods = newValue?.checkMethods;
      if (checkMethods && checkMethods.length > 0) {
        for (let check of checkMethods) {
          if (check.actIds) {
            newActIds.push(check.actIds);
          }
        }
      }
      if (newActIds.length > 0) {
        const actList = await queryActByIds({ ids: newActIds.join(',') });
        selRow['actIds'] = actList.map((act) => act.id).join(',');
        selRow['caName'] = actList.map((act) => act.caName).join(',');
      } else {
        selRow['actIds'] = '';
        selRow['caName'] = '';
      }
    } else {
      const oldActIds = selRow['actIds'];
      const newActIds = newValue['actIds'];
      if (oldActIds !== newActIds) {
        if (newActIds) {
          const actList = await queryActByIds({ ids: newActIds });
          selRow['actIds'] = actList.map((act) => act.id).join(',');
          selRow['caName'] = actList.map((act) => act.caName).join(',');
        } else {
          selRow['actIds'] = '';
          selRow['caName'] = '';
        }
      }
    }
  }

  const hasActiveEditRow = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      return $grid.isEditByRow(row);
    }
    return false;
  };

  const editRowEvent = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      $grid.setEditRow(row);
    }
  };

  const clearRowEvent = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      $grid.clearEdit().then(() => {
        $grid.revertData(row);
      });
    }
  };

  const saveRowEvent = async (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      await $grid.clearEdit();
      try {
        gridOptions.loading = true;
        saveOrUpdateByTp(curtp.value, row, true);
      } catch (e) {
        console.log(e);
      } finally {
        gridOptions.loading = false;
      }
    }
  };

  const removeRowEvent = async (row) => {
    const type = await VxeUI.modal.confirm('您确定要删除该数据?');
    const $grid = tableRef.value;
    if ($grid) {
      if (type === 'confirm') {
        await deleteByTp(curtp.value, { id: row.id }, function () {
          //$grid.remove(row);
          emit('success');
        });
      }
    }
  };

  async function setTableDataFile(tp, doc) {
    curtp.value = tp;
    currentComponent.value = currentComponentAry.value[tp];
    isFileList.value = true;
    fileDoc.value = doc;
    curtp.value = tp;
    tableData.value = listData.value = doc.child;
    gridOptions.columns = auditCols[tp];
    handlePageChange({ currentPage: 1, pageSize: 10 });
    curPageData.value = doc.child;
    nextTick(async () => {
      const $grid = tableRef.value;
      $grid.clearFilter();
      await setFilterOptions();
    });
  }

  function handleDetail(row) {
    let fileDetailDoc = {};
    fileDetailDoc['id'] = row.fileId;
    fileDetailDoc['fileName'] = row.fileName;
    fileDetailDoc['filePath'] = row.filePath;
    fileDetailDoc['fileTp'] = row.fileTp;
    nextTick(() => {
      openModal(true, {
        allData: tableData.value,
        docFile: fileDoc?.value || fileDetailDoc,
        record: row,
        isDetail: true,
        isUpdate: true,
        showFooter: false,
      });
    });
  }

  async function saveLabels(lableCodes, lableName) {
    let tids = await getSelectIds();
    if (!tids || tids.length == 0) return;
    await saveBatchLabels({
      tp: curtp.value,
      labelCodes: lableCodes?.join(','),
      tids: tids.join(','),
      labelNames: lableName?.join(','),
    });

    let selRows = await getSelectDatas();
    for (let row of selRows) {
      row['labels'] = lableCodes?.join(',');
      row['labelNames'] = lableName?.join(',');
    }
  }

  function addLabels() {
    let tids = getSelectIds();
    if (!tids || tids.length == 0) {
      VxeUI.modal.message({ content: '请选择至少1条记录', status: 'warning' });
      return;
    }

    let labelIds = '';
    if (tids.length == 1) {
      let datas = getSelectDatas()[0];
      labelIds = datas.labels;
    }
    openSetLabelModal(true, {
      labelIds: labelIds,
      isUpdate: false,
      showFooter: true,
    });
  }

  async function handleSaveRel(actIds, actNames) {
    let ids = await getSelectIds();
    if (ids && ids.length == 0) return;
    if (actIds && actIds.length == 0) return;

    let param = {
      tids: ids.join(','),
      tp: curtp.value,
      actIds: actIds.join(','),
    };

    await saveBatchActRels(param);
    let selRows = await getSelectDatas();
    for (let row of selRows) {
      row['actIds'] = actIds?.join(',');
      row['caName'] = actNames?.join(',');
    }
  }

  async function addBatchActs() {
    let tids = await getSelectIds();
    if (!tids || tids.length == 0) {
      VxeUI.modal.message({ content: '请选择至少1条记录', status: 'warning' });
      return;
    }

    let actIds = [];
    if (tids.length == 1) {
      let datas = getSelectDatas()[0];
      actIds = datas.actIds?.split(',');
    }
    openActLisModal(true, {
      actIds: actIds,
      isUpdate: false,
      showFooter: true,
    });
  }

  const gridEvents = {
    cellClick({ row }) {
      const $table = tableRef.value;
      $table.toggleCheckboxRow(row);
    },
  };

  function mergeActModel() {
    const $table = tableRef.value;
    const selRecords = $table.getCheckboxRecords();
    if (selRecords.length < 2) {
      VxeUI.modal.message({ content: '请至少选择2条控制项', status: 'warning' });
      return false;
    }

    openMergeActModel(true, {
      records: selRecords,
      isUpdate: false,
      showFooter: true,
    });
  }

  function showFileContent(row) {
    if (row.filePath) {
      openFileContentModel(true, {
        record: row,
        isUpdate: false,
        showFooter: true,
      });
    }
  }

  function showFile() {
    // let columns = auditCols[curtp.value];
    // const $grid = tableRef.value;
    // columns.forEach(function (col) {
    //   $grid.setFilter(col.field, [])
    // })
    // $grid.updateData()

    const $grid = tableRef.value;
    $grid.clearFilter();
    emit('showFileList');
  }

  function sendTask(row) {
    let flowNo = '017';
    showDrawerFlow.value = true;
    flowUrl.value = import.meta.env.VITE_APP_JFLOW_CORE_ADDR + '/#/WF/Port?DoWhat=StartFlow&FK_Flow=' + flowNo + '&Token=' + user.getJflowToken;
  }

  function onCloseDrawer() {
    showDrawerFlow.value = false;
  }

  async function setFilterOptions() {
    if (!auditCols[curtp.value]) return;
    
    let columns = cloneDeep(auditCols[curtp.value]);
    let filerOprions = {};
    
    columns.forEach(function (col) {
      if (col.filterMethodTp == 'check') {
        let colField = col.field;
        
        // 过滤掉 null/undefined/空字符串 的值，并去重
        filerOprions = listData.value
          .map(obj => obj[colField])
          .filter(value => value != null && value !== '') // 排除 null/undefined/空字符串
          .map(value => ({
            label: String(value), // 确保 label 是字符串
            value: value
          }));
        
        // 更高效的去重方式
        const uniqueOptions = [];
        const seen = new Set();
        filerOprions.forEach(option => {
          const key = `${option.value}`; // 使用字符串作为键
          if (!seen.has(key)) {
            seen.add(key);
            uniqueOptions.push(option);
          }
        });
        
        col.filters = uniqueOptions;
        
      } else if (col.filterMethodTp == 'text') {
        col.datas = [];
      }
    });
    
    gridOptions.columns = [];
    gridOptions.columns = columns;
  }

  // function filterChangeEvent({ filterList }) {
  //   if (!filterList || filterList.length == 0) {
  //     tableData.value = gridOptions.data = listData.value;
  //     handlePageChange({ currentPage: 1, pageSize: 10 });
  //     return;
  //   }
  //   let lastEle = filterList[filterList.length - 1];
  //   if (lastEle) {
  //     let field = lastEle.field;
  //     let datas = lastEle.datas;
  //     let values = lastEle.values;
  //     if (values[0]) {
  //       gridOptions.data = listData.value.filter((item) => values.indexOf(item[field]) > -1);
  //       tableData.value =  gridOptions.data;
  //       handlePageChange({ currentPage: 1, pageSize: 10 });
  //     } else {
  //      //alert(field)
  //       gridOptions.data = listData.value.filter((item) => datas.some((item) => item[field].includes(item)));
  //       tableData.value =  gridOptions.data;
  //       handlePageChange({ currentPage: 1, pageSize: 10 });
  //     }
  //   } else {
  //     gridOptions.data = listData.value;
  //   }

  //    //setTableData(curtp.value, gridOptions.data);

  // }

  async function filterChangeEvent({ field, values, datas }) {
    if (values.length == 0 && datas.length === 0) {
      gridOptions.data = tableData.value = listData.value;
      await updatePage();
      return;
    }

    if (values[0]) {
      console.log(listData.value,"listData.value")
      gridOptions.data = listData.value.filter((item) => values.indexOf(item[field]) > -1);
    } else {
      gridOptions.data = listData.value.filter((item) => datas.some((item) => item[field].includes(item)));
      tableData.value = listData.value.filter((item) =>
        datas.some((data) => {
          const itemField = item[field];
          return itemField && typeof itemField === 'string' ? itemField.includes(data) : itemField === null && data === null;
        })
      );
    }

    tableData.value = gridOptions.data;
    await updatePage();
  }

  const handleSearch = (srhTxt, col) => {
    const filterSrhTxt = String(srhTxt).trim().toLowerCase();
    if (filterSrhTxt) {
      const filterRE = new RegExp(filterSrhTxt, 'gi');
      const searchProps = !!col ? [col] : srhCond[curtp.value];
      let rest = listData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterSrhTxt) > -1));

      // tableData.value = rest.map((row) => {
      //   const item = Object.assign({}, row);
      //   searchProps.forEach((key) => {
      //     item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-lighten" style="color:red">${match}</span>`);
      //   });
      //   return item;
      // });
      setTableData(curtp.value, rest);
    } else {
      tableData.value = listData.value;
      setTableData(curtp.value, tableData.value);
    }
  };

  async function updatePage() {
    handlePageChange({ currentPage: 1, pageSize: tablePage.pageSize });
  }

  const refStPlanManFlow = ref()
  function handleFLow(record: Recordable) {

    console.log("----------- record",record);
    //window.open(url.value+"&kjzlid="+record.id, '_blank');
    refStPlanManFlow.value.iniPage(record);

  }

  defineExpose({
    getSelectDatas,
    getSelectIds,
    setTableData,
    showForm,
    setTableDataFile,
    addLabels,
    addBatchActs,
    mergeActModel,
    handleDetail,
    handleSearch,
    setFilterOptions,
  });
</script>

<style scope>
  blockquote {
    padding: 0px 5px;
    color: black;
    cursor: pointer;
  }
</style>
