/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-01 16:40:51
 * @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-js-style';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

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

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

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

const { RangePicker } = DatePicker;

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

const DEFAULT_FONT_COLOR = 'rgba(0, 0, 0, 0.85)';

const normalizeColor = (rawColor: any) => {
  if (typeof rawColor !== 'string') return DEFAULT_FONT_COLOR;
  const color = rawColor.trim();
  if (!color) return DEFAULT_FONT_COLOR;
  return color;
};

const getReportFontColor = (record: any) =>
  normalizeColor(
    record?.fontColor ||
      record?.fontcolor ||
      record?.font_color ||
      DEFAULT_FONT_COLOR,
  );

const toHex2 = (num: number) =>
  Math.max(0, Math.min(255, Math.round(num)))
    .toString(16)
    .padStart(2, '0')
    .toUpperCase();

const convertToExcelArgb = (rawColor: any) => {
  const color = normalizeColor(rawColor);
  const hexColorMatch = color.match(
    /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,
  );
  if (hexColorMatch) {
    const hex = hexColorMatch[1];
    if (hex.length === 3) {
      const r = hex[0] + hex[0];
      const g = hex[1] + hex[1];
      const b = hex[2] + hex[2];
      return `FF${(r + g + b).toUpperCase()}`;
    }
    if (hex.length === 6) {
      return `FF${hex.toUpperCase()}`;
    }
    // CSS 的 #RRGGBBAA 转成 Excel 的 AARRGGBB
    const rrggbb = hex.slice(0, 6).toUpperCase();
    const aa = hex.slice(6, 8).toUpperCase();
    return `${aa}${rrggbb}`;
  }

  const rgbaMatch = color.match(
    /^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)\s*(?:,\s*([0-9.]+)\s*)?\)$/i,
  );
  if (rgbaMatch) {
    const r = Number(rgbaMatch[1]);
    const g = Number(rgbaMatch[2]);
    const b = Number(rgbaMatch[3]);
    const alphaRaw = rgbaMatch[4];
    const alpha =
      alphaRaw === undefined ? 1 : Math.max(0, Math.min(1, Number(alphaRaw)));
    return `${toHex2(alpha * 255)}${toHex2(r)}${toHex2(g)}${toHex2(b)}`;
  }

  return 'FF000000';
};

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 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;
}

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

  // 转换单个条目
  const transformEntry = (
    entry: any,
    computeDate: string,
    allowDrillDown?: boolean,
  ) => {
    if (!entry) return {};
    const transformedEntry = { ...entry };

    // 根据 dataType 处理不同类型的数据
    const formatValue = (value: number) => {
      if (value == null) return null;

      if (entry.dataType === 2) {
        // 百分比类型
        return `${(value * 100).toFixed(entry.decimalPlace || 2)}%`;
      } else {
        // 数值类型 (dataType === 1 或未定义)
        return formatMoneyNumber(value, {
          decimalPlaces: entry.decimalPlace,
          useThousandSeparator: Boolean(entry.permil),
        });
      }
    };

    // 处理各个字段
    transformedEntry[`${computeDate}_amount`] = formatValue(entry.amount);
    transformedEntry[`${computeDate}_budgetAmount`] = formatValue(
      entry.budgetAmount,
    );
    transformedEntry[`${computeDate}_prevPeriodAmount`] = formatValue(
      entry.prevPeriodAmount,
    );
    transformedEntry[`${computeDate}_samePeriodAmount`] = formatValue(
      entry.samePeriodAmount,
    );

    // 百分比字段始终显示为百分比
    transformedEntry[`${computeDate}_percent`] =
      entry.percent != null ? `${(entry.percent * 100).toFixed(2)}%` : null;
    transformedEntry[`${computeDate}_completionRate`] =
      entry.completionRate != null
        ? `${(entry.completionRate * 100).toFixed(entry.decimalPlace || 2)}%`
        : null;
    transformedEntry[`${computeDate}_momRate`] =
      entry.momRate != null
        ? `${(entry.momRate * 100).toFixed(entry.decimalPlace || 2)}%`
        : null;
    transformedEntry[`${computeDate}_yoyRate`] =
      entry.yoyRate != null
        ? `${(entry.yoyRate * 100).toFixed(entry.decimalPlace || 2)}%`
        : null;

    // 处理allowDrillDown字段，按月份字段化
    transformedEntry[`${computeDate}_allowDrillDown`] = allowDrillDown;

    return transformedEntry;
  };

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

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

    const transformedNode = transformEntry(node, computeDate, allowDrillDown);

    if (node.children && Array.isArray(node.children)) {
      const processedChildren = node.children.map((child: any) =>
        processNode(child, computeDate, allowDrillDown),
      );
      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 { computeDate, profitVoList, allowDrillDown } = item;

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

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

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

      mergeEntries(existingEntry, transformedProfit);

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

  // 确保每个层级的数据都有完整的月份字段
  const fillMissingMonths = (nodes: any[], computeDates: string[]) => {
    nodes.forEach((node) => {
      computeDates.forEach((date) => {
        if (!node.hasOwnProperty(`${date}_amount`)) {
          node[`${date}_amount`] =
            node.amount != null
              ? formatMoneyNumber(node.amount, {
                  decimalPlaces: node.decimalPlace,
                  useThousandSeparator: Boolean(node.permil),
                })
              : null;
        }
        if (!node.hasOwnProperty(`${date}_budgetAmount`)) {
          node[`${date}_budgetAmount`] =
            node.budgetAmount != null
              ? formatMoneyNumber(node.budgetAmount, {
                  decimalPlaces: node.decimalPlace,
                  useThousandSeparator: Boolean(node.permil),
                })
              : null;
        }
        if (!node.hasOwnProperty(`${date}_prevPeriodAmount`)) {
          node[`${date}_prevPeriodAmount`] =
            node.prevPeriodAmount != null
              ? formatMoneyNumber(node.prevPeriodAmount, {
                  decimalPlaces: node.decimalPlace,
                  useThousandSeparator: Boolean(node.permil),
                })
              : null;
        }
        if (!node.hasOwnProperty(`${date}_samePeriodAmount`)) {
          node[`${date}_samePeriodAmount`] =
            node.samePeriodAmount != null
              ? formatMoneyNumber(node.samePeriodAmount, {
                  decimalPlaces: node.decimalPlace,
                  useThousandSeparator: Boolean(node.permil),
                })
              : null;
        }
        if (!node.hasOwnProperty(`${date}_completionRate`)) {
          node[`${date}_completionRate`] =
            node.completionRate != null
              ? `${(node.completionRate * 100).toFixed(
                  node.decimalPlace || 2,
                )}%`
              : null;
        }
        if (!node.hasOwnProperty(`${date}_momRate`)) {
          node[`${date}_momRate`] =
            node.momRate != null
              ? `${(node.momRate * 100).toFixed(node.decimalPlace || 2)}%`
              : null;
        }
        if (!node.hasOwnProperty(`${date}_yoyRate`)) {
          node[`${date}_yoyRate`] =
            node.yoyRate != null
              ? `${(node.yoyRate * 100).toFixed(node.decimalPlace || 2)}%`
              : null;
        }
        if (!node.hasOwnProperty(`${date}_percent`)) {
          node[`${date}_percent`] =
            node.percent != null ? `${(node.percent * 100).toFixed(2)}%` : null;
        }
        if (!node.hasOwnProperty(`${date}_allowDrillDown`)) {
          node[`${date}_allowDrillDown`] = node.allowDrillDown;
        }
      });

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

  const computeDates = data.map((item) => item.computeDate);

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

  fillMissingMonths(transformedData, computeDates);

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

  // console.log({ transformedData });
  return transformedData;
};

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

  // 转换单个条目
  const transformYearEntry = (
    entry: any,
    computeDate: string,
    allowDrillDown?: boolean,
  ) => {
    if (!entry) return {};
    const transformedEntry = { ...entry };

    // 根据 dataType 处理不同类型的数据
    const formatValue = (value: number) => {
      if (value == null) return null;

      if (entry.dataType === 2) {
        // 百分比类型
        return `${(value * 100).toFixed(entry.decimalPlace || 2)}%`;
      } else {
        // 数值类型 (dataType === 1 或未定义)
        return formatMoneyNumber(value, {
          decimalPlaces: entry.decimalPlace,
          useThousandSeparator: Boolean(entry.permil),
        });
      }
    };

    // 处理年度数据的各个字段
    transformedEntry[`${computeDate}_amount`] = formatValue(entry.amount);
    transformedEntry[`${computeDate}_budgetAmount`] = formatValue(
      entry.budgetAmount,
    );
    transformedEntry[`${computeDate}_samePeriodAmount`] = formatValue(
      entry.samePeriodAmount,
    );

    // 完成率和同比始终显示为百分比
    transformedEntry[`${computeDate}_completionRate`] =
      entry.completionRate != null
        ? `${(entry.completionRate * 100).toFixed(entry.decimalPlace || 2)}%`
        : null;

    transformedEntry[`${computeDate}_yoyRate`] =
      entry.yoyRate != null
        ? `${(entry.yoyRate * 100).toFixed(entry.decimalPlace || 2)}%`
        : null;

    // 处理allowDrillDown字段，按年份字段化
    transformedEntry[`${computeDate}_allowDrillDown`] = allowDrillDown;

    return transformedEntry;
  };

  // 合并新的条目到现有条目
  const mergeYearEntries = (existingEntry: any, newEntry: any) => {
    for (const key in newEntry) {
      if (
        !existingEntry[key] ||
        key.includes('_amount') ||
        key.includes('_budgetAmount') ||
        key.includes('_samePeriodAmount') ||
        key.includes('_completionRate') ||
        key.includes('_yoyRate') ||
        key.includes('_allowDrillDown')
      ) {
        existingEntry[key] = newEntry[key];
      }
    }
  };

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

    const transformedNode = transformYearEntry(
      node,
      computeDate,
      allowDrillDown,
    );

    if (node.children && Array.isArray(node.children)) {
      const processedChildren = node.children.map((child: any) =>
        processYearNode(child, computeDate, allowDrillDown),
      );
      transformedNode.children = mergeYearChildren(
        transformedNode.children || [],
        processedChildren,
      );
    }

    return transformedNode;
  };

  // 合并子节点
  const mergeYearChildren = (existingChildren: any[], newChildren: any[]) => {
    newChildren.forEach((newChild) => {
      const existingChild = existingChildren.find(
        (child) =>
          child.reportName === newChild.reportName &&
          child.key === newChild.key,
      );

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

    return existingChildren;
  };

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

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

    profitVoList.forEach((profit) => {
      if (!resultMap.has(profit.reportName)) {
        resultMap.set(profit.reportName, {
          ...transformYearEntry(profit, computeDate, allowDrillDown),
          key: profit.reportName,
        });
      }

      const existingEntry = resultMap.get(profit.reportName)!;
      const transformedProfit = processYearNode(
        profit,
        computeDate,
        allowDrillDown,
      );

      mergeYearEntries(existingEntry, transformedProfit);

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

  // 确保每个层级的数据都有完整的年份字段
  const fillMissingYears = (nodes: any[], computeDates: string[]) => {
    nodes.forEach((node) => {
      // 根据 dataType 处理不同类型的数据
      const formatValue = (value: number) => {
        if (value == null) return null;

        if (node.dataType === 2) {
          // 百分比类型
          return `${(value * 100).toFixed(node.decimalPlace || 2)}%`;
        } else {
          // 数值类型 (dataType === 1 或未定义)
          return formatMoneyNumber(value, {
            decimalPlaces: node.decimalPlace,
            useThousandSeparator: Boolean(node.permil),
          });
        }
      };

      computeDates.forEach((date) => {
        if (!node.hasOwnProperty(`${date}_amount`)) {
          node[`${date}_amount`] = formatValue(node.amount);
        }
        if (!node.hasOwnProperty(`${date}_budgetAmount`)) {
          node[`${date}_budgetAmount`] = formatValue(node.budgetAmount);
        }
        if (!node.hasOwnProperty(`${date}_samePeriodAmount`)) {
          node[`${date}_samePeriodAmount`] = formatValue(node.samePeriodAmount);
        }
        if (!node.hasOwnProperty(`${date}_completionRate`)) {
          node[`${date}_completionRate`] =
            node.completionRate != null
              ? `${(node.completionRate * 100).toFixed(
                  node.decimalPlace || 2,
                )}%`
              : null;
        }
        if (!node.hasOwnProperty(`${date}_yoyRate`)) {
          node[`${date}_yoyRate`] =
            node.yoyRate != null
              ? `${(node.yoyRate * 100).toFixed(node.decimalPlace || 2)}%`
              : null;
        }
        if (!node.hasOwnProperty(`${date}_allowDrillDown`)) {
          node[`${date}_allowDrillDown`] = node.allowDrillDown;
        }
      });

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

  const computeDates = data.map((item) => item.computeDate);
  const transformedData = Array.from(resultMap.values());
  fillMissingYears(transformedData, computeDates);

  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 location = useLocation();
  // 从路由路径判断模式，而不是从查询参数
  const isYearMode = location.pathname.includes('/year');
  const pageMode = isYearMode ? 'year' : 'month';

  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 [computeRangeDate, set_computeRangeDate] = useState<string[]>(() => {
    if (initialState) {
      if (isYearMode) {
        // 年度模式：使用年份格式
        const year = initialState.computeDate
          ? initialState.computeDate.substring(0, 4)
          : '';
        return [year, year];
      } else {
        // 月度模式：使用原有格式
        return [initialState.computeDate, initialState.computeDate];
      }
    }
    return [];
  });
  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 [needShowReportCode, set_needShowReportCode] = useState('0');

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

    if (isYearMode) {
      // 年度模式的列配置
      // 获取是否显示预算金额和完成率的参数
      let showBudgetAndCompletion = false;
      const { systemId } = JSON.parse(
        localStorage.getItem('currentSelectedTab') as string,
      );
      const budgetResp = await getParamsDataBySysId(
        systemId,
        '1942871277190647808',
      );
      if (budgetResp) {
        showBudgetAndCompletion = budgetResp.value === '1';
      }

      const yearColumns = data.map((item) => {
        const year = item.computeDate;
        const baseYearColumns = [
          {
            title: '实际',
            dataIndex: `${year}_amount`,
            key: `${year}_amount`,
            width: 100,
            align: 'right',
            renderText(num: number, record: any) {
              const { calcType } = record;
              if (calcType == 0) {
                return <React.Fragment></React.Fragment>;
              } else {
                // 使用按年份字段化的allowDrillDown
                const yearAllowDrillDown = record[`${year}_allowDrillDown`];
                // 检查allowDrillDown字段，如果为false则不可下钻
                if (
                  (calcType == 1 || calcType == 2 || calcType == 5) &&
                  yearAllowDrillDown
                ) {
                  return (
                    <span
                      onClick={() => {
                        set_nextLevel({ ...record, date: year });
                        tableRef.current?.reload();
                      }}
                      style={{ color: '#3377FF', cursor: 'pointer' }}
                    >
                      {num}
                    </span>
                  );
                } else {
                  return num;
                }
              }
            },
          },
          {
            title: '同期',
            dataIndex: `${year}_samePeriodAmount`,
            key: `${year}_samePeriodAmount`,
            width: 100,
            align: 'right',
            renderText(num: number, record: any) {
              const { calcType } = record;
              if (calcType == 0) {
                return <React.Fragment></React.Fragment>;
              } else {
                return num;
              }
            },
          },
          {
            title: '同比',
            dataIndex: `${year}_yoyRate`,
            key: `${year}_yoyRate`,
            width: 100,
            align: 'right',
            renderText(text: string, record: any) {
              const { calcType } = record;
              if (calcType == 0) {
                return <React.Fragment></React.Fragment>;
              } else {
                return text;
              }
            },
          },
        ];

        // 根据参数决定是否显示预算和完成率列
        const conditionalColumns = showBudgetAndCompletion
          ? [
              {
                title: '预算',
                dataIndex: `${year}_budgetAmount`,
                key: `${year}_budgetAmount`,
                width: 100,
                align: 'right',
                renderText(num: number, record: any) {
                  const { calcType } = record;
                  if (calcType == 0) {
                    return <React.Fragment></React.Fragment>;
                  } else {
                    // 年度模式下不可点击
                    return num;
                  }
                },
              },
              {
                title: '完成率',
                dataIndex: `${year}_completionRate`,
                key: `${year}_completionRate`,
                width: 100,
                align: 'right',
                renderText(text: string, record: any) {
                  const { calcType } = record;
                  if (calcType == 0) {
                    return <React.Fragment></React.Fragment>;
                  } else {
                    return text;
                  }
                },
              },
            ]
          : [];

        return {
          title: `${year}年`,
          children: [
            ...conditionalColumns.slice(0, 1), // 预算列（如果显示）
            ...baseYearColumns.slice(0, 1), // 实际列
            ...baseYearColumns.slice(1, 2), // 同期列
            ...conditionalColumns.slice(1, 2), // 完成率列（如果显示）
            ...baseYearColumns.slice(2, 3), // 同比列
          ],
        };
      });
      set_columns([...baseColumns, ...yearColumns]);
    } else {
      // 月度模式的列配置（原有逻辑）
      let ifShowPercent = true;
      let showBudgetAndCompletion = false;

      const { systemId } = JSON.parse(
        localStorage.getItem('currentSelectedTab') as string,
      );
      const resp = await getParamsDataBySysId(systemId, '1851077044079824896');
      if (resp) {
        ifShowPercent = resp.value == '1' ? true : false;
      }

      // 获取是否显示预算金额和完成率的参数
      const budgetResp = await getParamsDataBySysId(
        systemId,
        '1942871277190647808',
      );
      if (budgetResp) {
        showBudgetAndCompletion = budgetResp.value === '1';
      }

      // 获取所有月份并生成列
      const monthColumns = data.map((item) => {
        const month = item.computeDate;

        // 构建最终的列数组
        let finalColumns: any[] = [];

        // 根据参数决定是否显示预算列（放在实际列前面）
        if (showBudgetAndCompletion) {
          finalColumns.push({
            title: '预算',
            dataIndex: `${month}_budgetAmount`,
            key: `${month}_budgetAmount`,
            width: 100,
            align: 'right',
            renderText(num: number, record: any) {
              const { calcType } = record;
              if (calcType == 0) {
                return <React.Fragment></React.Fragment>;
              } else {
                return num;
              }
            },
          });
        }

        // 添加实际列
        finalColumns.push({
          title: '实际',
          dataIndex: `${month}_amount`,
          key: `${month}_amount`,
          width: 100,
          align: 'right',
          renderText(num: number, record: any) {
            const { calcType } = record;
            if (calcType == 0) {
              return <React.Fragment></React.Fragment>;
            } else {
              // 使用按月份字段化的allowDrillDown
              const monthAllowDrillDown = record[`${month}_allowDrillDown`];
              // 保留原有的calcType判断，同时使用allowDrillDown字段控制当前月是否可下钻
              if (
                (calcType == 1 || calcType == 2 || calcType == 5) &&
                monthAllowDrillDown
              ) {
                return (
                  <span
                    onClick={() => {
                      set_nextLevel({ ...record, date: month });
                      tableRef.current?.reload();
                    }}
                    style={{ color: '#3377FF', cursor: 'pointer' }}
                  >
                    {num}
                  </span>
                );
              } else {
                return num;
              }
            }
          },
        });

        // 始终显示上期列
        finalColumns.push({
          title: '上期',
          dataIndex: `${month}_prevPeriodAmount`,
          key: `${month}_prevPeriodAmount`,
          width: 100,
          align: 'right',
          renderText(num: number, record: any) {
            const { calcType } = record;
            if (calcType == 0) {
              return <React.Fragment></React.Fragment>;
            } else {
              return num;
            }
          },
        });

        // 始终显示同期列
        finalColumns.push({
          title: '同期',
          dataIndex: `${month}_samePeriodAmount`,
          key: `${month}_samePeriodAmount`,
          width: 100,
          align: 'right',
          renderText(num: number, record: any) {
            const { calcType } = record;
            if (calcType == 0) {
              return <React.Fragment></React.Fragment>;
            } else {
              return num;
            }
          },
        });

        // 根据参数决定是否显示完成率列
        if (showBudgetAndCompletion) {
          finalColumns.push({
            title: '完成率',
            dataIndex: `${month}_completionRate`,
            key: `${month}_completionRate`,
            width: 100,
            align: 'right',
            renderText(text: any, record: any) {
              const { calcType } = record;
              if (calcType == 0) {
                return <React.Fragment></React.Fragment>;
              } else {
                return text;
              }
            },
          });
        }

        // 始终显示环比列
        finalColumns.push({
          title: '环比增长',
          dataIndex: `${month}_momRate`,
          key: `${month}_momRate`,
          width: 100,
          align: 'right',
          renderText(text: any, record: any) {
            const { calcType } = record;
            if (calcType == 0) {
              return <React.Fragment></React.Fragment>;
            } else {
              return text;
            }
          },
        });

        // 始终显示同比列
        finalColumns.push({
          title: '同比增长',
          dataIndex: `${month}_yoyRate`,
          key: `${month}_yoyRate`,
          width: 100,
          align: 'right',
          renderText(text: any, record: any) {
            const { calcType } = record;
            if (calcType == 0) {
              return <React.Fragment></React.Fragment>;
            } else {
              return text;
            }
          },
        });

        // 如果显示占比，添加占比列
        if (ifShowPercent) {
          finalColumns.push({
            title: '占比',
            dataIndex: `${month}_percent`,
            key: `${month}_percent`,
            width: 100,
            align: 'right',
            renderText(text: number, record: any) {
              const { calcType } = record;
              if (calcType == 0) {
                return <React.Fragment></React.Fragment>;
              } else {
                return text;
              }
            },
          });
        }

        return {
          title: month,
          children: finalColumns,
        };
      });
      set_columns([...baseColumns, ...monthColumns]);
    }
  };

  const getIfShowReport = async () => {
    const { systemId } = JSON.parse(
      localStorage.getItem('currentSelectedTab') as string,
    );
    const resp = await getParamsDataBySysId(systemId, '1845698984623083520');
    if (resp) {
      set_needShowReportCode(resp.value);
    }
  };

  const getTableData = async (params: any) => {
    const { responsibilityCode, filter = undefined } = params;
    if (!responsibilityCode) return [];

    if (!nextLevel) {
      let resp;
      if (isYearMode) {
        // 年度模式调用年度接口
        resp = await getBatchComputeProfitListByYear({ ...params });
      } else {
        // 月度模式调用原有接口
        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 = isYearMode
          ? transformYearData(resp)
          : transformData(resp);
        if (currentTab.value == '1') {
          const allParents = findAllParents(realData);

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

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

    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',
            align: 'right',
            renderText(num: number, record: any) {
              return formatMoneyNumber(num, {
                decimalPlaces: record.decimalPlace,
                useThousandSeparator: Boolean(record.permil),
              });
            },
          },
        ]);
        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',
                align: 'right',
              },
            ],
          },
          {
            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, {
                      decimalPlaces: param.decimalPlace,
                      useThousandSeparator: Boolean(param.permil),
                    }),
                    shareParamValue: param.shareParamNum,
                    shareParamRate: param.shareParamRate,
                    amount: formatMoneyNumber(param.shareParamValue, {
                      decimalPlaces: param.decimalPlace,
                      useThousandSeparator: Boolean(param.permil),
                    }),
                  });
                },
              );
              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 getResponsibleCenterList = async (reportType: string) => {
    const resp = await getResponsibleCenters(reportType);
    if (resp) {
      set_responsibleCenters(resp);
    }
  };

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

  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);
      const dataRowColors: string[] = [];

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

      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' },
          };
        }
      });

      const headerRowsCount = headerRows.length;
      dataRowColors.forEach((rowColor, index) => {
        const excelArgb = convertToExcelArgb(rowColor);
        const rowIndex = headerRowsCount + index;
        for (let colIndex = 0; colIndex < leafColumns.length; colIndex++) {
          const cellRef = XLSX.utils.encode_cell({ r: rowIndex, c: colIndex });
          if (!worksheet[cellRef]) continue;
          const prevStyle = worksheet[cellRef].s || {};
          worksheet[cellRef].s = {
            ...prevStyle,
            font: { ...(prevStyle.font || {}), color: { rgb: excelArgb } },
            alignment: prevStyle.alignment || {
              vertical: 'center',
              horizontal: 'center',
            },
          };
        }
      });

      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      XLSX.writeFile(
        workbook,
        currentTab ? `${currentTab.label}.xlsx` : 'table_data.xlsx',
      );
    } catch (error) {
      console.error('Export failed:', error);
    }
  };

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

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

  useEffect(() => {
    if (computeRangeDate && currentTabKey != undefined) {
      getResponsibleCenterList(currentTabKey);
      set_nextLevel(undefined);
      set_allParentsKeys([]);
    }
  }, [computeRangeDate, currentTabKey]);

  useEffect(() => {
    if (currentSelectedRespon) {
      if (isYearMode) {
        // 年度模式：确保传递的是纯年份
        const startYear = computeRangeDate[0]
          ? computeRangeDate[0].substring(0, 4)
          : '';
        const endYear = computeRangeDate[1]
          ? computeRangeDate[1].substring(0, 4)
          : '';
        set_tableDataFilterParams({
          ...tableDataFilterParams,
          responsibilityCode: currentSelectedRespon.responsibilityCode,
          reportType: currentTabKey,
          startYear: startYear,
          endYear: endYear,
        });
      } else {
        set_tableDataFilterParams({
          ...tableDataFilterParams,
          responsibilityCode: currentSelectedRespon.responsibilityCode,
          reportType: currentTabKey,
          beginComputeDate: computeRangeDate[0],
          endComputeDate: computeRangeDate[1],
        });
      }
      set_nextLevel(undefined);
    }
    set_allParentsKeys([]);
  }, [currentSelectedRespon]);

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

  return (
    <KCIMPagecontainer className="DepartmentCostCalc" title={false}>
      <div className="header">
        <div className="search">
          <span>{isYearMode ? '核算年份：' : '核算年月：'}</span>
          <RangePicker
            onChange={(data, dateString) => {
              // console.log({data,dateString});
              set_computeRangeDate(dateString);
              setInitialState((s: any) => ({
                ...s,
                computeDate: dateString[0],
              }));
              if (isYearMode) {
                // 年度模式：提取年份部分
                const startYear =
                  data?.[0]?.year()?.toString() || dateString[0];
                const endYear = data?.[1]?.year()?.toString() || dateString[1];
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  startYear: startYear,
                  endYear: endYear,
                });
              } else {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  beginComputeDate: dateString[0],
                  endComputeDate: dateString[1],
                });
              }
            }}
            picker={isYearMode ? 'year' : 'month'}
            locale={locale}
            autoComplete="off"
            defaultValue={
              isYearMode
                ? [
                    moment(computeRangeDate[0], 'YYYY'),
                    moment(computeRangeDate[1], 'YYYY'),
                  ]
                : [
                    moment(computeRangeDate[0], 'YYYY-MM'),
                    moment(computeRangeDate[1], 'YYYY-MM'),
                  ]
            }
            format={isYearMode ? 'YYYY' : '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: 'children',
              }}
              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="iconzhuye" />
                    </span>
                    {nextLevel.reportName}
                  </div>
                )}
              </div>

              {(!nextLevel || (nextLevel && needShowReportCode == '0')) && (
                <div className="btnGroup">
                  {/* <span className='btn' onClick={() => openTableDataDrawer()}>报表数据</span> */}
                  <span className="btn" onClick={() => handleCollapseAll()}>
                    全部折叠
                  </span>
                  <span
                    className="btn"
                    style={{ marginRight: 16 }}
                    onClick={() => handleExpandNext()}
                  >
                    展开下一层
                  </span>
                  {!nextLevel && (
                    <span className="calc" onClick={() => handleExport()}>
                      导出
                    </span>
                  )}
                </div>
              )}
            </div>

            {needShowReportCode != '0' && nextLevel && (
              <ReportExport
                reportCode={needShowReportCode}
                tableScrollH={574}
                propsParams={{
                  compute_date: nextLevel.date,
                  reportId: nextLevel.reportId,
                  reportType: currentTabKey,
                  responsibilityCode: currentSelectedRespon.responsibilityCode,
                }}
              />
            )}
            {(needShowReportCode == '0' ||
              (needShowReportCode != '0' && !nextLevel)) && (
              <KCIMTable
                pagination={false}
                bordered
                rowClassName={(record) =>
                  `${
                    record.children ? 'has-children ' : ''
                  }hover-row report-font-color-row`
                }
                onRow={(record: any) => ({
                  style: {
                    ['--report-font-color' as any]: getReportFontColor(record),
                  } as React.CSSProperties,
                })}
                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)` }}
                actionRef={tableRef}
                rowKey="id"
                params={tableDataFilterParams}
                request={(params) => getTableData(params)}
              />
            )}
          </div>
        </div>
      </div>
    </KCIMPagecontainer>
  );
}
