<template>
  <div style="height: calc(80vh - 60px);padding:10px">
    <vxe-grid
      size="small"
      ref="tableRef"
      auto-resize
      keep-source
      height="auto"
      v-bind="gridOptions"
      :loading="loading"
      :check-config="{ highlight: true }"
      :columnConfig="{ resizable: true }"
      :row-config="{ isCurrent: true, isHover: true }"
      v-on="gridEvents"
      @filter-change="filterChangeEvent"
    >
      <!-- <template #filter="{ $panel, column }">
        <template v-for="(item, ind) in row.cgrpPath?.split(',')" :key="ind">
          {{ item }}
        </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)"> {{ item }}</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 #operate="{ row }">
        <vxe-button mode="text" size="small" content="详情" @click="handleDetail(row)" />
      </template>
      <template #pager>
        <vxe-pager
          :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          :total="tablePage.total"
          @page-change="handlePageChange"
        />
      </template>
    </vxe-grid>
    <!-- <vxe-modal v-model="showDetails" title="查看详情" width="45%" height="50%" :mask="false" :lock-view="false" resize>
      <template #default>
        <vxe-table auto-resize height="auto" :row-config="{ isHover: true }" :show-header="false" :sync-resize="showDetails" :data="detailData">
          <vxe-column field="label" width="20%" />
          <vxe-column field="value" />
        </vxe-table>
      </template>
    </vxe-modal> -->
  </div>
  <ShowFileContentModal @register="registerShowFileContentModal" />
  <component :is="currentComponent" @register="registerModal" @success="handleSuccess" @callback="callback" />
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, watch } from 'vue';
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
  import { deleteActRel } from '../index.api';
  import { auditCols } from './data/AuditCommon2.data';
  import { VXETable } from 'vxe-table';
  import { useModal } from '/@/components/Modal';
  import ShowFileContentModal from './modal/ShowFileContentModal.vue';
  import AuditComplianeItemModal from './modal/AuditComplianeItemModal.vue';
  import AuditInnerCtrlModal from './modal/AuditInnerCtrlModal.vue';
  import AuditInnerOrderModal from './modal/AuditInnerOrderModal.vue';
  import AuditProblemModal from './modal/AuditProblemModal.vue';
  import AuditCheckMethodModal from './modal/AuditCheckMethodModal.vue';

  const emit = defineEmits(['callback', 'callBackAct', 'filterChangeEvent']);

  const currentComponent = ref();
  const currentComponentAry = ref({
    1: AuditComplianeItemModal,
    2: AuditInnerCtrlModal,
    3: AuditInnerOrderModal,
    4: AuditProblemModal,
    5: AuditCheckMethodModal,
  });

  const tableRef = ref();
  const loading = ref(false);
  const tableData = ref([]);
  const oldData = ref([]);
  const curPageData = ref([]);
  const showDetails = ref(false);
  const fileDoc = ref();
  const filterActRes = ref();

  const [registerModal, { openModal }] = useModal();
  const [registerShowFileContentModal, { openModal: openFileContentModel }] = useModal();

  const curTp = ref();
  const detailData = ref<
    {
      label: string;
      value: string;
    }[]
  >([]);

  const gridOptions = reactive({
    border: false,
    showOverflow: true,
    loading: false,
    scrollY: {
      enabled: true,
      gt: 50,
    },
    checkboxConfig: { checkStrictly: true },
    columnConfig: {
      useKey: false,
      resizable: true,
    },
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      export: true,
      print: false,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    columns: [],
    data: curPageData,
  });

  // function showFileContent(row) {
  //   if (row.filePath) {
  //     let url = getFileAccessHttpUrl(row.filePath);
  //     window.open(url);
  //     return false;
  //   }
  // }

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

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

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  });

  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);
  };

  async function setTableData(tp, list) {
    curTp.value = tp;
    currentComponent.value = currentComponentAry.value[tp];
    tableData.value = oldData.value = list;

    setFilterOptions();

    let newwCols = structuredClone(auditCols[tp]);
    for (const element of newwCols) {
      if (element['field'] == 'ind') {
        element.visible = false;
      }
      if (element['field'] == 'caName') {
        element.visible = false;
      }
      if (element['field'] == 'fileName') {
        element.visible = true;
      }
    }

    gridOptions.columns = newwCols;
    handlePageChange({ currentPage: 1, pageSize: 10 });
  }

  async function delRels(tp, actId) {
    let ids = await getSelectIds();
    if (ids.length == 0) {
      VXETable.modal.message({ content: '请选择待删除的记录', status: 'warning' });
      return false;
    }
    await deleteActRel({ tp: tp, actId: actId, ids: ids.join(',') });
  }

  const gridEvents = {
    cellClick({ row, column, cell }) {
      handleCellClick({ row, column, cell });
    },
  };

  const handleCellClick = ({ row, column, cell }) => {
    if (column.field == 'fileName') {
      cell.stopPropagation();
    }
    detailData.value = [];
    auditCols[curTp.value].forEach((item) => {
      if (item.field) {
        if (item.field == 'fileName') {
          detailData.value.push({ label: item.title, value: row[item.field] });
        } else if (item.visible == undefined || item.visible === true) {
          detailData.value.push({ label: item.title, value: row[item.field] });
        }
      }
    });
    showDetails.value = true;
  };

  function handleClickLabelName(labelName) {
    emit('callback', labelName, 1);
  }

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

  function handleDetail(row) {
    let child = [];
    for (let i = 0; i < tableData.value.length; i++) {
      if (tableData.value[i].fileId == row.fileId) {
        child.push(tableData.value[i]);
      }
    }
    let fileDoc = {};
    fileDoc['fileName'] = row.fileName;
    fileDoc['fileId'] = row.fileId;
    fileDoc['fileTp'] = row.fileTp;
    fileDoc['filePath'] = row.filePath;
    fileDoc['child'] = child;
    nextTick(() => {
      openModal(true, {
        allData: tableData.value,
        docFile: fileDoc,
        record: row,
        isDetail: true,
        isUpdate: true,
        showFooter: false,
      });
    });
  }

  async function setFilterOptions() {
    let columns = auditCols[curTp.value];
    let filerOprions;
    columns.forEach(function (col) {
      if (col.filterMethodTp == 'check') {
        let colField = col.field;
        filerOprions = oldData.value.map((obj) => ({
          label: obj[colField],
          value: obj[colField],
        }));
        let uniqueArr = [...new Set(filerOprions.map(JSON.stringify))].map(JSON.parse);
        col.filters = uniqueArr;
      } else if (col.filterMethodTp == 'text') {
      }
    });
  }
  // 根据文件变化筛选控制项
  async function filterAct(item) {
    const mergedData = item.reduce((acc, item) => {
      if (!item.fileName || !item.actIds || item.actIds.trim() === '') {
        return acc;
      }
      if (!acc[item.fileName]) {
        acc[item.fileName] = new Set(item.actIds.split(','));
      } else {
        item.actIds.split(',').forEach((id) => acc[item.fileName].add(id));
      }
      return acc;
    }, {} as Record<string, Set<string>>);
    filterActRes.value = Object.entries(mergedData).map(([fileName, actIdsSet]) => ({
      fileName,
      actIds: Array.from(actIdsSet).join(','),
    }));
  }

  // 根据文件变化筛选控制项
  async function filterChangeEvent({ field, values, datas }) {
    if (field == 'fileName') {
      await clearFilter('cgrpPath');
    } else {
      await clearFilter('fileName');
    }

    if (values.length == 0 && datas.length === 0) {
      gridOptions.data = tableData.value = oldData.value;
      await updatePage();
      return;
    }

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

    await filterAct(gridOptions.data);
    emit('filterChangeEvent', filterActRes.value);
    tableData.value = gridOptions.data;
    await updatePage();
  }

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

  const clearFilter = async (field) => {
    const $table = tableRef.value;
    if ($table) {
      $table.clearFilter($table.getColumnByField(field));
    }
  };

  function handleSuccess() {}
  defineExpose({
    getSelectIds,
    setTableData,
    delRels,
  });
</script>
