<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    @cancel="handleCancel"
    :centered="true"
    :useWrapper="true"
    :footer="null"
    :title="modalTitle"
    :defaultFullscreen="true"
  >
    <div style="height: 87vh; overflow-y: auto; overflow-x: hidden">
      <a-row style="height: 100%" :gutter="10">
        <a-col :span="24 - rightWidth" style="height: 100%">
          <vxe-toolbar ref="toolbarRef">
            <template #buttons>
              <vxe-button mode="text" content="新增" @click="insertEvent(null)" status="primary" />
              <vxe-button mode="text" content="从标准库添加" @click="addFromRuleLib" status="primary" />
              <vxe-button mode="text" status="primary" @click="selectEvent()">发起工作计划</vxe-button>
              <vxe-input
                v-model="filterName"
                type="search"
                placeholder="搜索检查方法"
                @keyup="searchEvent"
                clearable
                style="margin-left: 200px; width: 300px"
              />
              <vxe-button mode="text" status="primary" @click="searchEvent" style="margin-left: 10px">搜索</vxe-button>
              <vxe-button mode="text" status="primary" @click="refreshEvent" style="margin-left: 10px">刷新</vxe-button>
            </template>
            <template #tools>
              <a-button type="link" @click="setRightWidth">
                <menuUnfoldOutlined v-if="collapsed" class="trigger" />
                <MenuFoldOutlined v-else class="trigger" />
              </a-button>
            </template>
          </vxe-toolbar>
          <vxe-table
            keep-source
            ref="tableRef"
            size="small"
            height="92%"
            :data="dataList"
            :show-radio="true"
            :row-config="{ isCurrent: true, isHover: true, useKey: true, resizable: true }"
            @current-change="rowChangeEvent"
            :column-config="{ resizable: true, useKey: true }"
            :scroll-y="{ enabled: true, gt: 50 }"
            :edit-config="{ trigger: 'dblclick', mode: 'cell' }"
            :radio-config="{ labelField: 'name', highlight: true }"
          >
            <template #empty>
              <vxe-button mode="text" icon="vxe-icon-add" @click="insertEvent(null)">
                <div style="font-size: 20px"> 添加</div>
              </vxe-button>
            </template>
            <vxe-column type="checkbox" width="50" />
            <vxe-column field="checkid" type="html" title="" :visible="false" />
            <vxe-column
              field="tp"
              title="分类"
              width="10%"
              :edit-render="{ autofocus: '.my-input', autoselect: true }"
              :sortable="true"
              :filters="tpOptions"
            >
              <template #default="{ row }">
                {{ setRowTpName(row) }}
              </template>
              <template #edit="{ row }">
                <vxe-radio-group v-model="row.tp" style="min-height: 60px; overflow-y: hidden">
                  <vxe-radio style="margin: 5px" v-for="item in tpOptions" :key="item.value" :label="item.value * 1" :content="item.label" />
                </vxe-radio-group>
              </template>
            </vxe-column>
            <vxe-column field="name" title="监管要求" :edit-render="{ autofocus: '.my-input', autoselect: true }" :sortable="true" min-width="15%">
              <template #default="{ row }">
                <span v-html="row.name"></span>
              </template>
              <template #edit="{ row }">
                <vxe-textarea v-model="row.name" style="min-height: 60px" type="text" placeholder="请输入" size="small" clearable :rows="2" />
              </template>
            </vxe-column>
            <vxe-column field="des" sortable :edit-render="{ autofocus: '.my-input', autoselect: true }" title="备注" :visible="true" width="15%">
              <template #default="{ row }">
                {{ row.des }}
              </template>
              <template #edit="{ row }">
                <vxe-textarea v-model="row.des" type="text" style="min-height: 60px" placeholder="请输入" size="small" clearable :rows="2" />
              </template>
            </vxe-column>

            <vxe-column field="comeFrom" title="来源" width="15%" :sortable="true" :filters="comeFrom">
              <template #default="{ row }">
                {{ setRowFrom(row.comeFrom) }}
              </template>
            </vxe-column>

            <vxe-column field="exeRule" title="执行规则" :edit-render="{ autofocus: '.my-input', autoselect: true }" :visible="true" width="20%">
              <template #default="{ row }">
                {{ getExeRuleLabel(row.exeRule) }}
              </template>
              <template #edit="{ row }">
                <vxe-radio-group v-model="row.exeRule" :options="exeRules" />
              </template>
            </vxe-column>

            <vxe-column field="id" title="" :visible="false" />

            <vxe-column title="操作" width="150">
              <template #default="{ row }">
                <template v-if="hasActiveEditRow(row)">
                  <vxe-button mode="text" @click="batchSaveEvent" status="primary">保存</vxe-button>
                  <vxe-button mode="text" size="small" content="取消" @click="clearRowEvent(row)" />
                </template>
                <template v-else>
                  <vxe-button mode="text" status="primary" @click="handleDetail(row)">详情</vxe-button>
                  <vxe-button mode="text" status="primary" @click="insertEvent(row)">添加</vxe-button>
                  <vxe-button mode="text" @click="removeEvent(row)" status="primary">删除</vxe-button>
                </template>
              </template>
            </vxe-column>
          </vxe-table>
        </a-col>
        <a-col :span="rightWidth" style="height: 100%">
          <AuditInnerDetail ref="refAuditInnerDetail" />
        </a-col>
      </a-row>
    </div>

    <!-- 标准库抽屉 -->
    <a-drawer
      title="选择标准库内容"
      :closable="true"
      placement="right"
      width="90%"
      :visible="showDrawer"
      :get-container="false"
      @close="closeDrawer"
      :destroyOnClose="true"
      :style="{ position: 'absolute' }"
    >
      <AuditInnerCtrlList 
        v-if="showDrawer" 
        ref="refAuditInnerCtrlList" 
        @closeDrawer="closeDrawer" 
        @callback="callback" 
        style="height:100%" 
      />
    </a-drawer>
    
    <!-- 发起计划弹窗 -->
    <StPlanManModal @register="registerInnerModal" :showSelectorBtn="false" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, nextTick, watch } from 'vue';
  import { VxeUI } from 'vxe-table';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { getDictItemsByCode } from '/@/utils/dict/index';
  import { deleteOne, batchSave, listAll } from '../api/AuditInnerCtrlItem.api';
  import AuditInnerCtrlList from './AuditInnerCtrlItemList.vue';
  import AuditInnerDetail from './AuditInnerDetail.vue';
  import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import StPlanManModal from '/@/views/project/plan/components/StPlanManModal.vue';
  
  // 注册弹窗
  const [registerInnerModal, { openModal }] = useModal();
  const user = useUserStoreWithOut();
  
  const emit = defineEmits(['callback']);
  
  // 响应式数据
  const filterName = ref('');
  const dataList = ref([]);
  const oldList = ref([]);
  const tableRef = ref();
  const loading = ref(false);
  const tpOptions = ref([]);
  const refAuditInnerDetail = ref();
  const refAuditInnerCtrlList = ref();

  const comeFrom = ref([
    { value: 1, label: '自建' },
    { value: 2, label: '合规库' },
    { value: 3, label: '内控制度' },
  ]);

  const exeRules = ref([
    { value: 1, label: '每发生' },
    { value: 2, label: '周期性' },
    { value: 3, label: '一次性' },
  ]);

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

  const modalTitle = ref('内控要求列表');
  const checkid = ref('');
  const innerCtlObj = ref({});
  const showDrawer = ref(false);
  const rightWidth = ref(0);
  const collapsed = ref(true);

  // 注册模态框
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    console.log('Modal opened with data:', data);
    
    // 重置所有状态
    checkid.value = data.data.id;
    srhData.value = {
      srhTxt: '',
      srhCol: '',
      srhTp: '2',
      ctlId: data.data.id,
    };
    
    innerCtlObj.value = data.data;
    modalTitle.value = '内控要求列表：' + data.data.name;
    
    // 初始化数据
    await iniData({ checkid: checkid.value });
    
    // 设置模态框属性
    setModalProps({ 
      loading: false,
      confirmLoading: false
    });
  });

  // 监听抽屉显示状态
  watch(showDrawer, async (newVal) => {
    if (newVal) {
      // 等待下一个tick确保组件已渲染
      await nextTick();
      
      // 延迟初始化，确保DOM已完全渲染
      setTimeout(() => {
        if (refAuditInnerCtrlList.value && refAuditInnerCtrlList.value.iniData) {
          console.log('Initializing drawer with data:', {
            srhTxt: srhData.value.srhTxt,
            srhCol: srhData.value.srhCol,
            srhTp: srhData.value.srhTp,
            ctlId: srhData.value.ctlId,
          });
          
          refAuditInnerCtrlList.value.iniData({
            srhTxt: srhData.value.srhTxt,
            srhCol: srhData.value.srhCol,
            srhTp: srhData.value.srhTp,
            ctlId: srhData.value.ctlId,
          });
        }
      }, 100);
    }
  });

  // 初始化数据
  const iniData = async (params) => {
    try {
      loading.value = true;
      
      // 获取字典数据
      tpOptions.value = await getDictItemsByCode('rule_type');
      tpOptions.value = await changeValeToInt(tpOptions.value);
      
      // 获取列表数据
      dataList.value = oldList.value = await listAll(params);
      
      console.log('Loaded data list:', dataList.value);
    } catch (error) {
      console.error('Failed to load data:', error);
      VxeUI.modal.message({ content: '加载数据失败', status: 'error' });
    } finally {
      loading.value = false;
    }
  };

  // 行选择事件
  const rowChangeEvent = async ({ row }) => {
    emit('callback', row);
    updateHeight(row, 100);
    rightWidth.value = 12;
    
    const data = { 
      name: row.name, 
      comeFrom: setRowFrom(row.comeFrom),
      des: row.des,
      exeRule: getExeRuleLabel(row.exeRule)
    };
    
    if (refAuditInnerDetail.value?.iniData) {
      refAuditInnerDetail.value.iniData(data);
    }
  };

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

  // 删除事件
  const removeEvent = async (row) => {
    const $table = tableRef.value;
    if (!$table) return;
    
    const type = await VxeUI.modal.confirm('您确定要删除该数据?');
    if (type === 'confirm') {
      try {
        if (row.id) {
          await deleteOne({ id: row.id },function(){
            $table.remove(row);
            VxeUI.modal.message({ content: '删除成功', status: 'success' });
          });
        }
       
      } catch (error) {
        console.error('Delete failed:', error);
        VxeUI.modal.message({ content: '删除失败', status: 'error' });
      }
    }
  };

  // 插入事件
  const insertEvent = async (row) => {
    const $table = tableRef.value;
    if ($table) {
      const record = {
        id: null,
        comeFrom: 1,
        tp: row ? row.tp : 3,
        name: '',
        des: '',
        exeRule: 1,
        checkid: checkid.value,
      };
      
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow, 'tp');
    }
  };

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

  // 设置来源名称
  const setRowFrom = (key) => {
    const foundItem = comeFrom.value.find((item) => item.value === key);
    return foundItem ? foundItem.label : key;
  };

  // 取消处理
  function handleCancel() {
    showDrawer.value = false;
    rightWidth.value = 0;
    closeModal();
  }

  // 从标准库添加
  const addFromRuleLib = () => {
    console.log('Opening drawer with srhData:', srhData.value);
    console.log('checkid:', checkid.value);
    
    showDrawer.value = true;
  };

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

  // 刷新事件
  async function refreshEvent() {
    await iniData({ checkid: checkid.value });
  }

  // 批量保存事件
  async function batchSaveEvent() {
    const $table = tableRef.value;
    if (!$table) return;
    
    try {
      loading.value = true;
      const insertRecords = $table.getInsertRecords();
      const updateRecords = $table.getUpdateRecords();
      const params = [...insertRecords, ...updateRecords];

      // 过滤有效数据
      const validParams = params.filter(item => item.name && item.name.trim());
      
      if (validParams.length === 0) {
        VxeUI.modal.message({ content: '没有需要保存的数据', status: 'warning' });
        return;
      }

      // 为新增数据设置checkid
      validParams.forEach(item => {
        if (!item.checkid && checkid.value) {
          item.checkid = checkid.value;
        }
      });

      await batchSave(validParams);
      await $table.clearEdit();
      
      VxeUI.modal.message({ content: '保存成功', status: 'success' });
      await refreshEvent();
    } catch (error) {
      console.error('Save failed:', error);
      VxeUI.modal.message({ content: '保存失败', status: 'error' });
    } finally {
      loading.value = false;
    }
  }

  // 关闭抽屉
  const closeDrawer = () => {
    console.log('Closing drawer');
    showDrawer.value = false;
  };

  // 回调处理
  const callback = async () => {
    console.log('Callback received, refreshing data');
    await refreshEvent();
  };

  // 更新行高
  const updateHeight = (row, height: number) => {
    const $table = tableRef.value;
    if ($table) {
      $table.setRowHeight(row, height);
    }
  };

  // 搜索事件
  const searchEvent = () => {
    const filterVal = String(filterName.value).trim().toLowerCase();
    if (filterVal) {
      const searchProps = ['name', 'des'];
      dataList.value = oldList.value.filter((item) => 
        searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1)
      );
    } else {
      dataList.value = oldList.value;
    }
  };

  // 详情处理
  function handleDetail(row) {
    rightWidth.value = 12;
    const data = { 
      name: row.name, 
      comeFrom: setRowFrom(row.comeFrom),
      des: row.des,
      exeRule: getExeRuleLabel(row.exeRule)
    };
    
    if (refAuditInnerDetail.value?.iniData) {
      refAuditInnerDetail.value.iniData(data);
    }
  }

  // 选择事件
  const selectEvent = async () => {
    const $table = tableRef.value;
    if ($table) {
      const selectRecords = $table.getCheckboxRecords();
      if (selectRecords.length > 0) {
        openModal(true, {
          isUpdate: false,
          showFooter: true,
          record: selectRecords,
        });
      } else {
        VxeUI.modal.message({
          content: '请选择数据',
          status: 'info',
        });
      }
    }
  };

  // 检查是否有编辑行
  const hasActiveEditRow = (row) => {
    const $table = tableRef.value;
    if ($table) {
      return $table.isEditByRow(row);
    }
    return false;
  };

  // 清除行事件
  const clearRowEvent = (row) => {
    const $table = tableRef.value;
    if ($table) {
      $table.clearEdit().then(() => {
        $table.revertData(row);
      });
    }
  };

  // 获取执行规则标签
  const getExeRuleLabel = (val) => {
    const result = exeRules.value.find((item) => item.value == val);
    return result ? result.label : '';
  };
</script>