<template>
  <div style="height: calc(80vh - 60px)">
    <vxe-table
      ref="tableRef"
      size="small"
      auto-resize
      height="auto"
      :data="tableData"
      @cell-click="clickRowEvent"
      :row-config="{ isCurrent: true, isHover: true }"
      :columnConfig="{ resizable: true }"
      :scroll-y="{ enabled: true, gt: 40 }"
      :radio-config="{ labelField: 'name', highlight: true }"
    >
      <vxe-column type="seq" width="60" />
      <vxe-column field="fileName" type="html" title="文件名称" min-width="25%">
        <template #default="{ row }">
          <a style="word-wrap: break-word; word-break: normal" status="primary" mode="text" size="small" @click="showFileContent(row, $event)">
            <span v-html="row.fileName + '[' + row['child'].length + ']'"> </span>
          </a>
        </template>
      </vxe-column>
      <!-- <vxe-column field="fileName" type="html" title="文件名称" min-width="15%" /> -->
      <vxe-column field="issued" type="html" title="发布单位" width="15%"/>
      <vxe-column field="applyRange" type="html" title="适用范围" width="10%" :filters="applyRangeOptions"  :filter-method="filterMethod" sortable/>
      <vxe-column field="issuedDate" type="html" title="发布日期" width="10%" sortable/>
      <vxe-column field="issuedSta" title="发布状态" min-width="10%" width="10%" :formatter="formatterSta" type="html" :filters="staList"  :filter-method="filterMethodSta" sortable/>
      <vxe-column field="docNo" type="html" title="发布文号" width="10%" />
      <vxe-column field="fileTp" type="html" title="类型" :visible="false" />
      <vxe-column field="id" title="" :visible="false" />
      <vxe-column title="操作" fixed="right" width="10%">
        <template #default="{ row }">
          <vxe-button mode="text" size="small" @click="showFileItems(row, $event)">显示条目</vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
  <FileViewerModal @register="registerShowFileContentModal" :useStaticPrefixForDocx="true" />
</template>

<script lang="ts" setup>
  import { ref,nextTick } from 'vue';
  import { getAuthCache } from '/@/utils/auth';
  import type { VxeColumnPropTypes } from 'vxe-table';
  import { useModal } from '/@/components/Modal';
  import XEUtils from 'xe-utils'
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
  import FileViewerModal from '/@/components/onlinePreview/FileViewerModal.vue';

  interface RowVO {
    fileName: string;
    applyRange: string;
    issued: string;
    docNo: string;
    issuedSta: number;
    id: number;
    issuedDate: string;
  }

  const filterMethod: VxeColumnPropTypes.FilterMethod<RowVO> = ({ value, row }) => {
    return XEUtils.toValueString(row.applyRangeCodes).indexOf(value) > -1
  }

  const filterMethodSta: VxeColumnPropTypes.FilterMethod<RowVO> = ({ value, row }) => {
    return XEUtils.toValueString(row.issuedSta).indexOf(value) > -1
  }


  const applyRangeOptions = ref<VxeColumnPropTypes.Filters>([]);
  const emit = defineEmits(['showItem']);

  const tableData = ref([]);
  const listData = ref([]);
  const tableRef = ref();

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

  const staList = [
    { label: '生效中', value: 1 },
    { label: '即将实施', value: 2 },
    { label: '废止', value: 3 },
  ];

  const formatterSta: VxeColumnPropTypes.Formatter<RowVO> = ({ cellValue }) => {
    const item = staList.find((item) => item.value === cellValue);
    return item ? item.label : cellValue;
  };

  async function iniData(allData) {
    if (!allData?.length) {
      tableData.value = listData.value = [];
      return;
    }

    try {
      const allDict = getAuthCache("UI_CACHE_DB_DICT_DATA");
      const dicAry = allDict?.applyrange || [];
      applyRangeOptions.value = dicAry;

      // 创建映射以提高查找性能
      const dictMap = new Map(dicAry.map(item => [item.value, item.title]));
      
      // 使用map而不是forEach+await，因为forEach不能正确处理async/await
      const processedData = allData.map(row => {
        if (!row.applyRangeCodes) {
          return { ...row, applyRange: row.applyRangeCodes };
        }
        
        const codes = row.applyRangeCodes.split(",");
        const textAry = codes.map(code => dictMap.get(code) || code);
        
        return {
          ...row,
          applyRange: textAry.join(",")
        };
      });

      // 使用nextTick确保在DOM更新后设置数据
      await nextTick();
      tableData.value = listData.value = processedData;
    } catch (error) {
      console.error("Error processing data:", error);
      tableData.value = listData.value = [];
    }
  }

  const handleSearch = (srhTxt,col) => {
    const filterSrhTxt = String(srhTxt).trim().toLowerCase();
    if (filterSrhTxt) {
      const filterRE = new RegExp(filterSrhTxt, 'gi');
      const searchProps = !!col?[col]:['fileName', 'issued','applyRange','issuedDate','docNo','issuedSta'];
      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;
      });
    } else {
      tableData.value = listData.value;
    }
  };

  const curSelRowIndex = ref();
  const clickRowEvent = (params) => {
    const { row, column, rowIndex, columnIndex, $event } = params;  
    if(!column.field) return
    const $table = tableRef.value;
    $table.setRadioRow(row);
    curSelRowIndex.value = rowIndex;
    showFileItems(row, null);
  };

  function showFileItems(row, e) {
    emit('showItem', row);
    e?.stopPropagation();
  }

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

  defineExpose({
    iniData,
    handleSearch,
  });
</script>
