<template>
  <div style="height:90vh; padding: 10px;">
    <a-row style="background-color: #f5f5f5; padding: 10px; height:100%" :gutter="4">
      <a-col :span="24 - rightWidth" style="height:100%">
        <vxe-toolbar ref="toolbarRef" custom>
          <template #buttons>
            <vxe-button mode="text" status="primary" @click="saveEvent" style="margin-left:10px;">加入</vxe-button>
            <vxe-select v-model="searchData.srhCol" placeholder="请选择" style="width: 120px; margin-left: 20px" clearable>
              <vxe-option value="" label="全部" />
              <vxe-option value="name" label="检查方法" />
              <vxe-option value="checkContent" label="检查点" />
              <vxe-option value="itemContent" label="监管内容" />
              <vxe-option value="item" label="监管条目" />
            </vxe-select>
            <vxe-input 
              v-model="searchData.srhTxt" 
              type="search" 
              placeholder="请输入搜索内容" 
              clearable 
              @keyup.enter="handleSearch()" 
              style="width: 200px; margin-left: 10px" 
            />
            <vxe-button mode="text" status="primary" @click="handleSearch()">搜索</vxe-button>
            <vxe-button mode="text" status="primary" @click="handleRefresh()">重置</vxe-button>
          </template>
          <template #tools>
            <vxe-radio-group v-model="searchData.srhTp" style="margin-right: 20px;" @change="handleChangeLib">
              <vxe-radio label="2" content="合规库" />
              <vxe-radio label="3" content="内控制度" />
            </vxe-radio-group>
            <vxe-button mode="text" status="primary" @click="closeDrawer" style="margin-right: 10px;">关闭</vxe-button>
            <a-button type="link" @click="setRightWidth">
              <menuUnfoldOutlined v-if="collapsed" class="trigger" />
              <MenuFoldOutlined v-else class="trigger" />
            </a-button>
          </template>
        </vxe-toolbar>
        
        <vxe-table
          size="small"
          show-overflow
          auto-resize
          ref="tableRef"
          height="92%"
          :span-method="rowspanMethod"
          :loading="loading"
          :data="tableData"
          :scroll-y="{ enabled: true, gt: 50 }"
          @cell-click="cellClickEvent"
          :checkbox-config="{ highlight: true }"
        >
          <vxe-column type="checkbox" width="60" fixed="left" />
          <vxe-column field="tp" title="分类" width="120" :filters="tpOptions">
            <template #default="{ row }">
              {{ setRowTpName(row) }}
            </template>
          </vxe-column>
          <vxe-column field="name" title="监管要求" min-width="200" />
          <vxe-column field="checkContent" title="检查点" min-width="200" />
          <vxe-column field="checkDes" title="检查点说明" width="150" />
          <vxe-column field="fileName" title="来源文件" width="200" :filters="fileList" />
          <vxe-column field="item" title="监管条目" width="150" />
          <vxe-column field="itemContent" title="监管条目内容" width="200" />
        </vxe-table>
      </a-col>
      <a-col :span="rightWidth" style="height: 100%">
        <AuditInnerDetail ref="refAuditInnerDetail" />
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { VxeTablePropTypes, VxeUI } from 'vxe-table';
  import { getDictItemsByCode } from '/@/utils/dict/index';
  import { queryRuleItems } from '../api/AuditInnerCtrl.api';
  import { batchSave } from '../api/AuditInnerCtrlItem.api';
  import AuditInnerDetail from './AuditInnerDetail.vue';
  import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue';

  interface RowVO {
    id: number;
    name: string;
    tp: number;
    checkContent: string;
    checkDes: string;
    itemContent: string;
    item: string;
    fileName: string;
    fileId: string;
    filePath: string;
  }

  // 搜索数据
  const searchData = ref({
    srhTxt: '',
    srhCol: '',
    srhTp: '2',
    ctlId: '',
  });

  // 其他响应式数据
  const rightWidth = ref(0);
  const loading = ref(false);
  const refAuditInnerDetail = ref();
  const fileList = ref<any[]>([]);
  const tableRef = ref();
  const tableData = ref<RowVO[]>([]);
  const oldData = ref<RowVO[]>([]);
  const tpOptions = ref<any[]>([]);
  const collapsed = ref(true);

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

  // 初始化数据 - 对外暴露的方法
  const iniData = async (paramData: any = {}) => {
    console.log('iniData called with:', paramData);
    
    try {
      // 更新搜索参数
      if (paramData) {
        if (paramData.srhTxt !== undefined) searchData.value.srhTxt = paramData.srhTxt;
        if (paramData.srhCol !== undefined) searchData.value.srhCol = paramData.srhCol;
        if (paramData.ctlId !== undefined) searchData.value.ctlId = paramData.ctlId;
        if (paramData.srhTp !== undefined) searchData.value.srhTp = paramData.srhTp;
      }
      
      console.log('Updated searchData:', searchData.value);
      
      // 获取字典数据
      const dictData = await getDictItemsByCode('rule_type');
      tpOptions.value = await changeValeToInt(dictData);
      
      // 加载表格数据
      await loadTableData();
    } catch (error) {
      console.error('Error in iniData:', error);
      VxeUI.modal.message({ content: '初始化失败', status: 'error' });
    }
  };

  // 加载表格数据
  const loadTableData = async () => {
    try {
      loading.value = true;
      
      const params = {
        srhTxt: searchData.value.srhTxt,
        srhCol: searchData.value.srhCol,
        srhTp: searchData.value.srhTp,
        ctlId: searchData.value.ctlId,
      };
      
      console.log('Loading table data with params:', params);
      
      const result = await queryRuleItems(params);
      tableData.value = oldData.value = result || [];
      
      console.log('Table data loaded:', tableData.value.length, 'records');
      
      // 设置文件列表
      await setFileList();
    } catch (error) {
      console.error('Error loading table data:', error);
      VxeUI.modal.message({ content: '加载数据失败', status: 'error' });
      tableData.value = oldData.value = [];
    } finally {
      loading.value = false;
    }
  };

  // 保存事件 - 加入选中项
  async function saveEvent() {
    try {
      loading.value = true;
      const $table = tableRef.value;
      if (!$table) return;
      
      const selectedRows = getSelectRows();
      
      if (selectedRows.length === 0) {
        VxeUI.modal.message({ content: '请选择要加入的数据', status: 'warning' });
        return;
      }
      
      console.log('Selected rows:', selectedRows.length);
      
      // 准备要保存的数据
      const saveData = selectedRows.map((row) => ({
        id: null,
        name: row.name || '',
        tp: row.tp || 3,
        checkid: searchData.value.ctlId,
        comeFrom: parseInt(searchData.value.srhTp) || 2,
        des: row.checkDes || row.des || '',
        exeRule: 1,
        checkContent: row.checkContent || '',
        itemContent: row.itemContent || '',
        item: row.item || '',
      }));
      
      console.log('Saving data:', saveData);
      
      // 调用API保存
      await batchSave(saveData);
      
      VxeUI.modal.message({ content: '加入成功', status: 'success' });
      
      // 通知父组件刷新
      emit('callback');
    } catch (error) {
      console.error('Error in saveEvent:', error);
      VxeUI.modal.message({ content: '加入失败', status: 'error' });
    } finally {
      loading.value = false;
    }
  }

  // 获取选中的行
  const getSelectRows = () => {
    const $table = tableRef.value;
    if ($table) {
      return $table.getCheckboxRecords();
    }
    return [];
  };

  // 设置分类名称
  const setRowTpName = (row: RowVO) => {
    const foundOption = tpOptions.value.find((option) => option.value * 1 === row.tp * 1);
    return foundOption?.label || row.tp;
  };

  // 搜索数据
  const searchDataHandler = ({ srhTxt, srhCol }: any) => {
    const filterSrhTxt = String(srhTxt).trim().toLowerCase();
    if (filterSrhTxt) {
      const searchProps = srhCol ? [srhCol] : ['name', 'checkContent', 'checkDes', 'itemContent', 'item'];
      tableData.value = oldData.value.filter((item) => 
        searchProps.some((key) => {
          const value = item[key as keyof RowVO];
          return value && String(value).toLowerCase().includes(filterSrhTxt);
        })
      );
    } else {
      tableData.value = oldData.value;
    }
  };

  // 单元格点击事件
  const cellClickEvent = ({ row }: any) => {
    rightWidth.value = 12;
    const data = { 
      name: row.name, 
      comeFrom: searchData.value.srhTp === '2' ? '合规库' : '内控制度',
      checkContent: row.checkContent,
      checkDes: row.checkDes,
      itemContent: row.itemContent,
      fileName: row.fileName,
      item: row.item,
    };
    
    if (refAuditInnerDetail.value?.iniData) {
      refAuditInnerDetail.value.iniData(data);
    }
  };

  // 关闭抽屉
  const closeDrawer = () => {
    console.log('Close drawer clicked');
    emit('closeDrawer');
  };

  // 刷新
  const handleRefresh = async () => {
    searchData.value.srhCol = '';
    searchData.value.srhTxt = '';
    await loadTableData();
  };

  // 搜索
  const handleSearch = async () => {
    await searchDataHandler(searchData.value);
  };

  // 切换库类型
  const handleChangeLib = async () => {
    searchData.value.srhCol = '';
    searchData.value.srhTxt = '';
    rightWidth.value = 0;
    await loadTableData();
  };

  // 转换值为整数
  const changeValeToInt = async (datas: any[]) => {
    if (!datas) return [];
    return datas.map((item) => ({
      ...item,
      value: parseInt(item.value, 10),
    }));
  };

  // 行合并方法
  const rowspanMethod: VxeTablePropTypes.SpanMethod<any> = ({ row, _rowIndex, column, visibleData }) => {
    const fields = ['checkContent', 'itemContent', 'item'];
    const cellValue = row[column.field];
    if (cellValue && fields.includes(column.field)) {
      const prevRow = visibleData[_rowIndex - 1];
      let nextRow = visibleData[_rowIndex + 1];
      if (prevRow && prevRow[column.field] === cellValue) {
        return { rowspan: 0, colspan: 0 };
      } else {
        let countRowspan = 1;
        while (nextRow && nextRow[column.field] === cellValue) {
          nextRow = visibleData[++countRowspan + _rowIndex];
        }
        if (countRowspan > 1) {
          return { rowspan: countRowspan, colspan: 1 };
        }
      }
    }
  };

  // 设置右侧宽度
  const setRightWidth = () => {
    collapsed.value = !collapsed.value;
    rightWidth.value = rightWidth.value ? 0 : 12;
  };

  // 设置文件列表
  async function setFileList() {
    const uniqueFileList = Array.from(
      new Map(
        tableData.value
          .filter(item => item.fileId && item.fileName)
          .map((item) => [item.fileId, { 
            value: item.fileName, 
            label: item.fileName, 
            filePath: item.filePath 
          }])
      ).values()
    );
    fileList.value = uniqueFileList;
  }

  // 组件挂载
  onMounted(() => {
    console.log('AuditInnerCtrlList component mounted');
  });

  // 对外暴露方法
  defineExpose({
    iniData,
  });
</script>

<style scoped>
.trigger {
  font-size: 18px;
  line-height: 40px;
  cursor: pointer;
  transition: color 0.3s;
}

.trigger:hover {
  color: #1890ff;
}
</style>