import ExcelJS from 'exceljs';

const THIN_BORDER: Partial<ExcelJS.Borders> = {
  top: { style: 'thin', color: { argb: 'FF000000' } },
  left: { style: 'thin', color: { argb: 'FF000000' } },
  bottom: { style: 'thin', color: { argb: 'FF000000' } },
  right: { style: 'thin', color: { argb: 'FF000000' } },
};

const HEADERS = [
  '序号',
  '药方名字',
  '条文编号',
  '药品JSON',
  '药材速览',
  '原方',
  '药方主治(文言文)',
  '现代主治(白话文)',
  '拼音首拼',
  '拼音全拼',
] as const;

/**
 * 下载金方导入模板（含字段说明 sheet）
 */
export async function exportGoldenFormulaTemplate(): Promise<ArrayBuffer> {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet('金方导入');
  sheet.columns = [
    { width: 8 },   // 序号
    { width: 14 },  // 药方名字
    { width: 14 },  // 条文编号
    { width: 52 },  // 药品JSON
    { width: 24 },  // 药材速览
    { width: 48 },  // 原方
    { width: 28 },  // 药方主治(文言文)
    { width: 28 },  // 现代主治(白话文)
    { width: 12 },  // 拼音首拼
    { width: 16 },  // 拼音全拼
  ];
  const headerRow = sheet.addRow([...HEADERS]);
  headerRow.height = 28;
  headerRow.eachCell((cell) => {
    cell.font = { bold: true };
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFFFF00' },
    };
    cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
    cell.border = THIN_BORDER;
  });
  // 示例：系统克数 + 展示扩展（古代剂量/炮制）
  const sampleDrugs =
    '[{"name":"桂枝","dose":"9","unit":"g","usage":"","ancient_dose":"三两","prep":"去皮"},{"name":"芍药","dose":"9","unit":"g","ancient_dose":"三两"},{"name":"甘草","dose":"6","unit":"g","ancient_dose":"二两","prep":"炙"},{"name":"生姜","dose":"9","unit":"g","ancient_dose":"三两","prep":"切"},{"name":"大枣","dose":"12","unit":"g","ancient_dose":"十二枚","prep":"擘"}]';
  const sampleOriginal =
    '桂枝三两，去皮 芍药三两 甘草二两，炙 生姜三两，切 大枣十二枚，擘。右五味，㕮咀三味，以水七升，微火煮取三升，去滓，适寒温，服一升。服已须臾，啜热稀粥一升余，以助药力。禁生冷、粘滑、肉面、五辛、酒酪、臭恶等物。';
  const sample = sheet.addRow([
    1,                         // 序号
    '桂枝汤',                  // 药方名字
    '第12条',                  // 条文编号
    sampleDrugs,               // 药品JSON
    '桂枝、芍药、甘草、生姜、大枣', // 药材速览
    sampleOriginal,            // 原方
    '太阳中风，阳浮而阴弱',    // 药方主治(文言文)
    '外感风寒表虚证',          // 现代主治(白话文)
    'gzt',                     // 拼音首拼
    'guizhitang',              // 拼音全拼
  ]);
  sample.height = 80;
  sample.eachCell((cell) => {
    cell.border = THIN_BORDER;
    cell.alignment = { vertical: 'middle', wrapText: true };
  });
  sheet.views = [{ state: 'frozen', ySplit: 1 }];

  const tip = workbook.addWorksheet('填写说明');
  tip.columns = [{ width: 18 }, { width: 80 }];
  const tipHead = tip.addRow(['字段', '说明']);
  tipHead.eachCell((cell) => {
    cell.font = { bold: true };
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFD9EAD3' },
    };
    cell.border = THIN_BORDER;
  });
  const tips: [string, string][] = [
    ['序号', '仅作行号，不导入；可空'],
    ['药方名字', '必填'],
    ['条文编号', '典籍条文编号，如「第12条」，可空'],
    [
      '药品JSON',
      '系统字段（导入用）：name/dose(克数数字)/unit(固定g)/usage(先煎、后下等，可空)。展示扩展（仅展示）：ancient_dose(如三两、十二枚)、prep(去皮、炙、切、擘)。勿把古代单位或炮制写进 dose/unit/usage。',
    ],
    ['药材速览', '展示用简短药味列表'],
    [
      '原方',
      '典籍药味+煮法+服法+禁忌全文，如「桂枝三两，去皮…服一升…禁生冷…」',
    ],
    ['药方主治(文言文)', '主治典籍原文'],
    ['现代主治(白话文)', '主治白话译文'],
    ['拼音首拼', '可空，系统按药方名自动生成'],
    ['拼音全拼', '可空，系统按药方名自动生成'],
  ];
  tips.forEach(([k, v]) => {
    const row = tip.addRow([k, v]);
    row.eachCell((cell) => {
      cell.border = THIN_BORDER;
      cell.alignment = { wrapText: true, vertical: 'top' };
    });
  });

  return workbook.xlsx.writeBuffer() as Promise<ArrayBuffer>;
}
