/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-05-13 11:28:30
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

import { createFromIconfontCN } from '@ant-design/icons';

import { ActionType, ProFormInstance } from '@ant-design/pro-components';

import { ProColumns } from '@ant-design/pro-table';
import { Modal, message, Tabs, Input, DatePicker, Popover, Alert } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import {
  computeProfitReq,
  getReportProjectSettingList,
  getResponsibleCenters,
} from './service';

import './style.less';
import React from 'react';

import { getDicDataBySysId } from '@/services/getDic';
import { KCIMLeftList } from '@/components/KCIMLeftList';
import { formatMoneyNumber } from '@/utils/format';
import { useModel } from '@umijs/max';
import { getUserHasReports } from '../costAccounting/calcPageTemplate/service';

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

let currentRow: any = undefined;

function findAllParents(tree: any[]) {
  let parents: any[] = [];
  // 递归函数来遍历树并找到所有父节点
  function traverse(nodes: any[]) {
    for (const node of nodes) {
      // 检查节点是否有子节点
      if (node.children && node.children.length > 0) {
        parents.push(node); // 添加到父节点列表
        traverse(node.children); // 递归遍历子节点
      }
    }
  }

  traverse(tree); // 开始遍历树
  return parents; // 返回所有父节点的数组
}

function countLeafNodes(trees: any[]) {
  let leafCount = 0;

  // 遍历集合中的每棵树
  for (let i = 0; i < trees.length; i++) {
    leafCount += countLeafNodesRecursive(trees[i]);
  }

  return leafCount;
}

function countLeafNodesRecursive(node: any) {
  // 如果当前节点没有子节点，说明它是一个叶子节点
  if (!node.children || node.children.length === 0) {
    return 1;
  }

  let leafCount = 0;

  // 递归计算每个子节点的叶子节点数
  for (let i = 0; i < node.children.length; i++) {
    leafCount += countLeafNodesRecursive(node.children[i]);
  }

  return leafCount;
}

function searchTree(tree: any[], searchTerm: string) {
  // 定义结果数组
  let results = [];

  // 定义递归函数来搜索匹配的节点
  function searchNode(node: any) {
    // 创建一个变量来标记当前节点或其子节点是否匹配
    let isMatch = false;

    // 检查当前节点的 name 或 code 是否包含搜索词
    if (node.reportName.includes(searchTerm)) {
      isMatch = true;
    }

    // 复制当前节点，避免修改原始数据
    let newNode = { ...node, children: [] };

    // 如果有子节点，递归搜索每个子节点
    if (node.children) {
      for (let child of node.children) {
        let childMatch = searchNode(child);
        // 如果子节点或其子树匹配，添加到新节点的子节点数组中
        if (childMatch) {
          newNode.children.push(childMatch);
          isMatch = true;
        }
      }
    }

    // 如果当前节点或其任何子节点匹配，返回新节点
    // 如果children为空，则不包含children属性
    if (isMatch) {
      if (newNode.children.length === 0) {
        delete newNode.children;
      }
      return newNode;
    } else {
      return null;
    }
  }

  // 遍历树的每个顶级节点
  for (let node of tree) {
    let result = searchNode(node);
    if (result) {
      results.push(result);
    }
  }

  return results;
}

// 递归函数，用于处理多层级标题
function generateColumns(item: any, titleIndex = 0) {
  const column: any = {
    title: item.reportName,
    dataIndex: `${item.reportId}`,
    key: `${item.reportId}`,
    // align: item.reportName != ''?'center':'',
  };

  if (
    item.childTitle &&
    Array.isArray(item.childTitle) &&
    item.childTitle.length > 0
  ) {
    column.children = item.childTitle.map((a: any, aindex: number) =>
      generateColumns(a, titleIndex + 1),
    );
  }

  return column;
}

// 主函数，生成表格列
const generateTableColumns = (title: any[]) => {
  return title.map((item: any, titleIndex: number) =>
    generateColumns(item, titleIndex),
  );
};

// 数据转换函数
const transformData = (data: any[]) => {
  const resultMap: Map<
    string,
    { reportName: string; key: string; children?: any[]; [key: string]: any }
  > = new Map();

  // 转换单个条目
  const transformEntry = (entry: any, type: string) => {
    if (!entry) return {};
    const transformedEntry = { ...entry }; // 完整复制 entry 以包含 decimalPlace 和 permil
    const formatOptions = {
      decimalPlaces: entry.decimalPlace, // 使用 entry 中的 decimalPlace
      useThousandSeparator: entry.permil, // 使用 entry 中的 permil
    };
    transformedEntry[`${type}_currentAmount`] =
      entry.currentAmount != null
        ? formatMoneyNumber(entry.currentAmount, formatOptions)
        : null;
    transformedEntry[`${type}_preMonthAmount`] =
      entry.preMonthAmount != null
        ? formatMoneyNumber(entry.preMonthAmount, formatOptions)
        : null;
    transformedEntry[`${type}_preYearAmount`] =
      entry.preYearAmount != null
        ? formatMoneyNumber(entry.preYearAmount, formatOptions)
        : null;
    transformedEntry[`${type}_preMonthPercent`] =
      entry.preMonthPercent != null ? entry.preMonthPercent : null;
    transformedEntry[`${type}_preYearPercent`] =
      entry.preYearPercent != null ? entry.preYearPercent : null;
    return transformedEntry;
  };

  // 合并新的条目到现有条目，不覆盖已有的字段
  const mergeEntries = (existingEntry: any, newEntry: any) => {
    for (const key in newEntry) {
      if (
        !existingEntry[key] ||
        key.endsWith('_currentAmount') ||
        key.endsWith('_preMonthAmount') ||
        key.endsWith('_preYearAmount') ||
        key.endsWith('_preMonthPercent') ||
        key.endsWith('_preYearPercent')
      ) {
        existingEntry[key] = newEntry[key];
      }
    }
  };

  // 递归处理每个节点及其子节点
  const processNode = (node: any, type: string): any => {
    if (!node) return {};

    const transformedNode = transformEntry(node, type);

    if (node.children && Array.isArray(node.children)) {
      const processedChildren = node.children.map((child: any) =>
        processNode(child, type),
      );
      transformedNode.children = mergeChildren(
        transformedNode.children || [],
        processedChildren,
      );
    }

    return transformedNode;
  };

  // 合并子节点，确保同一个父节点下的子节点是唯一的
  const mergeChildren = (existingChildren: any[], newChildren: any[]) => {
    newChildren.forEach((newChild) => {
      const existingChild = existingChildren.find(
        (child) =>
          child.reportName === newChild.reportName &&
          child.key === newChild.key,
      );

      if (existingChild) {
        mergeEntries(existingChild, newChild);
        if (newChild.children && Array.isArray(newChild.children)) {
          existingChild.children = mergeChildren(
            existingChild.children || [],
            newChild.children,
          );
        }
      } else {
        existingChildren.push(newChild);
      }
    });

    return existingChildren;
  };

  // 主处理逻辑
  data.forEach((item) => {
    const { medicalType, data } = item;

    if (!data || !Array.isArray(data)) {
      return;
    }

    data.forEach((profit) => {
      if (!resultMap.has(profit.reportName)) {
        resultMap.set(profit.reportName, {
          ...transformEntry(profit, medicalType),
          key: profit.reportName,
        });
      }

      const existingEntry = resultMap.get(profit.reportName)!;
      const transformedProfit = processNode(profit, medicalType);

      mergeEntries(existingEntry, transformedProfit);

      if (
        transformedProfit.children &&
        Array.isArray(transformedProfit.children)
      ) {
        existingEntry.children = mergeChildren(
          existingEntry.children || [],
          transformedProfit.children,
        );
      }
    });
  });

  // 确保每个层级的数据都有完整的月份字段
  const fillMissingMonths = (nodes: any[], medicalTypes: string[]) => {
    nodes.forEach((node) => {
      medicalTypes.forEach((type) => {
        const formatOptions = {
          decimalPlaces: node.decimalPlace, // 使用 node 中的 decimalPlace
          useThousandSeparator: node.permil, // 使用 node 中的 permil
        };
        if (!node.hasOwnProperty(`${type}_currentAmount`)) {
          node[`${type}_currentAmount`] =
            node.currentAmount != null
              ? formatMoneyNumber(node.currentAmount, formatOptions)
              : null;
        }
        if (!node.hasOwnProperty(`${type}_preMonthAmount`)) {
          node[`${type}_preMonthAmount`] =
            node.preMonthAmount != null
              ? formatMoneyNumber(node.preMonthAmount, formatOptions)
              : null;
        }
        if (!node.hasOwnProperty(`${type}_preYearAmount`)) {
          node[`${type}_preYearAmount`] =
            node.preYearAmount != null
              ? formatMoneyNumber(node.preYearAmount, formatOptions)
              : null;
        }

        if (!node.hasOwnProperty(`${type}_preMonthPercent`)) {
          node[`${type}_preMonthPercent`] = node.preMonthPercent
            ? node.preMonthPercent
            : null;
        }
        if (!node.hasOwnProperty(`${type}_preYearPercent`)) {
          node[`${type}_preYearPercent`] = node.preYearPercent
            ? node.preYearPercent
            : null;
        }
      });

      if (node.children && Array.isArray(node.children)) {
        fillMissingMonths(node.children, medicalTypes);
        if (node.children.length === 0) {
          delete node.children;
        }
      }
    });
  };

  const medicalTypes = data.map((item) => item.medicalType);

  const transformedData = Array.from(resultMap.values());

  fillMissingMonths(transformedData, medicalTypes);

  transformedData.forEach((node) => {
    if (node.children && node.children.length === 0) {
      delete node.children;
    }
  });

  return transformedData;
};

const getNextUnexpandedKeys = (data: any[], expandedKeys: any[] = []) => {
  let keys: any[] = [];

  const traverse = (nodes: any) => {
    for (const node of nodes) {
      // 如果当前节点还没有展开，就把它加入 keys
      if (!expandedKeys.includes(node.id)) {
        keys.push(node.id);
      }

      // 如果当前节点已经展开，继续遍历子节点
      if (node.children && expandedKeys.includes(node.id)) {
        traverse(node.children);
      }
    }
  };

  traverse(data);

  return keys;
};

export default function DepartmentCostCalc() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ reportType: 0 });
  const tableRef = useRef<ActionType>();
  const [tabs, set_tabs] = useState<any[]>([]);

  const { initialState, setInitialState } = useModel('@@initialState');
  const [computeDate, set_computeDate] = useState<string>(
    initialState ? initialState.computeDate : '',
  );
  const [responsibleCenters, set_responsibleCenters] = useState<any[]>([]);
  const [currentTabKey, set_currentTabKey] = useState<any | undefined>(
    undefined,
  );
  const [currentTab, set_currentTab] = useState<any | undefined>(undefined);
  const [currentSelectedRespon, set_currentSelectedRespon] = useState<
    any | undefined
  >(undefined);
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  const [allParentsKeys, set_allParentsKeys] = useState<Key[]>([]);

  const [dataSource, set_dataSource] = useState<any[]>([]);
  const [calcResultText, set_calcResultText] = useState<undefined | string>(
    undefined,
  );
  const [nextLevel, set_nextLevel] = useState<any>(undefined);

  const [columns, set_columns] = useState<any[]>([]);

  // 动态生成列定义函数
  const generateDataColumns = (colData: any[]) => {
    const baseColumns: any[] = [
      {
        title: '报表项目名称',
        dataIndex: 'reportName',
        key: 'reportName',
        width: 200,
        fixed: 'left',
      },
    ];

    colData.forEach((data) => {
      const medicalTypeTitle =
        data.medicalType === 1
          ? '门诊'
          : data.medicalType === 2
          ? '住院'
          : '总计';

      baseColumns.push({
        title: medicalTypeTitle,
        dataIndex: '1',
        children: [
          {
            title: '本期',
            dataIndex: `${data.medicalType}_currentAmount`,
            key: `${data.medicalType}_currentAmount`,
            align: 'right',
            render: (
              num: number,
              record: {
                calcType: any;
                decimalPlace?: number;
                permil?: boolean;
                dataType?: number;
              },
            ) => {
              const { calcType, decimalPlace, permil, dataType } = record;
              if (calcType === 0) return <React.Fragment></React.Fragment>;

              const formatOptions = {
                decimalPlaces: decimalPlace !== undefined ? decimalPlace : 2,
                useThousandSeparator: permil !== undefined ? permil : true,
              };

              if (dataType === 2) {
                if (typeof num === 'string') {
                  if (num === '-' || num === '') {
                    return num;
                  }
                } else if (num === null || num === undefined) {
                  return num;
                }
                return `${formatMoneyNumber(num, formatOptions)}%`;
              }
              return formatMoneyNumber(num, formatOptions);
            },
          },
          {
            title: '上期',
            align: 'right',
            dataIndex: `${data.medicalType}_preMonthAmount`,
            key: `${data.medicalType}_preMonthAmount`,
            render: (
              num: number,
              record: {
                calcType: any;
                decimalPlace?: number;
                permil?: boolean;
                dataType?: number;
              },
            ) => {
              const { calcType, decimalPlace, permil, dataType } = record;
              if (calcType === 0) return <React.Fragment></React.Fragment>;

              const formatOptions = {
                decimalPlaces: decimalPlace !== undefined ? decimalPlace : 2,
                useThousandSeparator: permil !== undefined ? permil : true,
              };

              if (dataType === 2) {
                if (typeof num === 'string') {
                  if (num === '-' || num === '') {
                    return num;
                  }
                } else if (num === null || num === undefined) {
                  return num;
                }
                return `${formatMoneyNumber(num, formatOptions)}%`;
              }
              return formatMoneyNumber(num, formatOptions);
            },
          },
          {
            title: '环比增长率',
            align: 'right',
            dataIndex: `${data.medicalType}_preMonthPercent`,
            key: `${data.medicalType}_preMonthPercent`,
            renderText(text: string, record: any) {
              const { calcType } = record;
              if (calcType === 0) return <React.Fragment></React.Fragment>;

              if (!text) return null;

              const isNegative = text.startsWith('-') && text.includes('%');
              return isNegative ? (
                <span style={{ color: '#00BF8F' }}>{text}</span>
              ) : (
                text
              );
            },
          },
          {
            title: '同期',
            align: 'right',
            dataIndex: `${data.medicalType}_preYearAmount`,
            key: `${data.medicalType}_preYearAmount`,
            render: (
              num: number,
              record: {
                calcType: any;
                decimalPlace?: number;
                permil?: boolean;
                dataType?: number;
              },
            ) => {
              const { calcType, decimalPlace, permil, dataType } = record;
              if (calcType === 0) return <React.Fragment></React.Fragment>;

              const formatOptions = {
                decimalPlaces: decimalPlace !== undefined ? decimalPlace : 2,
                useThousandSeparator: permil !== undefined ? permil : true,
              };

              if (dataType === 2) {
                if (typeof num === 'string') {
                  if (num === '-' || num === '') {
                    return num;
                  }
                } else if (num === null || num === undefined) {
                  return num;
                }
                return `${formatMoneyNumber(num, formatOptions)}%`;
              }
              return formatMoneyNumber(num, formatOptions);
            },
          },
          {
            title: '同比增长率',
            align: 'right',
            dataIndex: `${data.medicalType}_preYearPercent`,
            key: `${data.medicalType}_preYearPercent`,
            renderText(text: string, record: any) {
              const { calcType } = record;
              if (calcType === 0) return <React.Fragment></React.Fragment>;

              if (!text) return null;

              const isNegative = text.startsWith('-') && text.includes('%');
              return isNegative ? (
                <span style={{ color: '#00BF8F' }}>{text}</span>
              ) : (
                text
              );
            },
          },
        ],
      });
    });

    return baseColumns;
  };

  const getTableData = async (params: any) => {
    const { responsibilityCode, filter = undefined } = params;

    if (!responsibilityCode) return [];

    if (!nextLevel) {
      const resp = await getReportProjectSettingList({ ...params });
      if (resp) {
        // if (filter) {
        //     const filterData = searchTree(resp, filter);
        //     const allParents = findAllParents(filterData);

        //     set_allParentsKeys([...(allParents.map((a: any) => a.id))])
        //     return {
        //         data: filterData,
        //         success: true,
        //     }
        // }

        const realData = transformData(resp);
        if (currentTab.value == '1') {
          const allParents = findAllParents(realData);

          set_allParentsKeys([...allParents.map((a: any) => a.id)]);
        }

        set_columns(generateDataColumns(resp));
        set_dataSource(realData);
        return {
          data: realData,
          success: true,
        };
      } else {
        set_columns(generateDataColumns([]));
        set_dataSource([]);
        return {
          data: [],
          success: true,
        };
      }
    }

    // if (nextLevel) {
    //     const { reportId, calcType, date } = nextLevel;

    //     if (calcType == 1) {
    //         set_columns([
    //             {
    //                 title: '会计科目代码',
    //                 dataIndex: 'accountCode',
    //                 key: 'accountCode',
    //             },
    //             {
    //                 title: '会计项目名称',
    //                 dataIndex: 'accountName',
    //                 key: 'accountName',
    //             },
    //             {
    //                 title: '金额',
    //                 dataIndex: 'amount',
    //                 key: 'amount',
    //                 renderText(num: number, record: any) {
    //                     return formatMoneyNumber(num)
    //                 }
    //             }
    //         ])
    //         // const resp = await getNextLevelTableData({
    //         //     computeDate: date,
    //         //     reportId,
    //         //     reportType: currentTabKey,
    //         //     responsibilityCode: currentSelectedRespon.responsibilityCode
    //         // });

    //         // return {
    //         //     data: resp ? resp : [],
    //         //     success: true,
    //         // }
    //     }
    //     if (calcType == 2 || calcType == 5) {
    //         const columns = [
    //             {
    //                 title: () => <React.Fragment></React.Fragment>,
    //                 key: 'empty',
    //                 children: [
    //                     {
    //                         title: '责任中心',
    //                         dataIndex: 'responsibilityCenter',
    //                         key: 'responsibilityCenter',
    //                         render: (text: any, row: { responsibilityCenterRowSpan: any; }) => {
    //                             return {
    //                                 children: text,
    //                                 props: {
    //                                     rowSpan: row.responsibilityCenterRowSpan,
    //                                 },
    //                             };
    //                         },
    //                     },
    //                     {
    //                         title: '项目名称',
    //                         dataIndex: 'projectName',
    //                         key: 'projectName',
    //                         render: (text: any, row: { projectNameRowSpan: any; }) => {
    //                             return {
    //                                 children: text,
    //                                 props: {
    //                                     rowSpan: row.projectNameRowSpan,
    //                                 },
    //                             };
    //                         },
    //                     },
    //                     {
    //                         title: '分摊参数',
    //                         dataIndex: 'shareParam',
    //                         key: 'shareParam',
    //                     },
    //                       {
    //                         title: '分摊金额',
    //                         dataIndex: 'shareAmount',
    //                         key: 'shareAmount',
    //                       },
    //                 ]
    //             },
    //             {
    //                 title: `${currentSelectedRespon.responsibilityName}`,
    //                 dataIndex: `${currentSelectedRespon.responsibilityCode}`,
    //                 key: `${currentSelectedRespon.responsibilityCode}`,
    //                 children: [
    //                     {
    //                         title: '分摊参数数值',
    //                         dataIndex: 'shareParamValue',
    //                         key: 'shareParamValue',
    //                     },
    //                     {
    //                         title: '分摊参数占比',
    //                         dataIndex: 'shareParamRate',
    //                         key: 'shareParamRate',
    //                     },
    //                     {
    //                         title: '金额',
    //                         dataIndex: 'amount',
    //                         key: 'amount',
    //                     },
    //                 ]
    //             }
    //         ];
    //         set_columns([...columns]);
    //         const resp = await getNextLevelTableData({
    //             computeDate: date,
    //             reportId,
    //             reportType: currentTabKey,
    //             responsibilityCode: currentSelectedRespon.responsibilityCode
    //         });

    //         const processData = (data: any[]) => {
    //             const rows: any[] = [];
    //             data.forEach((item, index) => {
    //                 let responseNameRowSpan = 0; // 合并相同责任中心的单元格
    //                 item.dataList.forEach((dataItem: any) => {
    //                     responseNameRowSpan += dataItem.shareParamData.length; // 计算需要合并的行数
    //                 });

    //                 let currentRow = 0; // 当前行位置
    //                 item.dataList.forEach((dataItem: any) => {
    //                     const dataItemRowSpan = dataItem.shareParamData.length; // 项目名称的行合并数
    //                     dataItem.shareParamData.forEach((param: any, paramIndex: number) => {
    //                         rows.push({
    //                             key: `${item.responseCode}-${dataItem.alias}-${param.shareParamCode}`,
    //                             responsibilityCenter: paramIndex === 0 && currentRow === 0 ? item.responseName : '',
    //                             responsibilityCenterRowSpan: paramIndex === 0 && currentRow === 0 ? responseNameRowSpan : 0,
    //                             projectName: paramIndex === 0 ? dataItem.alias : '',
    //                             projectNameRowSpan: paramIndex === 0 ? dataItemRowSpan : 0,
    //                             shareParam: param.shareParamName,
    //                             shareAmount: formatMoneyNumber(param.shareParamAmount),
    //                             shareParamValue: param.shareParamNum,
    //                             shareParamRate: param.shareParamRate.toFixed(6),
    //                             amount: formatMoneyNumber(param.shareParamValue),
    //                         });
    //                     });
    //                     currentRow++;
    //                 });
    //             });
    //             return rows;
    //         };

    //         return {
    //             data: resp ? processData(resp) : [],
    //             success: true,
    //         }
    //     }

    // }

    return [];
  };

  const onTabChanged = (key: Key) => {
    set_currentTabKey(key);
    const needItem = tabs.filter((a) => a.key == key);
    if (needItem.length > 0) set_currentTab(needItem[0]);
  };

  const getTabs = async () => {
    // const { systemId } = JSON.parse((localStorage.getItem('currentSelectedTab')) as string)
    // const resp = await getDicDataBySysId(systemId, 'PROFIT_REPORT_TYPE');
    const resp = await getUserHasReports();
    if (resp) {
      const { dataVoList } = resp;
      const tempArr = dataVoList.map((a: any) => ({
        label: `${a.name}`,
        key: Number(a.code),
        value: a.value,
      }));
      const arr = tempArr.filter((a: any) => a.value != '2');
      set_tabs([...arr]);
      set_currentTabKey(arr[0].key);
      set_currentTab(arr[0]);
    }
  };

  const computeProfitHandle = async () => {
    Modal.confirm({
      title: '注意',
      content: '计算操作会覆盖当月已计算的数据，是否继续操作？',
      okText: '确定',
      cancelText: '取消',
      onOk: async (...args) => {
        const resp = await computeProfitReq(computeDate, currentTabKey);
        if (resp) {
          message.success('操作成功！');
          set_calcResultText('计算成功！');
          getResponsibleCenterList(currentTabKey, computeDate);
        } else {
          set_calcResultText('计算失败！');
        }
      },
    });
  };

  const getResponsibleCenterList = async (
    reportType: string,
    computeDate: string,
  ) => {
    const resp = await getResponsibleCenters(reportType, computeDate);
    if (resp) {
      set_responsibleCenters(resp);
    } else {
      set_columns(generateDataColumns([]));
      set_dataSource([]);
      set_responsibleCenters([]);
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        responsibilityCode: undefined,
        responsibilityType: undefined,
      });
    }
  };

  const onLeftChange = (currentSelected: any) => {
    set_currentSelectedRespon(currentSelected);
  };

  const backToHandle = () => {
    set_nextLevel(undefined);
    tableRef.current?.reload();
  };

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const getHeaderRows = (
    columns: any[],
    level = 0,
    headerRows: any[] = [],
    maxLevel = 0,
  ) => {
    headerRows[level] = headerRows[level] || [];
    columns.forEach((col: { title: any; children: any }) => {
      const colSpan = getColSpan(col);
      headerRows[level].push({
        title: col.title,
        colSpan,
        rowSpan: col.children ? 1 : maxLevel - level,
      });
      if (col.children) {
        getHeaderRows(col.children, level + 1, headerRows, maxLevel);
      } else {
        // 填充空白单元格
        for (let i = level + 1; i < maxLevel; i++) {
          headerRows[i] = headerRows[i] || [];
          headerRows[i].push({ title: '', colSpan: 1, rowSpan: 1 });
        }
      }
    });
    return headerRows;
  };

  const getColSpan: any = (col: { children: any[] }) => {
    if (!col.children) return 1;
    return col.children.reduce((sum, child) => sum + getColSpan(child), 0);
  };

  const getMaxLevel = (col: any) => {
    if (!col.children) return 1;
    return 1 + Math.max(...col.children.map(getMaxLevel));
  };

  const extractLeafColumns = (columns: any[]) => {
    let leafColumns: any[] = [];
    columns.forEach((col) => {
      if (col.children) {
        leafColumns = leafColumns.concat(extractLeafColumns(col.children));
      } else {
        leafColumns.push(col);
      }
    });
    return leafColumns;
  };

  const addRowWithIndentation = (
    record: any,
    level: number,
    leafColumns: any[],
    worksheetData: any[],
  ) => {
    const row = leafColumns.map((col) => record[col.dataIndex] ?? '');
    row[0] = ' '.repeat(level * 4) + row[0]; // 在第一列前添加缩进空格以表示层级
    worksheetData.push(row);
    if (record.children) {
      record.children.forEach((child: any) =>
        addRowWithIndentation(child, level + 1, leafColumns, worksheetData),
      );
    }
  };

  const handleExport = () => {
    try {
      const workbook = XLSX.utils.book_new();
      const worksheetData: any[] = [];

      // 获取最大层级
      const maxLevel = columns.reduce(
        (max, col) => Math.max(max, getMaxLevel(col)),
        0,
      );

      // 生成多层级表头
      const headerRows = getHeaderRows(columns, 0, [], maxLevel);

      // 构建表头行
      headerRows.forEach((row: any, rowIndex) => {
        const rowData: string[] = [];
        row.forEach(
          (cell: { title: any; colSpan: number; rowSpan: number }) => {
            rowData.push(cell.title);
            for (let i = 1; i < cell.colSpan; i++) {
              rowData.push('');
            }
          },
        );
        worksheetData.push(rowData);
      });

      // 填充单层表头的空白行
      if (maxLevel > 1) {
        const numColumns = headerRows[0].reduce(
          (sum: any, cell: { colSpan: any }) => sum + cell.colSpan,
          0,
        );
        for (let i = 1; i < maxLevel; i++) {
          while (worksheetData[i].length < numColumns) {
            worksheetData[i].push('');
          }
        }
      }

      // 提取最内层表头列
      const leafColumns = extractLeafColumns(columns);

      // 添加数据并处理树结构
      dataSource.forEach((record) =>
        addRowWithIndentation(record, 0, leafColumns, worksheetData),
      );

      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

      // 初始化合并单元格数组
      worksheet['!merges'] = worksheet['!merges'] || [];

      // 合并单元格
      headerRows.forEach((row: any, rowIndex) => {
        let colIndex = 0;
        row.forEach((cell: { colSpan: number; rowSpan: number }) => {
          if (cell.colSpan > 1 || cell.rowSpan > 1) {
            worksheet['!merges']!.push({
              // 使用非空断言 '!'
              s: { r: rowIndex, c: colIndex },
              e: {
                r: rowIndex + cell.rowSpan - 1,
                c: colIndex + cell.colSpan - 1,
              },
            });
          }
          colIndex += cell.colSpan;
        });
      });

      // 设置单元格对齐方式
      Object.keys(worksheet).forEach((cell) => {
        if (cell[0] !== '!') {
          worksheet[cell].s = {
            alignment: { vertical: 'center', horizontal: 'center' },
          };
        }
      });

      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
      const s2ab = (s: string) => {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      };

      saveAs(
        new Blob([s2ab(wbout)], { type: 'application/octet-stream' }),
        currentTab ? `${currentTab.label}.xlsx` : 'table_data.xlsx',
      );
    } catch (error) {
      console.error('Export failed:', error);
    }
  };

  const onekeyComputeProfitHandle = async () => {
    Modal.confirm({
      title: '注意',
      content: '一键计算操作会覆盖当月已计算的数据，是否继续操作？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const promises = tabs.map((tab) =>
            computeProfitReq(computeDate, tab.key),
          ); // 对每个tab创建一个请求
          const results = await Promise.all(promises); // 等待所有请求完成

          const allSuccess = results.every((resp) => resp); // 检查所有请求是否都成功
          if (allSuccess) {
            message.success('操作成功！');
            set_calcResultText('一键计算成功！');
          } else {
            set_calcResultText('一键计算部分失败！');
          }

          tableRef.current?.reload(); // 重新加载表格数据
        } catch (error) {
          message.error('操作失败，请重试！');
          set_calcResultText('一键计算失败！');
        }
      },
    });
  };

  const handleCollapseAll = () => {
    set_allParentsKeys([]);
  };

  const handleExpandNext = () => {
    // 当前所有未展开的节点，第一层优先展开
    const keysToExpand = getNextUnexpandedKeys(dataSource, allParentsKeys);
    set_allParentsKeys((prev) =>
      Array.from(new Set([...prev, ...keysToExpand])),
    );
  };

  useEffect(() => {
    set_currentSelectedRespon(undefined);
    if (computeDate && currentTabKey != undefined) {
      getResponsibleCenterList(currentTabKey, computeDate);
      // set_tableDataFilterParams({
      //     ...tableDataFilterParams,
      //     currentTabKey,
      //     computeDate
      // });
      set_nextLevel(undefined);
    }
    set_allParentsKeys([]);
  }, [computeDate, currentTabKey]);

  useEffect(() => {
    if (currentSelectedRespon) {
      console.log({ currentSelectedRespon });
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        responsibilityCode: currentSelectedRespon.responsibilityCode,
        reportType: currentTabKey,
        responsibilityType: currentSelectedRespon.responsibilityType,
        computeDate,
      });
      set_nextLevel(undefined);
    }
    set_allParentsKeys([]);
  }, [currentSelectedRespon]);

  useEffect(() => {
    getTabs();
  }, []);

  return (
    <KCIMPagecontainer className="DepartmentCostCalc" title={false}>
      <div className="header">
        <div className="search">
          <span>核算年月：</span>
          <DatePicker
            onChange={(data, dateString) => {
              // console.log({data,dateString});
              set_computeDate(dateString);
              setInitialState((s: any) => ({ ...s, computeDate: dateString }));
              // set_tableDataFilterParams({
              //     ...tableDataFilterParams,
              //     computeDate: dateString
              // });
            }}
            picker="month"
            locale={locale}
            autoComplete="off"
            defaultValue={moment(computeDate, 'YYYY-MM')}
            format="YYYY-MM"
          />
        </div>
        <div className="btnGoup">
          <span
            className="onekeyCalcBtn"
            onClick={() => onekeyComputeProfitHandle()}
          >
            一键计算
          </span>
        </div>
      </div>
      <div className="content">
        <Tabs
          defaultActiveKey={tabs.length > 0 ? tabs[0].key : undefined}
          items={tabs}
          key={'key'}
          onChange={(key) => onTabChanged(key)}
        />
        {calcResultText && (
          <Alert
            showIcon
            onClose={() => set_calcResultText(undefined)}
            icon={
              <IconFont
                type={
                  calcResultText.indexOf('失败') != -1
                    ? 'icon-cuowutishi'
                    : 'icon-chenggongtishi'
                }
              />
            }
            closable
            style={{
              padding: '4px 12px',
              marginBottom: 16,
              borderRadius: 4,
              border:
                calcResultText.indexOf('失败') != -1 ? '1px solid #73E6BF' : '',
              background:
                calcResultText.indexOf('失败') != -1 ? '#FFF1F3' : '#EBFFF8',
            }}
            message={calcResultText}
            type={calcResultText.indexOf('失败') != -1 ? 'error' : 'success'}
          />
        )}
        <div className="inner">
          <div className="left">
            <KCIMLeftList
              fieldNames={{
                title: 'responsibilityName',
                key: 'responsibilityCode',
                children: 'child',
              }}
              rowKey={'responsibilityCode'}
              dataSource={responsibleCenters}
              searchKey={'responsibilityName'}
              onChange={onLeftChange}
              contentH={`100%`}
              // placeholder={leftListSearchPlaceHolder}
              listType={'tree'}
            />
          </div>
          <div className="right">
            <div className="toolBar">
              <div className="filterItem" style={{ width: 228 }}>
                {/* <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                                <Input placeholder={'报表项目代码/名称'} allowClear autoComplete='off'
                                    suffix={
                                        <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('filter')} />
                                    }
                                    onChange={(e) => {
                                        set_tableDataSearchKeywords(e.target.value);
                                        if (e.target.value.length == 0) {
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                filter: ''
                                            });
                                        }
                                    }}
                                    onPressEnter={(e) => {
                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            filter: ((e.target) as HTMLInputElement).value
                                        });
                                    }}

                                /> */}
                {nextLevel && (
                  <div className="back" onClick={() => backToHandle()}>
                    <span>
                      <IconFont type="iconfanhui" />
                    </span>
                    {nextLevel.reportName}
                  </div>
                )}
              </div>

              <div className="btnGroup">
                {/* <span className='btn' onClick={() => openTableDataDrawer()}>报表数据</span> */}
                <span className="btn" onClick={() => handleCollapseAll()}>
                  全部折叠
                </span>
                <span
                  className="btn"
                  style={{ marginRight: 16 }}
                  onClick={() => handleExpandNext()}
                >
                  展开下一层
                </span>
                <span className="calc" onClick={() => computeProfitHandle()}>
                  计算
                </span>
              </div>
            </div>

            <KCIMTable
              pagination={false}
              bordered
              rowClassName={(record) =>
                record.children ? 'has-children hover-row' : 'hover-row'
              }
              expandable={{
                defaultExpandAllRows: true,
                expandedRowKeys: allParentsKeys,
                onExpand(expanded, record) {
                  const { id } = record;
                  if (!expanded) {
                    const expandedKeys = allParentsKeys.filter((a) => a != id);
                    set_allParentsKeys([...expandedKeys]);
                  } else {
                    set_allParentsKeys([...allParentsKeys, id]);
                  }
                },
              }}
              columns={columns as ProColumns[]}
              scroll={{
                y: `calc(100vh - 343px)`,
                x: (columns.length - 1) * 710 + 220,
              }}
              actionRef={tableRef}
              rowKey="id"
              params={tableDataFilterParams}
              request={(params) => getTableData(params)}
            />
          </div>
        </div>
      </div>
    </KCIMPagecontainer>
  );
}
