import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';

interface CheckItem {
  // name: string;
  // tp: number;
  issues: string;
  // situation: string;
}

interface SourceData {
  cgrpPath: string;
  content: string;
  item: string;
  checkid: CheckItem[];
}

// 传入数据即可导出
export const exportListDataToExcel = async (data: SourceData[], filename = '问题清单.xlsx') => {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet('问题清单');

  const headers = ['一级分组', '二级分组', '合规条目', '检查项', '存在问题'];
  sheet.addRow(headers);

  const headerRow = sheet.getRow(1);
  headerRow.font = { bold: true };
  headerRow.alignment = { vertical: 'middle', horizontal: 'center' };
  headerRow.eachCell((cell) => {
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'D9E1F2' },
    };
    cell.border = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' },
    };
  });

  let currentRowIndex = 2;
  let mergeTracker: {
    group1: string;
    group2: string;
    startRow: number;
  } | null = null;
  for (const entry of data) {
    const [group1, group2 = ''] = entry.cgrpPath.split('/');
    const checks = entry.checkid.length > 0 ? entry.checkid : [null];
    const startRow = currentRowIndex;

    for (const check of checks) {
      sheet.addRow([group1, group2, entry.item, entry.content, check?.issues ?? '']);
      currentRowIndex++;
    }

    const endRow = currentRowIndex - 1;
    if (endRow > startRow) {
      sheet.mergeCells(`C${startRow}:C${endRow}`);
      sheet.mergeCells(`D${startRow}:D${endRow}`);
    }
    // 合并一级分组和二级分组
    if (!mergeTracker || mergeTracker.group1 !== group1 || mergeTracker.group2 !== group2) {
      if (mergeTracker) {
        const lastStart = mergeTracker.startRow;
        const lastEnd = currentRowIndex - checks.length - 1;
        if (lastEnd > lastStart) {
          sheet.mergeCells(`A${lastStart}:A${lastEnd}`);
          if (mergeTracker.group2) {
            sheet.mergeCells(`B${lastStart}:B${lastEnd}`);
          }
        }
      }
      // 新建合并追踪器
      mergeTracker = {
        group1,
        group2,
        startRow,
      };
    }
  }
  // 处理最后一组分组的合并
  if (mergeTracker) {
    const lastStart = mergeTracker.startRow;
    const lastEnd = currentRowIndex - 1;
    if (lastEnd > lastStart) {
      sheet.mergeCells(`A${lastStart}:A${lastEnd}`);
      if (mergeTracker.group2) {
        sheet.mergeCells(`B${lastStart}:B${lastEnd}`);
      }
    }
  }
  sheet.columns.forEach((column, colIndex) => {
    let maxLength = 10;
    column.eachCell?.((cell) => {
      const text = cell.value?.toString() || '';
      maxLength = Math.max(maxLength, text.length + 2);
      if (colIndex === 3 || colIndex === 4) {
        maxLength = Math.min(maxLength, 60);
        cell.alignment = { vertical: 'middle', horizontal: 'left', wrapText: true };
      } else {
        cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
      }
      column.width = maxLength;
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' },
      };
    });
  });

  const buffer = await workbook.xlsx.writeBuffer();
  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, filename);
};
