<template>
  <div style="max-height: calc(80vh - 60px); min-height: calc(50vh - 100px); margin: 0px 0px; background-color: #fff">
    <vxe-toolbar>
      <template #buttons>  
        <div style="display: flex; align-items: center; width: 100%;">  
          <span style="line-height: 30px">检查方法:</span>
          <vxe-input v-model="srhText" placeholder="请输入" clearable  style="width: 35%; margin: 5px" />
          <a-button type="link" @click="handleSearch()">搜索</a-button>  
            <a-button type="link" @click="refreshDb()">刷新</a-button>  
            <a-button type="link" @click="exportEvent">导出</a-button>   
        </div>  
      </template> 
    </vxe-toolbar>
    <vxe-table
      border
      keep-source
      ref="tableRef"
      size="small"
      show-overflow
      height="auto"
      :data="list"
      :show-radio="true"
      :row-config="{ isCurrent: true, isHover: true }"
      :export-config="exportConfig"
      @current-change="currentChangeEvent"
      :edit-config="{ trigger: 'dblclick', mode: 'cell', autoClear: false, showStatus: true }"
      :columnConfig="{ resizable: true }"
      :scroll-y="{ enabled: true, gt: 50 }"
      :radio-config="{ labelField: 'name', highlight: true }"
    >
      <vxe-column type="seq" width="55" />
      <vxe-column field="tp" sortable :filters="tpOptions" :filter-multiple="true" type="html" title="分类" :visible="false">
      </vxe-column>
      <vxe-column field="tpname" sortable :filters="tpOptions" :filter-multiple="true" width="25%" type="html" title="分类" />
      <vxe-column field="name" sortable title="检查方法" :edit-render="{ autofocus: '.my-input', autoselect: true }">
        <template #edit="{ row, column }">
          <div style="display: flex; align-items: center">
            <vxe-input v-model="row.name" @input="clearFormattedName(row.name)" type="text" style="width: 190px" />
            <vxe-button type="text" @click="editCancel" style="margin-left: 5px">取消</vxe-button>
            <vxe-button type="text" @click="saveEdit(row, column)" style="margin-left: 0px">保存</vxe-button>
          </div>
        </template>
        <template #default="{ row }">
          <span style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis; ​">{{ row.name }}</span>
        </template>
      </vxe-column>
      <vxe-column field="des" width="1" title="备注" />
      <!-- <vxe-column field="fileName" width="30%" sortable :filters="fileList" :filter-method="filterMethod" :filter-multiple="true" type="html" title="参考文件">
      </vxe-column> -->
      <vxe-column field="id" title="" :visible="false" />
    </vxe-table>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import {getAllProjectItems } from '../AuditProjectItem.api';
  import VXETable from 'vxe-table';
  import { VxeSelectEvents, VxeTablePropTypes, VxeColumnPropTypes, VxeTableInstance, VxeTableEvents } from 'vxe-table';
  import VXETablePluginExportXLSX from 'vxe-table-plugin-export-xlsx';
  import ExcelJS from 'exceljs';

  const list = ref([]);
  const emit = defineEmits(['rowChangeEvent']);
  const oldData = ref();
  const srhText = ref('');
  const curProject = ref();

  const fileList = ref<{ value: any; label: any }[]>([]);

  interface RowVO {
    id: number;
    tp: number;
    name: string;
    fileName: string;
    tpname: string;

  }

  const tableRef = ref<VxeTableInstance<RowVO>>();
  VXETable.use(VXETablePluginExportXLSX, {
    ExcelJS,
  });

  function refresh() {
    srhText.value=""
    list.value = oldData.value;
    const $table = tableRef.value;
    if ($table) {
      $table.clearFilter();
    }
  }

  async function refreshDb() {
   srhText.value=""
    oldData.value = list.value = await getAllProjectItems({pid:curProject.value.pid});
    const $table = tableRef.value;
    if ($table) {
      $table.clearFilter();
    }
  }

  const curSelRowIndex = ref();
  const currentChangeEvent = ({ rowIndex,row }) => {
    curSelRowIndex.value = rowIndex;
    emit('rowChangeEvent', row);
  };

  async function iniData(project) {
    curProject.value = project
    const retData = await getAllProjectItems({pid:project.id});
    oldData.value = list.value = await deduplicateRecords(retData)
  }

  function deduplicateRecords(records) {  
    if(!records) return [];
    const seen = new Set(); 
    const deduplicated = records.filter(record => {  
        const key = `${record.tp}_${record.name}`; 
        if (!seen.has(key)) { 
            seen.add(key); 
            return true;  
        }  
        return false;
    });  
    return deduplicated;  
}  

  const formatTp = (row) => {
    return row.tp == 1 ? '工具要求' : row.tp == 2 ? '记录要求' : '制度要求';
  };

  const tpOptions = ref([
    { label: '工具要求', value: '工具要求' },
    { label: '记录要求', value: '记录要求' },
    { label: '制度要求', value: '制度要求' },
    { label: '流程要求', value: '流程要求' },
    { label: '访谈人员', value: '访谈人员' },
    { label: '查阅系统', value: '查阅系统' },
    { label: '其他要求', value: '其他要求' },
  ]);

  async function handleSearchDb() {
    oldData.value = list.value = await getAllProjectItems({pid:project.pid});
  }

  const exportConfig = {
    filename: '检查要求',
  };

  const exportEvent = () => {
    const $table = tableRef.value;
    if ($table) {
      $table.exportData({
        type: 'xlsx',
      });
    }
  };

  function handleSearch() {
    if (!srhText.value) {
      list.value = oldData.value;
      return false;
    }

    const filterContent = String(srhText.value).trim().toLowerCase();
    const filterRE = new RegExp(filterContent, 'gi');
    const searchProps = ['name'];
    list.value = oldData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterContent) > -1));

  }

  function textFilterMethod({ option, row, column }) {
    // if (option.data) {
    //   return `${row[column.field]}`.indexOf(option.data) > -1
    // }
    return true;
  }

  const textFilterRender: VxeColumnPropTypes.FilterRender = {
    name: 'VxeInput',
  };

  async function saveEdit(row, column) {
    const $table = tableRef.value;
    if ($table) {
      const field = column.field;
      const cellValue = row[field];
      // 判断单元格值是否被修改;
      if ($table.isUpdateByRow(row, field)) {
        let param = { id: row.id };
        param[field] = clearFormattedName(cellValue);
        await saveOrUpdate(param, true);
      }
      await $table.clearEdit();
    }
  }
  async function editCancel() {
    const $table = tableRef.value;
    if (!$table) return;
    await $table.clearEdit();
  }
  

  const filterMethod: VxeColumnPropTypes.FilterMethod<RowVO> = ({ value, row }) => {
    return row['fileId'] == value;
  };

  function clearFormattedName(strVal) {
    return strVal.replace(/<[^>]*>/g, '').trim();
  }

  const cellMerge = ({ row, rowIndex }) => {
    const prevRow = list.value[rowIndex - 1];
    if (prevRow && prevRow.name === row.name) {
      return { colspan: 0 }; // 隐藏当前行的 name 列单元格
    }
    let cnt = countSameName(row.name, rowIndex);
    return { rowspan: cnt };
  };

  const countSameName = (name, startIndex) => {
    let count = 1;
    for (let i = startIndex + 1; i < list.value.length; i++) {
      if (list.value[i].name == name) {
        count++;
      } else {
        break;
      }
    }
    return count;
  };

  const filterFileEvent: VxeSelectEvents.Change = () => {
    const $table = tableRef.value;
    if ($table) {
      const column = $table.getColumnByField('fileName');
      if (column) {
        const option = column.filters.find((item) => item.value === srhFormData.fileId);
        if (option) {
          option.checked = true;
        }
        $table.updateData();
      }
    }
  };

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

<style scope>
  .layout {
    background: #fff;
    height: calc(90vh - 120px);
    margin: 0px 0px 0px 0px;
    overflow: hidden;
    min-height: 400px;
  }
  .ant-descriptions-item-label {
    width: 150px;
  }

  .cell-content {
    text-align: left;
    white-space: normal; /* 允许文本换行 */
    word-wrap: break-word; /* 按单词折行 */
    overflow-wrap: break-word; /* 按单词折行 */
    max-width: 100%; /* 根据需要设置最大宽度 */
  }
</style>
