/*
 * 导出相关工具（最小落地版）
 * 仅抽离现有 calcPageTemplate 的导出格式化逻辑，避免页面过重
 */

import { ProColumns } from '@ant-design/pro-components';
import exportTableToExcel from './tableToExcel';
import exportTableToMultiExcel from './tableToMultiHeaderExcel';
import { formatMoneyNumber, formatToPercentage } from './format';
import * as XLSX from 'xlsx-js-style';
import { saveAs } from 'file-saver';

export interface ExportOptions {
  // 页面 key，用于处理特殊格式化
  calcPageKey?: string;
  // 是否为树形数据时需要缩进的列
  indentColumn?: string;
}

const parseExcelRgbColor = (rawColor: any): string | undefined => {
  if (typeof rawColor !== 'string') return undefined;
  const color = rawColor.trim();
  if (!color) return undefined;

  if (/^[0-9a-fA-F]{6}$/.test(color)) return color.toUpperCase();

  if (/^#[0-9a-fA-F]{6}$/.test(color)) return color.slice(1).toUpperCase();

  if (/^#[0-9a-fA-F]{3}$/.test(color)) {
    const short = color.slice(1).toUpperCase();
    return `${short[0]}${short[0]}${short[1]}${short[1]}${short[2]}${short[2]}`;
  }

  const rgbMatch = color.match(/^rgba?\(([^)]+)\)$/i);
  if (rgbMatch) {
    const parts = rgbMatch[1].split(',').map((p) => p.trim());
    if (parts.length >= 3) {
      const r = Math.max(0, Math.min(255, Number(parts[0])));
      const g = Math.max(0, Math.min(255, Number(parts[1])));
      const b = Math.max(0, Math.min(255, Number(parts[2])));
      if ([r, g, b].every((n) => !Number.isNaN(n))) {
        return [r, g, b]
          .map((n) => n.toString(16).padStart(2, '0').toUpperCase())
          .join('');
      }
    }
  }

  return undefined;
};

const exportWholeHospWithFontColor = (
  data: any[],
  flatKeys: string[],
  leafColumns: any[],
  rowFontColors: Array<string | undefined>,
  fileName: string,
) => {
  const header = leafColumns.map((column: any) => column.title);
  const dataValues = data.map((row: any) => flatKeys.map((key) => row[key]));
  const allData = [header, ...dataValues];

  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.aoa_to_sheet(allData);

  // 自动计算列宽，保持与现有导出一致
  ws['!cols'] = header.map((_: any, index: number) => {
    const maxLength = allData.reduce((max, row) => {
      const cellValue = row[index] ? row[index].toString() : '';
      return Math.max(max, cellValue.length);
    }, 0);
    return { wch: maxLength + 2 };
  });

  // 行级字体颜色（仅数据行，跳过表头）
  for (let rowIndex = 0; rowIndex < rowFontColors.length; rowIndex++) {
    const color = rowFontColors[rowIndex];
    if (!color) continue;
    const excelRow = rowIndex + 1;
    for (let colIndex = 0; colIndex < flatKeys.length; colIndex++) {
      const cellRef = XLSX.utils.encode_cell({ r: excelRow, c: colIndex });
      if (!ws[cellRef]) continue;
      const prevStyle = ws[cellRef].s || {};
      ws[cellRef].s = {
        ...prevStyle,
        font: {
          ...(prevStyle.font || {}),
          color: { rgb: color },
        },
      };
    }
  }

  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
  saveAs(
    new Blob([wbout], { type: 'application/octet-stream' }),
    `${fileName}.xlsx`,
  );
};

/**
 * 根据当前列与数据，进行必要的格式化与树形缩进，并导出为 Excel
 * 注意：本方法内的“wholeHospCostCalculate”逻辑与原实现保持一致，避免行为变化
 */
export function exportCalcPageDataToExcel(
  columns: ProColumns[],
  totalData: any[],
  options: ExportOptions = {},
) {
  const { calcPageKey, indentColumn } = options;

  // 扁平化列（仅保留叶子列，保证多级表头时也能拿到 dataIndex）
  const flattenColumns = (cols: any[]): any[] => {
    const result: any[] = [];
    (cols || []).forEach((c: any) => {
      if (Array.isArray(c?.children) && c.children.length > 0) {
        result.push(...flattenColumns(c.children));
      } else if (c?.dataIndex) {
        result.push(c);
      }
    });
    return result;
  };
  const leafColumns: any[] = flattenColumns(columns as any[]);
  const flatKeys: string[] = leafColumns.map((c: any) => String(c.dataIndex));

  // 列配置索引，便于判断数值列（基于叶子列）
  const columnMap = new Map<string, any>();
  (leafColumns as any[])?.forEach?.((c) => {
    if (c && c.dataIndex) columnMap.set(String(c.dataIndex), c);
  });

  // 递归处理数据（支持 children），并为 indentColumn 添加缩进
  const data: any[] = [];
  const rowFontColors: Array<string | undefined> = [];
  const processData = (items: any[], level: number = 0) => {
    items.forEach((item) => {
      const row: { [key: string]: any } = {};
      const rowFontColor =
        calcPageKey === 'wholeHospCostCalculate'
          ? parseExcelRgbColor(
              item?.fontColor || item?.fontcolor || item?.font_color,
            )
          : undefined;
      flatKeys.forEach((key) => {
        if (indentColumn && key === indentColumn) {
          // 使用 Unicode 不可见空格来缩进
          row[`${key}`] = `${'\u00A0'.repeat(level * 4)}${item[`${key}`]}`;
        } else if (
          item.children &&
          item.children.length > 0 &&
          calcPageKey !== 'wholeHospCostCalculate'
        ) {
          // 非全院损益时，有 children 的父节点导出为空字符串
          row[`${key}`] = '';
        } else {
          if (calcPageKey === 'wholeHospCostCalculate') {
            if (key === 'amount') {
              const { decimalPlace, permil, dataType, children, calcType } =
                item;
              if (children && children.length > 0 && calcType === '0') {
                row[`${key}`] = '';
              } else if (dataType === 2) {
                row[`${key}`] =
                  typeof item[`${key}`] === 'number' && !isNaN(item[`${key}`])
                    ? `${(item[`${key}`] * 100).toFixed(decimalPlace || 2)}%`
                    : item[`${key}`];
              } else {
                const formatOptions = {
                  decimalPlaces: decimalPlace !== undefined ? decimalPlace : 2,
                  useThousandSeparator: permil === 1,
                };
                row[`${key}`] = formatMoneyNumber(
                  item[`${key}`],
                  formatOptions,
                );
              }
            } else if (key === 'percent') {
              const { children, calcType } = item;
              row[`${key}`] =
                children && children.length > 0 && calcType === '0'
                  ? ''
                  : formatToPercentage(item[`${key}`]);
            } else {
              row[`${key}`] = item[`${key}`];
            }
          } else if (
            calcPageKey === 'deptDirectMedicalCost' ||
            calcPageKey === 'deptFullDirectCost' ||
            calcPageKey === 'hospitalVisitCostComposition' ||
            calcPageKey === 'hospitalDeptVisitCost' ||
            calcPageKey === 'deptCostAllocationSummary' ||
            calcPageKey === 'hospitalBedDayCostComposition'
          ) {
            // 这两个页面导出需要默认启用千分号，并按行的 decimalPlace 控制小数位
            const col = columnMap.get(key);
            const isNumericColumn = col && col.align === 'right';
            if (isNumericColumn) {
              const decimalPlaces =
                typeof item?.decimalPlace === 'number' ? item.decimalPlace : 2;
              row[`${key}`] = formatMoneyNumber(item[`${key}`], {
                decimalPlaces,
                useThousandSeparator: true,
              });
            } else {
              row[`${key}`] = item[`${key}`];
            }
          } else {
            row[`${key}`] = item[`${key}`];
          }
        }
      });

      data.push(row);
      rowFontColors.push(rowFontColor);
      if (item.children && item.children.length > 0) {
        processData(item.children, level + 1);
      }
    });
  };

  processData(totalData);

  // 根据页面 key 设定导出文件名
  const fileNameMap: Record<string, string> = {
    wholeHospCostCalculate: '全院损益报表',
    projectCostCalc: '项目成本计算',
    deptDirectMedicalCost: '医院科室直接成本表（医疗成本）',
    deptFullDirectCost: '医院科室直接成本表（全成本）',
    clinicalDeptMedicalCost: '临床服务类科室全成本（医疗成本）',
    clinicalDeptFullCost: '临床服务类科室全成本（全成本）',
    clinicalDeptFullCostAnalysis: '临床服务类科室全成本构成分析表',
    deptCostAllocationSummary: '医院科室成本分摊汇总表',
    hospitalVisitCostComposition: '医院诊次成本构成表',
    hospitalBedDayCostComposition: '医院床日成本构成表',
    hospitalDeptVisitCost: '医院科室诊次成本表',
    hospitalDeptBedDayCost: '医院科室床日成本表',
    hospitalServiceProjectCost: '医院医疗服务项目成本汇总表',
    medicalServiceCostDetail: '医院医疗服务项目成本明细表',
    diseaseCostDetail: '医院病种成本明细表',
    diseaseCostCompositionDetail: '病种成本构成明细表',
    drgCostDetail: '医院DRG成本明细表',
    drgCostCompositionDetail: '医院DRG成本构成明细表',
    deptDiseaseCostCompositionDetail: '服务单元病种成本构成明细表',
    deptDrgCostCompositionDetail: '医院服务单元DRG成本构成明细表',
  };
  const fileName =
    calcPageKey && fileNameMap[calcPageKey]
      ? fileNameMap[calcPageKey]
      : '项目成本计算';

  // 判断是否为多级表头报表
  const hasMultiLevelHeader = (columns as any[])?.some?.(
    (col: any) => Array.isArray(col?.children) && col.children.length > 0,
  );

  if (calcPageKey === 'wholeHospCostCalculate') {
    exportWholeHospWithFontColor(
      data,
      flatKeys,
      leafColumns,
      rowFontColors,
      fileName,
    );
    return;
  }

  if (hasMultiLevelHeader) {
    // 使用多级表头导出
    exportTableToMultiExcel(data, columns as any[], fileName);
  } else {
    // 使用简单表头导出
    exportTableToExcel(data, columns as any[], fileName);
  }
}
