/*
 * @Description: 查核要点管理页面
 */
import React, { useEffect, useRef, useState } from 'react';
import {
  Input,
  message,
  Card,
  Button,
  Dropdown,
  Menu,
  Tabs,
  Modal,
  Popconfirm,
  Select,
  Table,
} from 'antd';
import { ActionType, ProColumns } from '@ant-design/pro-table';

const { TabPane } = Tabs;
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import {
  ModalForm,
  ProFormDigit,
  ProFormText,
  ProFormTextArea,
  ProFormSelect,
} from '@ant-design/pro-form';
import { PlusOutlined, SearchOutlined, MoreOutlined } from '@ant-design/icons';
import { createFromIconfontCN } from '@ant-design/icons';
import './style.less';
import {
  getTreeData,
  getTableData,
  addTableData,
  deleteTableData,
  getPointCategoryList,
  addCheckpoint,
  updateCheckpoint,
  deleteCheckpoint,
  getCheckpointPendingDept,
  addCheckpointDept,
  delCheckpointDept,
  getCheckpointGroup,
  getCheckpointPendingGroup,
  addCheckpointGroup,
  delCheckpointGroup,
  getCheckpointItem,
  getCheckpointPendingItem,
  addCheckpointItem,
  delCheckpointItem,
  getCheckpointRule,
  getReviewRuleVersion,
  getCheckpointPendingRule,
  addCheckpointRule,
  delCheckpointRule,
} from './service';
import { getExpandedSelectedNodes, handleTreeSelection } from '@/utils/tooljs';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

// 添加查核组弹窗组件 - 移到主组件外部
const AddCheckpointGroupModal: React.FC<{
  selectedDept: any;
  onSuccess: () => void;
}> = ({ selectedDept, onSuccess }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedGroupIds, setSelectedGroupIds] = useState<React.Key[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const groupTableRef = useRef<ActionType>();

  // 获取可添加的查核组列表
  const getGroupSelectData = async (params: any) => {
    if (!selectedDept?.id) {
      return {
        data: [],
        success: true,
        total: 0,
      };
    }

    try {
      const { current = 1, pageSize = 10 } = params;
      const res = await getCheckpointPendingGroup(
        selectedDept.id,
        searchKeyword,
        current,
        pageSize,
      );

      return {
        data: res.list,
        success: res.success,
        total: res.total,
      };
    } catch (error) {
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  // 打开弹窗时重置状态
  const handleOpenModal = () => {
    setModalVisible(true);
    setSelectedGroupIds([]);
    setSearchKeyword('');

    // 延迟触发表格重新加载
    setTimeout(() => {
      groupTableRef.current?.reload();
    }, 100);
  };

  // 提交添加
  const handleSubmit = async () => {
    if (selectedGroupIds.length === 0) {
      message.warning('请至少选择一个查核组');
      return;
    }

    try {
      await addCheckpointGroup(selectedDept.id, selectedGroupIds as number[]);
      message.success(`已添加 ${selectedGroupIds.length} 个查核组`);
      setModalVisible(false);
      onSuccess(); // 调用成功回调
    } catch (error) {
      message.error('添加失败');
    }
  };

  // 定义表格列
  const groupSelectColumns: ProColumns[] = [
    {
      title: '查核组名称',
      dataIndex: 'name',
      align: 'left',
      ellipsis: true,
    },
    {
      title: '组长',
      dataIndex: 'groupManagerName',
      align: 'left',
      width: 120,
    },
  ];

  return (
    <>
      <Button
        type="primary"
        className="add-btn"
        size="small"
        onClick={handleOpenModal}
      >
        添加
      </Button>

      <Modal
        title={`选择查核组（${selectedDept?.name || ''}）`}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={352}
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            onClick={handleSubmit}
            disabled={selectedGroupIds.length === 0}
            style={{
              backgroundColor: '#3377FF',
              borderColor: '#3377FF',
              color: '#FFFFFF',
            }}
          >
            确定
            {selectedGroupIds.length > 0 ? ` (${selectedGroupIds.length})` : ''}
          </Button>,
        ]}
        className="employee-select-modal"
      >
        <div style={{ marginBottom: 8 }}>
          <Input
            placeholder="请输入"
            value={searchKeyword}
            allowClear
            onChange={(e) => {
              setSearchKeyword(e.target.value);
              if (e.target.value === '') {
                // 清空搜索时自动刷新
                groupTableRef.current?.reload();
              }
            }}
            onPressEnter={() => groupTableRef.current?.reload()}
            suffix={
              <SearchOutlined
                onClick={() => groupTableRef.current?.reload()}
                style={{ cursor: 'pointer', color: '#99A6BF' }}
              />
            }
            style={{ width: '100%' }}
          />
        </div>

        <KCIMTable
          actionRef={groupTableRef}
          columns={groupSelectColumns}
          request={getGroupSelectData}
          rowKey="id"
          search={false}
          pagination={{
            simple: true,
            pageSize: 10,
            size: 'small',
            showTotal: () => null,
          }}
          rowSelection={{
            selectedRowKeys: selectedGroupIds,
            onChange: (selectedRowKeys) => {
              setSelectedGroupIds(selectedRowKeys);
            },
          }}
          tableAlertRender={false}
          scroll={{ y: 360 }}
        />
      </Modal>
    </>
  );
};

// 添加查核项弹窗组件 - 移到主组件外部
const AddCheckpointItemModal: React.FC<{
  selectedDept: any;
  onSuccess: () => void;
}> = ({ selectedDept, onSuccess }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedItemIds, setSelectedItemIds] = useState<React.Key[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const itemTableRef = useRef<ActionType>();

  // 获取可添加的查核项列表
  const getItemSelectData = async (params: any) => {
    if (!selectedDept?.id) {
      return {
        data: [],
        success: true,
        total: 0,
      };
    }

    try {
      const { current = 1, pageSize = 10 } = params;
      const res = await getCheckpointPendingItem(
        selectedDept.id,
        searchKeyword,
        current,
        pageSize,
      );

      return {
        data: res.list,
        success: res.success,
        total: res.total,
      };
    } catch (error) {
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  // 打开弹窗时重置状态
  const handleOpenModal = () => {
    setModalVisible(true);
    setSelectedItemIds([]);
    setSearchKeyword('');

    // 延迟触发表格重新加载
    setTimeout(() => {
      itemTableRef.current?.reload();
    }, 100);
  };

  // 提交添加
  const handleSubmit = async () => {
    if (selectedItemIds.length === 0) {
      message.warning('请至少选择一个查核项');
      return;
    }

    try {
      await addCheckpointItem(selectedDept.id, selectedItemIds as number[]);
      message.success(`已添加 ${selectedItemIds.length} 个查核项`);
      setModalVisible(false);
      onSuccess(); // 调用成功回调
    } catch (error) {
      message.error('添加失败');
    }
  };

  // 定义表格列
  const itemSelectColumns: ProColumns[] = [
    {
      title: '查核项',
      dataIndex: 'name',
      align: 'left',
      ellipsis: true,
    },
    {
      title: '应知应会',
      dataIndex: 'rightAnswerText',
      align: 'left',
      ellipsis: true,
    },
  ];

  return (
    <>
      <Button
        type="primary"
        className="add-btn"
        size="small"
        onClick={handleOpenModal}
      >
        添加
      </Button>

      <Modal
        title={`选择查核项（${selectedDept?.name || ''}）`}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={632}
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            onClick={handleSubmit}
            disabled={selectedItemIds.length === 0}
            style={{
              backgroundColor: '#3377FF',
              borderColor: '#3377FF',
              color: '#FFFFFF',
            }}
          >
            确定
            {selectedItemIds.length > 0 ? ` (${selectedItemIds.length})` : ''}
          </Button>,
        ]}
        className="employee-select-modal"
      >
        <div style={{ marginBottom: 8 }}>
          <Input
            placeholder="请输入"
            value={searchKeyword}
            allowClear
            onChange={(e) => {
              setSearchKeyword(e.target.value);
              if (e.target.value === '') {
                // 清空搜索时自动刷新
                itemTableRef.current?.reload();
              }
            }}
            onPressEnter={() => itemTableRef.current?.reload()}
            suffix={
              <SearchOutlined
                onClick={() => itemTableRef.current?.reload()}
                style={{ cursor: 'pointer', color: '#99A6BF' }}
              />
            }
            style={{ width: '100%' }}
          />
        </div>

        <KCIMTable
          actionRef={itemTableRef}
          columns={itemSelectColumns}
          request={getItemSelectData}
          rowKey="id"
          search={false}
          pagination={{
            simple: true,
            pageSize: 10,
            size: 'small',
            showTotal: () => null,
          }}
          rowSelection={{
            selectedRowKeys: selectedItemIds,
            onChange: (selectedRowKeys) => {
              setSelectedItemIds(selectedRowKeys);
            },
          }}
          tableAlertRender={false}
          scroll={{ y: 360 }}
        />
      </Modal>
    </>
  );
};

// 添加条文条款弹窗组件
const AddCheckpointRuleModal: React.FC<{
  selectedDept: any;
  onSuccess: () => void;
}> = ({ selectedDept, onSuccess }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedRuleIds, setSelectedRuleIds] = useState<React.Key[]>([]);
  const [selectedRuleData, setSelectedRuleData] = useState<any[]>([]); // 存储完整的选中条文数据
  const [prevSelectedRuleIds, setPrevSelectedRuleIds] = useState<React.Key[]>(
    [],
  ); // 存储之前的选中项
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedVersion, setSelectedVersion] = useState<string>('');
  const [versionOptions, setVersionOptions] = useState<any[]>([]);
  const [allTableData, setAllTableData] = useState<any[]>([]); // 存储表格中的所有数据
  const [modalExpandedRowKeys, setModalExpandedRowKeys] = useState<React.Key[]>(
    [],
  ); // 弹窗中的展开状态
  const ruleTableRef = useRef<ActionType>();

  // 获取版本选项数据
  const fetchVersionOptions = async () => {
    try {
      const options = await getReviewRuleVersion();
      setVersionOptions(options);
      // 默认选择第一个版本
      if (options.length > 0) {
        setSelectedVersion(options[0].value);
      }
    } catch (error) {
      message.error('获取版本选项失败');
    }
  };

  // 获取可添加的条文条款列表
  const getRuleSelectData = async (params: any) => {
    if (!selectedDept?.id || !selectedVersion) {
      return {
        data: [],
        success: true,
        total: 0,
      };
    }

    try {
      const { current = 1, pageSize = 10 } = params;
      const res = await getCheckpointPendingRule(
        selectedDept.id,
        selectedVersion,
        searchKeyword,
        current,
        pageSize,
      );

      // 保存表格数据，用于父子节点处理
      setAllTableData(res.list || []);

      // 获取前5个顶层节点的展开键（只展开一级，不递归）
      const getTop5ExpandableKeys = (data: any[]): React.Key[] => {
        const keys: React.Key[] = [];
        const topLevelItems = data.slice(0, 5); // 只取前5个
        topLevelItems.forEach((item) => {
          if (item.children && item.children.length > 0) {
            keys.push(item.id);
          }
        });
        return keys;
      };

      // 设置弹窗中的默认展开前5个顶层节点
      const top5Keys = getTop5ExpandableKeys(res.list || []);
      setModalExpandedRowKeys(top5Keys);

      return {
        data: res.list,
        success: res.success,
        total: res.total,
      };
    } catch (error) {
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  // 加载条文条款数据
  const loadRuleData = async () => {
    if (!selectedDept?.id || !selectedVersion) {
      setAllTableData([]);
      return;
    }

    try {
      const res = await getCheckpointPendingRule(
        selectedDept.id,
        selectedVersion,
        searchKeyword,
        1,
        100, // 加载更多数据用于测试
      );

      setAllTableData(res.list || []);
    } catch (error) {
      setAllTableData([]);
    }
  };

  // 打开弹窗时重置状态并获取版本数据
  const handleOpenModal = async () => {
    setModalVisible(true);
    setSelectedRuleIds([]);
    setSelectedRuleData([]);
    setPrevSelectedRuleIds([]); // 清空之前的选中项
    setSearchKeyword('');
    setAllTableData([]); // 清空表格数据
    setModalExpandedRowKeys([]); // 清空弹窗展开状态

    // 获取版本选项
    await fetchVersionOptions();

    // 延迟触发表格加载，确保版本选择完成后能正确加载数据
    setTimeout(() => {
      ruleTableRef.current?.reload();
    }, 200);
  };

  // 当版本选择后加载数据
  useEffect(() => {
    if (modalVisible && selectedVersion) {
      // 延迟触发表格重新加载，确保组件已经渲染完成
      setTimeout(() => {
        ruleTableRef.current?.reload();
      }, 100);
    }
  }, [modalVisible, selectedVersion, searchKeyword]);

  // 版本变化时重新加载数据
  const handleVersionChange = (version: string) => {
    setSelectedVersion(version);
    setSelectedRuleIds([]); // 清空选中项
    setSelectedRuleData([]); // 清空选中数据
    setPrevSelectedRuleIds([]); // 清空之前的选中项
    setAllTableData([]); // 清空表格数据
    setTimeout(() => {
      ruleTableRef.current?.reload();
    }, 100);
  };

  // 提交添加
  const handleSubmit = async () => {
    if (selectedRuleIds.length === 0) {
      message.warning('请至少选择一个条文条款');
      return;
    }

    if (!selectedVersion) {
      message.warning('请选择版本');
      return;
    }

    try {
      // 使用工具函数获取展开后的节点（包含父节点选中时的所有子节点）
      const expandedNodes = getExpandedSelectedNodes(
        selectedRuleData,
        allTableData,
        'children',
      );

      // 使用numStr作为id传递给后端，去重处理
      const uniqueRuleDataWithNumStr = Array.from(
        new Set(expandedNodes.map((item) => item.numStr || item.id)),
      );

      await addCheckpointRule(
        selectedDept.id,
        uniqueRuleDataWithNumStr,
        selectedVersion,
      );
      message.success(`已添加 ${uniqueRuleDataWithNumStr.length} 个条文条款`);
      setModalVisible(false);
      onSuccess(); // 调用成功回调
    } catch (error) {
      message.error('添加失败');
    }
  };

  // 定义表格列
  const ruleSelectColumns: ProColumns[] = [
    {
      title: '条文四码',
      dataIndex: 'numStr',
      width: 200,
      render: (text: any) => text || '-',
    },
    {
      title: '条文内容',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '版本',
      dataIndex: 'version',
      width: 120,
      ellipsis: true,
    },
  ];

  return (
    <>
      <Button
        type="primary"
        className="add-btn"
        size="small"
        onClick={handleOpenModal}
      >
        添加
      </Button>

      <Modal
        title={`选择条文条款（${selectedDept?.name || ''}）`}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={832}
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            onClick={handleSubmit}
            disabled={selectedRuleIds.length === 0}
            style={{
              backgroundColor: '#3377FF',
              borderColor: '#3377FF',
              color: '#FFFFFF',
            }}
          >
            确定
            {selectedRuleIds.length > 0 ? ` (${selectedRuleIds.length})` : ''}
          </Button>,
        ]}
        className="employee-select-modal"
      >
        <div
          style={{
            marginBottom: 16,
            display: 'flex',
            gap: 8,
            alignItems: 'center',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Select
              value={selectedVersion}
              onChange={handleVersionChange}
              style={{ width: 120 }}
              placeholder="请选择版本"
              options={versionOptions}
            />
          </div>
          <div style={{ flex: 1 }}>
            <Input
              placeholder="请输入条文内容"
              value={searchKeyword}
              allowClear
              onChange={(e) => {
                setSearchKeyword(e.target.value);
                if (e.target.value === '') {
                  // 清空搜索时自动刷新
                  ruleTableRef.current?.reload();
                }
              }}
              onPressEnter={() => ruleTableRef.current?.reload()}
              suffix={
                <SearchOutlined
                  onClick={() => ruleTableRef.current?.reload()}
                  style={{ cursor: 'pointer', color: '#99A6BF' }}
                />
              }
              style={{ width: '100%' }}
            />
          </div>
        </div>

        <KCIMTable
          actionRef={ruleTableRef}
          columns={ruleSelectColumns}
          request={getRuleSelectData}
          rowKey="id"
          search={false}
          pagination={{
            simple: true,
            pageSize: 10,
            size: 'small',
            showTotal: () => null,
          }}
          rowSelection={{
            selectedRowKeys: selectedRuleIds,
            checkStrictly: false, // 启用父子关联选择
            onChange: (selectedRowKeys, selectedRows) => {
              // 使用Ant Design内置的父子关联功能
              setSelectedRuleIds(selectedRowKeys);
              setSelectedRuleData(selectedRows);
            },
          }}
          tableAlertRender={false}
          scroll={{ y: 360 }}
          expandable={{
            expandedRowKeys: modalExpandedRowKeys, // 受控的展开状态
            onExpandedRowsChange: (expandedKeys) => {
              setModalExpandedRowKeys([...expandedKeys]);
            },
            expandRowByClick: false, // 禁止点击行展开
            childrenColumnName: 'children', // 指定子数据的字段名
            indentSize: 20, // 设置缩进大小
          }}
        />
      </Modal>
    </>
  );
};

// 主页面组件
const CheckPointMana: React.FC = () => {
  // 左侧分组/树数据
  const [treeData, setTreeData] = useState<any[]>([]);
  const [filteredTreeData, setFilteredTreeData] = useState<any[]>([]);
  const [selectedDept, setSelectedDept] = useState<any>(null);
  const [treeSearchKeywords, setTreeSearchKeywords] = useState<string>('');
  const [hoveredNode, setHoveredNode] = useState<string | null>(null);
  const [openDropdownNode, setOpenDropdownNode] = useState<string | null>(null);

  // 分页加载相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);

  // 表格相关
  const [searchKeywords, setSearchKeywords] = useState<string>('');
  const [activeTab, setActiveTab] = useState('units'); // 当前活动标签页
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]); // 选中的行
  const [pointCategoryOptions, setPointCategoryOptions] = useState<any[]>([]); // 要点分类选项
  const tableRef = useRef<ActionType>();

  // 查核组相关
  const [groupSearchKeywords, setGroupSearchKeywords] = useState<string>('');
  const [selectedGroupKeys, setSelectedGroupKeys] = useState<string[]>([]);
  const groupTableRef = useRef<ActionType>();

  // 查核项相关
  const [itemSearchKeywords, setItemSearchKeywords] = useState<string>('');
  const [selectedItemKeys, setSelectedItemKeys] = useState<string[]>([]);
  const itemTableRef = useRef<ActionType>();

  // 条文条款相关
  const [ruleSearchKeywords, setRuleSearchKeywords] = useState<string>('');
  const [selectedRuleKeys, setSelectedRuleKeys] = useState<string[]>([]);
  const [selectedRuleData, setSelectedRuleData] = useState<any[]>([]); // 存储完整的选中条文数据
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]); // 控制展开的行
  const [allRuleTableData, setAllRuleTableData] = useState<any[]>([]); // 存储条文条款表格的全部数据
  const ruleTableRef = useRef<ActionType>();

  // 右侧内容区ref和操作栏定位状态
  const deptContentRef = useRef<HTMLDivElement>(null);
  const [actionBarStyle, setActionBarStyle] = useState<{
    left: number;
    width: number;
  }>({ left: 0, width: 0 });

  // 更新操作栏定位，支持ResizeObserver
  const updateActionBarPosition = () => {
    if (deptContentRef.current) {
      const rect = deptContentRef.current.getBoundingClientRect();
      setActionBarStyle({ left: rect.left, width: rect.width });
    }
  };

  useEffect(() => {
    updateActionBarPosition();
    window.addEventListener('resize', updateActionBarPosition);
    window.addEventListener('scroll', updateActionBarPosition, true);
    let resizeObserver: ResizeObserver | null = null;
    if (deptContentRef.current && typeof ResizeObserver !== 'undefined') {
      resizeObserver = new ResizeObserver(() => {
        updateActionBarPosition();
      });
      resizeObserver.observe(deptContentRef.current);
    }
    return () => {
      window.removeEventListener('resize', updateActionBarPosition);
      window.removeEventListener('scroll', updateActionBarPosition, true);
      if (resizeObserver && deptContentRef.current) {
        resizeObserver.unobserve(deptContentRef.current);
        resizeObserver.disconnect();
      }
    };
  }, []);

  // 获取左侧分组/树数据
  useEffect(() => {
    fetchTreeData();
    // 初始化时也获取分类数据，确保用户点击新增时有选项
    fetchPointCategoryOptions();
  }, []);

  const fetchTreeData = async (
    current: number = 1,
    isLoadMore: boolean = false,
    keyword?: string,
    pageSize: number = 50,
  ) => {
    try {
      setLoading(true);
      // 如果传入了keyword参数，使用它；否则使用状态中的treeSearchKeywords
      const searchKeyword =
        keyword !== undefined ? keyword : treeSearchKeywords;
      const res = await getTreeData(current, searchKeyword, pageSize);
      if (res) {
        // 转换数据格式，符合树形组件需要的格式，同时保留原始数据
        const transformedData = res.list.map((item: any) => ({
          title: item.name,
          key: item.id,
          type: 'checkPoint', // 标记为查核要点
          // 保留原始数据
          id: item.id,
          name: item.name,
          sort: item.sort,
          pointCategory: item.pointCategory,
        }));

        if (isLoadMore) {
          // 加载更多时，追加到现有数据
          setTreeData((prev) => [...prev, ...transformedData]);
          setFilteredTreeData((prev) => [...prev, ...transformedData]);
        } else {
          // 首次加载或搜索时，替换数据
          setTreeData(transformedData);
          setFilteredTreeData(transformedData);

          // 默认选中第一个
          if (transformedData.length > 0) {
            setSelectedDept(transformedData[0]);
          }
        }

        // 更新分页信息
        setTotalCount(res.totalCount);
        setCurrentPage(current);
        setHasMore(res.list.length === pageSize && current * pageSize < res.totalCount);
      }
    } catch (error) {
      message.error('获取要点分类失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取要点分类选项
  const fetchPointCategoryOptions = async () => {
    try {
      const res = await getPointCategoryList();
      setPointCategoryOptions(res);
    } catch (error) {
      message.error('获取要点分类选项失败');
    }
  };

  // 监听选中项变化，刷新表格
  useEffect(() => {
    if (selectedDept?.key) {
      tableRef.current?.reload();
    }
  }, [selectedDept?.key]);

  // 树形数据搜索过滤
  const filterTreeData = (data: any[], keywords: string) => {
    if (!keywords.trim()) {
      return data;
    }
    return data.filter((item) =>
      item.title.toLowerCase().includes(keywords.toLowerCase()),
    );
  };

  // 处理树形搜索 - 点击搜索图标或回车时触发
  const handleTreeSearch = () => {
    setCurrentPage(1);
    setHasMore(true);
    fetchTreeData(1, false);
  };

  // 处理搜索输入框的变化
  const handleSearchInputChange = (value: string) => {
    setTreeSearchKeywords(value);
    // 如果清空搜索，立即重新加载数据，传入空字符串确保清空搜索
    if (!value.trim()) {
      setCurrentPage(1);
      setHasMore(true);
      // 直接传入空字符串，而不是依赖状态更新
      fetchTreeData(1, false, '', 50);
    }
  };

  // 加载更多数据
  const loadMoreData = () => {
    if (!loading && hasMore) {
      const nextPage = currentPage + 1;
      fetchTreeData(nextPage, true, undefined, 50);
    }
  };

  // 滚动事件处理
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    // 当滚动到底部附近时加载更多数据
    if (scrollHeight - scrollTop <= clientHeight + 10) {
      loadMoreData();
    }
  };

  // 新增查核要点弹窗组件
  const AddCheckPointModal = () => {
    return (
      <ModalForm
        title="新增查核要点"
        width={400}
        trigger={<Button icon={<PlusOutlined />} className="add-button" />}
        onFinish={async (val: any) => {
          try {
            await addCheckpoint(val);
            message.success('新增成功！');
            fetchTreeData(1, false); // 重新获取数据
            return true;
          } catch (error) {
            message.error('新增失败');
            return false;
          }
        }}
        modalProps={{
          destroyOnClose: true,
          maskClosable: false,
        }}
      >
        <ProFormText
          name="name"
          label="查核要点"
          placeholder="请输入"
          rules={[{ required: true, message: '查核要点不能为空!' }]}
        />
        <ProFormDigit
          name="sort"
          label="序号"
          placeholder="请输入序号"
          min={0}
          rules={[{ required: true, message: '序号不能为空!' }]}
        />
        <ProFormSelect
          name="pointCategory"
          label="要点分类"
          placeholder="请选择"
          options={pointCategoryOptions}
          rules={[{ required: true, message: '要点分类不能为空!' }]}
        />
      </ModalForm>
    );
  };

  // 更多操作菜单
  const getMoreMenu = (node: any) => (
    <Menu>
      <Menu.Item key="edit">
        <ModalForm
          title="编辑查核要点"
          width={400}
          initialValues={{
            name: node.name,
            sort: node.sort,
            pointCategory: node.pointCategory,
          }}
          trigger={<span>编辑</span>}
          onFinish={async (val: any) => {
            try {
              await updateCheckpoint({
                id: node.id,
                name: val.name,
                sort: val.sort,
                pointCategory: val.pointCategory,
              });
              message.success('编辑成功！');
              fetchTreeData(1, false);
              return true;
            } catch (error) {
              message.error('编辑失败');
              return false;
            }
          }}
          modalProps={{ destroyOnClose: true }}
        >
          <ProFormText
            name="name"
            label="查核要点"
            placeholder="请输入"
            rules={[{ required: true, message: '查核要点不能为空!' }]}
          />
          <ProFormDigit
            name="sort"
            label="序号"
            placeholder="请输入序号"
            min={0}
            rules={[{ required: true, message: '序号不能为空!' }]}
          />
          <ProFormSelect
            name="pointCategory"
            label="要点分类"
            placeholder="请选择"
            options={pointCategoryOptions}
            rules={[{ required: true, message: '要点分类不能为空!' }]}
          />
        </ModalForm>
      </Menu.Item>
      <Menu.Item key="delete">
        <a
          onClick={() => {
            // 删除确认
            const modal = Modal.confirm({
              title: '确认删除',
              content: `确定要删除查核要点"${node.name}"吗？`,
              okText: '确定',
              cancelText: '取消',
              onOk: async () => {
                try {
                  await deleteCheckpoint(node.id);
                  message.success('删除成功！');
                  fetchTreeData(1, false);
                } catch (error) {
                  message.error('删除失败');
                }
              },
            });
          }}
        >
          删除
        </a>
      </Menu.Item>
    </Menu>
  );

  // 添加查核单位弹窗组件
  const AddCheckpointDeptModal = () => {
    const [modalVisible, setModalVisible] = useState(false);
    const [selectedDeptIds, setSelectedDeptIds] = useState<React.Key[]>([]);
    const [searchKeyword, setSearchKeyword] = useState('');
    const deptTableRef = useRef<ActionType>();

    // 获取可添加的查核单位列表
    const getDeptSelectData = async (params: any) => {
      if (!selectedDept?.id) {
        return {
          data: [],
          success: true,
          total: 0,
        };
      }

      try {
        const { current = 1, pageSize = 10 } = params;
        const res = await getCheckpointPendingDept(
          selectedDept.id,
          searchKeyword,
          current,
          pageSize,
        );

        return {
          data: res.list,
          success: res.success,
          total: res.total,
        };
      } catch (error) {
        return {
          data: [],
          success: false,
          total: 0,
        };
      }
    };

    // 打开弹窗时重置状态
    const handleOpenModal = () => {
      setModalVisible(true);
      setSelectedDeptIds([]);
      setSearchKeyword('');

      // 延迟触发表格重新加载
      setTimeout(() => {
        deptTableRef.current?.reload();
      }, 100);
    };

    // 提交添加
    const handleSubmit = async () => {
      if (selectedDeptIds.length === 0) {
        message.warning('请至少选择一个查核单位');
        return;
      }

      try {
        await addCheckpointDept(selectedDept.id, selectedDeptIds as number[]);
        message.success(`已添加 ${selectedDeptIds.length} 个查核单位`);
        setModalVisible(false);
        tableRef.current?.reload(); // 刷新表格
      } catch (error) {
        message.error('添加失败');
      }
    };

    // 定义表格列
    const deptSelectColumns: ProColumns[] = [
      {
        title: '查核单位名称',
        dataIndex: 'name',
        align: 'left',
        ellipsis: true,
      },
      {
        title: '单位负责人',
        dataIndex: 'deptManagerName',
        align: 'left',
        width: 120,
      },
    ];

    return (
      <>
        <Button
          type="primary"
          className="add-btn"
          size="small"
          onClick={handleOpenModal}
        >
          添加
        </Button>

        <Modal
          title={`选择查核单位（${selectedDept?.name || ''}）`}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          width={352}
          footer={[
            <Button key="cancel" onClick={() => setModalVisible(false)}>
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={handleSubmit}
              disabled={selectedDeptIds.length === 0}
              style={{
                backgroundColor: '#3377FF',
                borderColor: '#3377FF',
                color: '#FFFFFF',
              }}
            >
              确定
              {selectedDeptIds.length > 0 ? ` (${selectedDeptIds.length})` : ''}
            </Button>,
          ]}
          className="employee-select-modal"
        >
          <div style={{ marginBottom: 8 }}>
            <Input
              placeholder="请输入"
              value={searchKeyword}
              allowClear
              onChange={(e) => {
                setSearchKeyword(e.target.value);
                if (e.target.value === '') {
                  // 清空搜索时自动刷新
                  deptTableRef.current?.reload();
                }
              }}
              onPressEnter={() => deptTableRef.current?.reload()}
              suffix={
                <SearchOutlined
                  onClick={() => deptTableRef.current?.reload()}
                  style={{ cursor: 'pointer', color: '#99A6BF' }}
                />
              }
              style={{ width: '100%' }}
            />
          </div>

          <KCIMTable
            actionRef={deptTableRef}
            columns={deptSelectColumns}
            request={getDeptSelectData}
            rowKey="id"
            search={false}
            pagination={{
              simple: true,
              pageSize: 10,
              size: 'small',
              showTotal: () => null,
            }}
            rowSelection={{
              selectedRowKeys: selectedDeptIds,
              onChange: (selectedRowKeys) => {
                setSelectedDeptIds(selectedRowKeys);
              },
            }}
            tableAlertRender={false}
            scroll={{ y: 360 }}
          />
        </Modal>
      </>
    );
  };

  // 左侧树形组件渲染
  const renderDeptTree = () => {
    return (
      <div className="dept-tree">
        <div className="search-wrapper">
          <Input
            placeholder="要点名称"
            suffix={
              <SearchOutlined
                style={{ color: '#99A6BF', cursor: 'pointer' }}
                onClick={handleTreeSearch}
              />
            }
            className="search-input"
            value={treeSearchKeywords}
            onChange={(e) => handleSearchInputChange(e.target.value)}
            onPressEnter={handleTreeSearch}
            allowClear
          />
          <AddCheckPointModal />
        </div>

        <div className="dept-list" onScroll={handleScroll}>
          {filteredTreeData.map((item) => (
            <div key={item.key} className="dept-group">
              <div
                className={`dept-leaf ${
                  selectedDept?.key === item.key ? 'selected' : ''
                }`}
                onClick={() => {
                  setSelectedDept(item);
                }}
                onMouseEnter={() => setHoveredNode(item.key)}
                onMouseLeave={() => setHoveredNode(null)}
              >
                <span className="dept-leaf-title">
                  {item.sort !== undefined && item.sort !== null && (
                    <span className="dept-sort-circle">{item.sort}</span>
                  )}
                  <span className="dept-leaf-text">{item.title}</span>
                </span>
                {(selectedDept?.key === item.key ||
                  hoveredNode === item.key ||
                  openDropdownNode === item.key) && (
                  <Dropdown
                    overlay={getMoreMenu(item)}
                    trigger={['click']}
                    placement="bottomRight"
                    overlayClassName="check-unit-add-dropdown"
                    onVisibleChange={(visible) => {
                      if (visible) {
                        setOpenDropdownNode(item.key);
                      } else {
                        setOpenDropdownNode(null);
                      }
                    }}
                  >
                    <Button
                      type="text"
                      icon={<MoreOutlined />}
                      className="more-button"
                      onClick={(e) => e.stopPropagation()}
                    />
                  </Dropdown>
                )}
              </div>
            </div>
          ))}

          {/* 加载更多提示 */}
          {loading && (
            <div className="loading-more">
              <span>加载中...</span>
            </div>
          )}

          {!hasMore && filteredTreeData.length > 0 && (
            <div className="no-more-data">
              <span>已加载全部数据（共{totalCount}条）</span>
            </div>
          )}
        </div>
      </div>
    );
  };

  // 处理标签页切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setSelectedRowKeys([]); // 切换标签页时清空选中项
    setSelectedGroupKeys([]); // 切换标签页时清空查核组选中项
    setSelectedItemKeys([]); // 切换标签页时清空查核项选中项
    setSelectedRuleKeys([]); // 切换标签页时清空条文条款选中项
    setSelectedRuleData([]); // 切换标签页时清空条文条款选中数据
    setAllRuleTableData([]); // 切换标签页时清空条文条款全部数据
  };

  // 查核单位表格列定义
  const deptColumns: ProColumns[] = [
    {
      title: '查核单位名称',
      dataIndex: 'deptName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '单位负责人',
      dataIndex: 'deptManagerName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 100,
      valueType: 'option',
      render: (_: any, record: any) => [
        <Popconfirm
          title="确认删除该查核单位吗？"
          onConfirm={async () => {
            try {
              await delCheckpointDept([record.id]);
              message.success('删除成功！');
              tableRef.current?.reload();
            } catch (error) {
              message.error('删除失败');
            }
          }}
          okText="确定"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 查核组表格列定义
  const groupColumns: ProColumns[] = [
    {
      title: '查核组',
      dataIndex: 'checkGroupName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '组长',
      dataIndex: 'groupManagerName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 100,
      valueType: 'option',
      render: (_: any, record: any) => [
        <Popconfirm
          title="确认删除该查核组吗？"
          onConfirm={async () => {
            try {
              await delCheckpointGroup([record.id]);
              message.success('删除成功！');
              groupTableRef.current?.reload();
            } catch (error) {
              message.error('删除失败');
            }
          }}
          okText="确定"
          cancelText="取消"
          key="delete"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 查核项表格列定义
  const itemColumns: ProColumns[] = [
    {
      title: '查核项',
      dataIndex: 'checkItemName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '应知应会',
      dataIndex: 'rightAnswerText',
      width: 300,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 100,
      valueType: 'option',
      render: (_: any, record: any) => [
        <Popconfirm
          title="确认删除该查核项吗？"
          onConfirm={async () => {
            try {
              await delCheckpointItem([record.id]);
              message.success('删除成功！');
              itemTableRef.current?.reload();
            } catch (error) {
              message.error('删除失败');
            }
          }}
          okText="确定"
          cancelText="取消"
          key="delete"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 条文条款表格列定义
  const ruleColumns: ProColumns[] = [
    {
      title: '条文四码',
      dataIndex: 'numStr',
      width: 200,
      render: (text: any) => text || '-',
    },
    {
      title: '条文内容',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '版本',
      dataIndex: 'version',
      width: 120,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 100,
      valueType: 'option',
      render: (_: any, record: any) => [
        <Popconfirm
          title="确认删除该条文条款吗？删除父节点时会同时删除所有子节点"
          onConfirm={async () => {
            try {
              // 使用工具函数获取当前节点及其所有子节点
              const expandedNodes = getExpandedSelectedNodes(
                [record], // 当前选中的节点
                allRuleTableData, // 全部表格数据
                'children', // 子节点字段名
              );

              // 使用numStr作为id传递给后端，去重处理
              const uniqueRuleDataWithNumStr = Array.from(
                new Set(expandedNodes.map((item) => item.numStr || item.id)),
              );

              // 构造删除参数
              const ruleData = uniqueRuleDataWithNumStr.map((id) => {
                const node = expandedNodes.find((item) => (item.numStr || item.id) === id);
                return {
                  id: id,
                  version: node?.version || '',
                };
              });

              await delCheckpointRule(selectedDept.id, ruleData);
              message.success(`删除成功！共删除 ${ruleData.length} 个条文条款`);
              ruleTableRef.current?.reload();
            } catch (error) {
              message.error('删除失败');
            }
          }}
          okText="确定"
          cancelText="取消"
          key="delete"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <KCIMPagecontainer title={false}>
      <div className="check-unit-mana">
        <div className="check-unit-container">
          {/* 左侧要点分类树 */}
          {renderDeptTree()}

          {/* 右侧内容区 */}
          <div className="dept-content" ref={deptContentRef}>
            {selectedDept && (
              <Card className="pfm-ant-card" bordered={false}>
                <Tabs activeKey={activeTab} onChange={handleTabChange}>
                  <TabPane tab="查核单位" key="units">
                    <div className="tab-content">
                      <div className="toolbar">
                        <div
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 8,
                          }}
                        >
                          <span style={{ color: '#17181A', fontSize: 14 }}>
                            检索:
                          </span>
                          <Input
                            placeholder="查核单位名称"
                            allowClear
                            suffix={
                              <SearchOutlined style={{ color: '#99A6BF' }} />
                            }
                            style={{ width: 250 }}
                            value={searchKeywords}
                            onChange={(e) => {
                              setSearchKeywords(e.target.value);
                              if (e.target.value === '') {
                                tableRef.current?.reload();
                              }
                            }}
                            onPressEnter={(e) => {
                              tableRef.current?.reload();
                            }}
                          />
                        </div>
                        <AddCheckpointDeptModal />
                      </div>

                      <KCIMTable
                        columns={deptColumns as ProColumns[]}
                        actionRef={tableRef}
                        rowKey="id"
                        params={{
                          parentId: selectedDept?.key,
                          filter: searchKeywords,
                        }}
                        request={async (params) => {
                          try {
                            const result = await getTableData(params);
                            return result;
                          } catch (error) {
                            return {
                              data: [],
                              total: 0,
                              success: false,
                            };
                          }
                        }}
                        search={false}
                        options={false}
                        pagination={false}
                        rowSelection={{
                          selectedRowKeys,
                          onChange: (keys) =>
                            setSelectedRowKeys(keys as string[]),
                        }}
                        tableAlertRender={false}
                      />
                    </div>
                  </TabPane>

                  <TabPane tab="查核组" key="groups">
                    <div className="tab-content">
                      <div className="toolbar">
                        <div
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 8,
                          }}
                        >
                          <span style={{ color: '#17181A', fontSize: 14 }}>
                            检索:
                          </span>
                          <Input
                            placeholder="查核组名称"
                            allowClear
                            suffix={
                              <SearchOutlined style={{ color: '#99A6BF' }} />
                            }
                            style={{ width: 250 }}
                            value={groupSearchKeywords}
                            onChange={(e) => {
                              setGroupSearchKeywords(e.target.value);
                              if (e.target.value === '') {
                                groupTableRef.current?.reload();
                              }
                            }}
                            onPressEnter={(e) => {
                              groupTableRef.current?.reload();
                            }}
                          />
                        </div>
                        <AddCheckpointGroupModal
                          selectedDept={selectedDept}
                          onSuccess={() => groupTableRef.current?.reload()}
                        />
                      </div>

                      <KCIMTable
                        columns={groupColumns as ProColumns[]}
                        actionRef={groupTableRef}
                        rowKey="id"
                        params={{
                          parentId: selectedDept?.key,
                          filter: groupSearchKeywords,
                        }}
                        request={async (params) => {
                          try {
                            const result = await getCheckpointGroup(params);
                            return result;
                          } catch (error) {
                            return {
                              data: [],
                              total: 0,
                              success: false,
                            };
                          }
                        }}
                        search={false}
                        options={false}
                        pagination={false}
                        rowSelection={{
                          selectedRowKeys: selectedGroupKeys,
                          onChange: (keys) =>
                            setSelectedGroupKeys(keys as string[]),
                        }}
                        tableAlertRender={false}
                      />
                    </div>
                  </TabPane>

                  <TabPane tab="查核项" key="items">
                    <div className="tab-content">
                      <div className="toolbar">
                        <div
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 8,
                          }}
                        >
                          <span style={{ color: '#17181A', fontSize: 14 }}>
                            检索:
                          </span>
                          <Input
                            placeholder="查核项名称"
                            allowClear
                            suffix={
                              <SearchOutlined style={{ color: '#99A6BF' }} />
                            }
                            style={{ width: 250 }}
                            value={itemSearchKeywords}
                            onChange={(e) => {
                              setItemSearchKeywords(e.target.value);
                              if (e.target.value === '') {
                                itemTableRef.current?.reload();
                              }
                            }}
                            onPressEnter={(e) => {
                              itemTableRef.current?.reload();
                            }}
                          />
                        </div>
                        <AddCheckpointItemModal
                          selectedDept={selectedDept}
                          onSuccess={() => itemTableRef.current?.reload()}
                        />
                      </div>

                      <KCIMTable
                        columns={itemColumns as ProColumns[]}
                        actionRef={itemTableRef}
                        rowKey="id"
                        params={{
                          parentId: selectedDept?.key,
                          filter: itemSearchKeywords,
                        }}
                        request={async (params) => {
                          try {
                            const result = await getCheckpointItem(params);
                            return result;
                          } catch (error) {
                            return {
                              data: [],
                              total: 0,
                              success: false,
                            };
                          }
                        }}
                        search={false}
                        options={false}
                        pagination={false}
                        rowSelection={{
                          selectedRowKeys: selectedItemKeys,
                          onChange: (keys) =>
                            setSelectedItemKeys(keys as string[]),
                        }}
                        tableAlertRender={false}
                      />
                    </div>
                  </TabPane>

                  <TabPane tab="条文条款" key="clauses">
                    <div className="tab-content">
                      <div className="toolbar">
                        <div
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 8,
                          }}
                        >
                          <span style={{ color: '#17181A', fontSize: 14 }}>
                            检索:
                          </span>
                          <Input
                            placeholder="条文条款"
                            allowClear
                            suffix={
                              <SearchOutlined style={{ color: '#99A6BF' }} />
                            }
                            style={{ width: 250 }}
                            value={ruleSearchKeywords}
                            onChange={(e) => {
                              setRuleSearchKeywords(e.target.value);
                              if (e.target.value === '') {
                                ruleTableRef.current?.reload();
                              }
                            }}
                            onPressEnter={(e) => {
                              ruleTableRef.current?.reload();
                            }}
                          />
                        </div>
                        <AddCheckpointRuleModal
                          selectedDept={selectedDept}
                          onSuccess={() => ruleTableRef.current?.reload()}
                        />
                      </div>

                      <KCIMTable
                        columns={ruleColumns as ProColumns[]}
                        actionRef={ruleTableRef}
                        rowKey="id"
                        params={{
                          parentId: selectedDept?.key,
                          filter: ruleSearchKeywords,
                        }}
                        request={async (params) => {
                          try {
                            const result = await getCheckpointRule(params);
                            
                            // 保存全部数据，用于单个删除时的父子节点处理
                            setAllRuleTableData(result.data || []);
                            
                            // 获取前5个顶层节点的展开键（只展开一级，不递归）
                            const getTop5ExpandableKeys = (
                              data: any[],
                            ): React.Key[] => {
                              const keys: React.Key[] = [];
                              const topLevelItems = data.slice(0, 5); // 只取前5个
                              topLevelItems.forEach((item) => {
                                if (item.children && item.children.length > 0) {
                                  keys.push(item.id);
                                }
                              });
                              return keys;
                            };

                            // 设置默认展开前5个顶层节点
                            const top5Keys = getTop5ExpandableKeys(
                              result.data || [],
                            );
                            setExpandedRowKeys(top5Keys);

                            return result;
                          } catch (error) {
                            return {
                              data: [],
                              total: 0,
                              success: false,
                            };
                          }
                        }}
                        search={false}
                        options={false}
                        pagination={false}
                        rowSelection={{
                          selectedRowKeys: selectedRuleKeys,
                          checkStrictly: false, // 启用父子关联选择
                          onChange: (keys, selectedRows) => {
                            setSelectedRuleKeys(keys as string[]);
                            setSelectedRuleData(selectedRows); // 存储完整的选中行数据
                          },
                        }}
                        tableAlertRender={false}
                        expandable={{
                          expandedRowKeys: expandedRowKeys, // 受控的展开状态
                          onExpandedRowsChange: (expandedKeys) => {
                            setExpandedRowKeys([...expandedKeys]);
                          },
                          expandRowByClick: false, // 禁止点击行展开
                          childrenColumnName: 'children', // 指定子数据的字段名
                          indentSize: 20, // 设置缩进大小
                        }}
                      />
                    </div>
                  </TabPane>
                </Tabs>
              </Card>
            )}

            {!selectedDept && (
              <div className="empty-state">
                <div className="empty-content">
                  <div className="empty-text">请选择左侧要点分类查看详情</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 批量操作栏 - 固定在页面底部，宽度跟dept-content一致 */}
      {((activeTab === 'units' && selectedRowKeys.length > 0) ||
        (activeTab === 'groups' && selectedGroupKeys.length > 0) ||
        (activeTab === 'items' && selectedItemKeys.length > 0) ||
        (activeTab === 'clauses' && selectedRuleKeys.length > 0)) && (
        <div
          style={{
            position: 'fixed',
            left: actionBarStyle.left + 16,
            width: actionBarStyle.width - 16,
            bottom: 16,
            height: 56,
            backgroundColor: '#fff',
            zIndex: 1000,
            boxShadow: 'rgba(0, 0, 0, 0.04) 0px -2px 8px',
            borderRadius: 4,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '0 16px',
            transition: 'left 0.2s, width 0.2s',
          }}
        >
          <span style={{ color: '#3377FF', fontWeight: 500 }}>
            已选{' '}
            {activeTab === 'units'
              ? selectedRowKeys.length
              : activeTab === 'groups'
              ? selectedGroupKeys.length
              : activeTab === 'items'
              ? selectedItemKeys.length
              : selectedRuleKeys.length}{' '}
            项
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button
              onClick={() => {
                if (activeTab === 'units') {
                  setSelectedRowKeys([]);
                } else if (activeTab === 'groups') {
                  setSelectedGroupKeys([]);
                } else if (activeTab === 'items') {
                  setSelectedItemKeys([]);
                } else if (activeTab === 'clauses') {
                  setSelectedRuleKeys([]);
                  setSelectedRuleData([]);
                }
              }}
              style={{ height: 32, borderRadius: 4, fontSize: 14 }}
              size="small"
            >
              取消选择
            </Button>
            <Popconfirm
              title={`确认批量删除所选${
                activeTab === 'units'
                  ? '查核单位'
                  : activeTab === 'groups'
                  ? '查核组'
                  : activeTab === 'items'
                  ? '查核项'
                  : '条文条款'
              }？`}
              okText="确定"
              cancelText="取消"
              onConfirm={async () => {
                try {
                  if (activeTab === 'units') {
                    await delCheckpointDept(selectedRowKeys);
                    message.success('批量删除成功');
                    setSelectedRowKeys([]);
                    tableRef.current?.reload();
                  } else if (activeTab === 'groups') {
                    await delCheckpointGroup(selectedGroupKeys);
                    message.success('批量删除成功');
                    setSelectedGroupKeys([]);
                    groupTableRef.current?.reload();
                  } else if (activeTab === 'items') {
                    await delCheckpointItem(selectedItemKeys);
                    message.success('批量删除成功');
                    setSelectedItemKeys([]);
                    itemTableRef.current?.reload();
                  } else if (activeTab === 'clauses') {
                    // 使用numStr作为id，从完整数据中获取版本信息
                    const ruleData = selectedRuleData.map((item) => ({
                      id: item.numStr || item.id,
                      version: item.version || '',
                    }));
                    await delCheckpointRule(selectedDept.id, ruleData);
                    message.success('批量删除成功');
                    setSelectedRuleKeys([]);
                    setSelectedRuleData([]);
                    ruleTableRef.current?.reload();
                  }
                } catch (e) {
                  message.error('批量删除失败');
                }
              }}
            >
              <Button
                type="primary"
                style={{
                  background: '#3377FF',
                  borderColor: '#3377FF',
                  height: 32,
                  borderRadius: 4,
                  fontSize: 14,
                }}
                size="small"
              >
                批量删除
              </Button>
            </Popconfirm>
          </div>
        </div>
      )}
    </KCIMPagecontainer>
  );
};

export default CheckPointMana;
