<template>
  <div style="max-height: calc(80vh - 60px); min-height: calc(50vh - 100px); margin: 0px 0px; background-color: #fff">
    <vxe-toolbar>
      <template #buttons>
        <vxe-form :data="srhFormData" style="width: 100%" layout="inline">
          <vxe-form-item title="要求:" field="name" :item-render="{}" title-width="50" title-align="right" size="small">
            <template #default="{ data }">
              <vxe-input v-model="data.name" placeholder="" clearable size="small" />
            </template>
          </vxe-form-item>
          <vxe-form-item title="来源文件:" field="fileId" :item-render="{}" title-width="80" title-align="right" size="small">
            <template #default="{ data }">
              <vxe-select v-model="data.fileId" placeholder="来源" clearable @change="filterFileEvent">
                <vxe-option v-for="(item, index) in fileList" :key="index" :value="item.value" :label="item.label" />
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item>
            <a-button type="link" @click="handleSearchDb()">搜索</a-button>
            <a-button type="link" @click="refreshDb()">刷新</a-button>
            <a-button type="link" @click="exportEvent">导出</a-button>
          </vxe-form-item>
        </vxe-form>
        <a-radio-group style="padding: 0 10px" v-model:value="libTp" size="small" @change="handleChangeLib">
          <a-radio-button value="2">合规库</a-radio-button>
          <a-radio-button value="3">内控库</a-radio-button>
        </a-radio-group>
        <a-button type="link" @click="addInnerLib()">添加到内控要求库</a-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      keep-source
      ref="tableRef"
      size="small"
      show-overflow
      height="auto"
      :data="listData"
      :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="checkbox" width="50" />
      <vxe-column field="tp" sortable :filters="tpOptions" :filter-multiple="true" type="html" title="分类" :visible="false">
        <template #default="{ row }">
          <span>{{ formatTp(row) }}</span>
        </template>
      </vxe-column>
      <vxe-column field="tpname" sortable :filters="tpOptions" :filter-multiple="true" width="20%" 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: 280px" />
            <vxe-button type="text" @click="editCancel" style="margin-left: 15px">取消</vxe-button>
            <vxe-button type="text" @click="saveEdit(row, column)" style="margin-left: 5px">保存</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="method" sortable title="检查方法" :edit-render="{ autofocus: '.my-input', autoselect: true }" width="20%">
      </vxe-column> -->

      <vxe-column field="des" width="20%" title="备注" :visible="false"/>
      <!-- <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>

      <vxe-modal
        resize
        destroy-on-close
        show-confirm-button
        show-cancel-button
        v-model="showPopup"
        title="内控要求库列表"
        width="60vw"
        height="80vh"
        :confirm-closable="false">

        <vxe-grid ref="tableModelRef" v-bind="gridOptions" keep-source :radio-config="{highlight: true}"  size="small">
          <template #toolbar_buttons>
            <a-button  @click="insertEvent()">加入</a-button>
          </template>
        </vxe-grid>
      

      </vxe-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { getAllCheckMethod, getAllCheckMethodFiles, saveEditName } from './api/AuditCheckMethodItem.api';
  import { getAllInnerOrderCheckMethodItem } from './api/AuditInnerCheckmethodItem.api';
  import VXETable from 'vxe-table';
  import {VxeSelectEvents, VxeColumnPropTypes, VxeTableInstance, VxeGridProps,VxeUI } from 'vxe-table';
  import VXETablePluginExportXLSX from 'vxe-table-plugin-export-xlsx';
  import ExcelJS from 'exceljs';
  import { list } from './api/AuditInnerCtrl.api';
  import { batchSave } from './api/AuditInnerCtrlItem.api';

  const listData = ref([{}]);
  const emit = defineEmits(['rowChangeEvent']);
  const oldData = ref();
  const libTp = ref('2');

  const showPopup = ref(false)
  const tableModelRef = ref();

  interface FormDataVO {
    name: string;
    fileId: string;
  }
  const srhFormData = reactive<FormDataVO>({
    name: '',
    fileId: '',
  });

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

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

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

  function refresh() {
    srhFormData.name = '';
    srhFormData.fileId = '';

    listData.value = oldData.value;
    const $table = tableRef.value;
    if ($table) {
      $table.clearFilter();
    }
  }

  async function refreshDb() {
    srhFormData.name = '';
    srhFormData.fileId = '';
    oldData.value = listData.value = await getAllCheckMethod({});
    const $table = tableRef.value;
    if ($table) {
      $table.clearFilter();
    }
  }

  const currentChangeEvent = ({ row }) => {
    const data = { name: row.name };
    emit('rowChangeEvent', data);
  };

  async function  iniData() {
    if (libTp.value == '2') {
      let retData = await getAllCheckMethod({});
      oldData.value = listData.value = await uniqueData(retData);
    } else {
      let retData = await getAllInnerOrderCheckMethodItem({});
      oldData.value = listData.value = await uniqueData(retData);
    }

    fileList.value = await getAllCheckMethodFiles('');
  }

  async function uniqueData(data) {
    const uniqueSet = new Set();
    const result = data
      .map((item) => ({
        tpname: item.tpname,
        tp: item.tp,
        name: item.name,
        id: item.id,
        des: item.des,
      }))
      .filter((item) => {
        const key = `${item.tp}-${item.name}`;
        if (!uniqueSet.has(key)) {
          uniqueSet.add(key);
          return true;
        }
        return false;
      });
    return result;
  }

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

  const tpOptions = ref([
    { label: '工具要求', value: '工具要求' },
    { label: '记录要求', value: '记录要求' },
    { label: '制度要求', value: '制度要求' },
    { label: '流程要求', value: '流程要求' },
  ]);

  async function handleSearchDb() {
    let retData = await getAllCheckMethod(srhFormData);
    oldData.value = listData.value = await uniqueData(retData);
  }

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

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

  function handleSearch() {
    listData.value = oldData.value;
    if (!srhFormData.name) {
      return false;
    }

    const filterContent = String(srhFormData.name).trim().toLowerCase();
    const filterRE = new RegExp(filterContent, 'gi');
    const searchProps = ['name', 'fileName'];
    listData.value = oldData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterContent) > -1));
    // list.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;
    // });
  }

  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 saveEditName(param);
      }
      await $table.clearEdit();
    }
  }
  async function editCancel() {
    const $table = tableRef.value;
    if (!$table) return;
    await $table.clearEdit();
  }
  // async function setFileList() {
  //   let rest = listData.value.map((item) => {
  //     return { label: item.fileName, value: item.fileId };
  //   });
  //   const uniqueResult = Array.from(new Set(rest.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item));

  //   fileList.value = uniqueResult;
  // }

  // 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 = listData.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 < listData.value.length; i++) {
      if (listData.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();
      }
    }
  };

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

  const addInnerLib= async () => {
    const ids = getSelectIds();
    if(ids.length==0) {
      VxeUI.modal.message({ content: '请选择记录', status:"warning" })
      return false
    }
    showPopup.value =  true

    await findPageList(1,10)
    await queryEvent()

  }


  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 gridOptions = reactive<VxeGridProps<RowVO>>({

    border: true,
    height:"auto",
    columnConfig: {
      resizable: true
    },
    pagerConfig: {
      enabled: true,
      pageSize: 10
    },
    columns: [
      { type: 'radio', visible: true, width: '40', showOverflow: false }, 
      {
        field: 'name',
        title: '内控文件名称',
        width: '30%',
        editRender: { name: 'input' },
        sortable:true
      },{
        field: 'des',
        title: '说明',
        editRender: { name: 'input' },
        minWidth:'30%',
        sortable:true
      },{
        field: 'createTime',
        title: '创建时间',
        width: '10%',
        visible: true,
        type: 'html',
        sortable:true
      },{
        field: 'id',
        title: '',
        visible: false,
      },{
        field: 'createUser', title: '创建人', visible: true , width: '10%',  sortable:true
      }
    ],
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    proxyConfig: {
      seq: true,
      props: {
        result: 'result',
        total: 'page.total'
      },
      ajax: {
        query: ({ page }) => {
          return findPageList(page.currentPage, page.pageSize)
        }
      }
    }
  })


  interface SrhParam {
    name: string
    column:string
    order:string
    pageNo:number
    pageSize:number
  }

  const srhParams = ref<SrhParam>({  
    name: '',  
    column: 'createTime',  
    order: 'desc',  
    pageNo: 1,  
    pageSize: 10  
  });

  const findPageList = async (currentPage: number, pageSize: number) => {  
    srhParams.value.pageNo = currentPage;  
    srhParams.value.pageSize = pageSize;  
    let retData = await list(srhParams.value) 
    return {  
      page: {  
        total: retData.total  
      },  
      result: retData.records  
    };  
  };

  const queryEvent = () => {
    const $grid = tableModelRef.value
    if ($grid) {
      $grid.commitProxy('query')
    }
  }

  async function insertEvent() {
    try {
      const $table = tableRef.value;
      if (!$table) return;
      const rows = await getSelectDatas();

      if(rows.length==0) {
        VxeUI.modal.message({ content: '请选择记录', status:"warning" })
        return false
      }
      const $grid = tableModelRef.value;
      if(!$grid) return
      const mRow =  $grid.getRadioRecord()
      const objAry = rows.map((row) => ({
        id: row.id,
        name: row.name,
        tp:row.tp,
        checkid: mRow.id,
        comeFrom:libTp.value,
        des: row.des,
      }));

      await batchSave(objAry);
    } catch (error) {
      console.error('Error in saveEvent:', error);
    } finally {
      showPopup.value = false
    }
  }

  function getSelectDatas() {

    const $table = tableRef.value;
    const selRecords = $table?.getCheckboxRecords();
    return selRecords||[];
  }


  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>
