import ExcelJS from 'exceljs';

import { MEDICAL_RECORD_FIELD_OPTIONS } from '../config/constants';

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 = [
  '字段编码',
  '词条名称',
  '正文',
  '临床意义',
  '排序',
  '状态',
] as const;

/**
 * 下载病历词条导入模板（含字段编码说明 sheet）
 */
export async function exportMedicalRecordEntryTemplate(): Promise<ArrayBuffer> {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet('词条导入');
  sheet.columns = [
    { width: 18 },
    { width: 20 },
    { width: 36 },
    { width: 24 },
    { width: 10 },
    { width: 10 },
  ];
  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' };
    cell.border = THIN_BORDER;
  });
  // 示例行：方便运营对照填写
  const sample = sheet.addRow([
    'chief_complaint',
    '头痛三天',
    '头痛三天，加重一天',
    '常见主诉示例',
    100,
    1,
  ]);
  sample.eachCell((cell) => {
    cell.border = THIN_BORDER;
    cell.alignment = { vertical: 'middle' };
  });
  sheet.views = [{ state: 'frozen', ySplit: 1 }];

  const tip = workbook.addWorksheet('字段编码说明');
  tip.columns = [{ width: 20 }, { width: 16 }];
  const tipHead = tip.addRow(['字段名称', '字段编码']);
  tipHead.eachCell((cell) => {
    cell.font = { bold: true };
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFD9EAD3' },
    };
    cell.border = THIN_BORDER;
  });
  MEDICAL_RECORD_FIELD_OPTIONS.forEach((opt) => {
    const row = tip.addRow([opt.label, opt.value]);
    row.eachCell((cell) => {
      cell.border = THIN_BORDER;
    });
  });
  tip.addRow([]);
  tip.addRow([
    '填写说明',
    '「字段编码」可填右侧英文编码，也可直接填左侧中文名（如：主诉）',
  ]);
  tip.addRow(['状态说明', '1=启用，0=禁用；空默认启用']);
  tip.addRow(['拼音首拼', '由系统根据词条名称自动生成，无需填写']);
  tip.addRow([
    '按字段菜单导入',
    '在「主诉/既往史」等拆分页导入时，字段编码列可留空，系统自动归属当前字段',
  ]);

  // 给「字段编码」列加下拉，减少填错中文/编码混用导致整表无效
  const codeList = MEDICAL_RECORD_FIELD_OPTIONS.map((o) => o.value).join(',');
  // Excel 数据验证公式长度有限；字段不多时可直接列枚举
  sheet.dataValidations.add('A2:A2001', {
    type: 'list',
    allowBlank: true,
    formulae: [`"${codeList}"`],
    showErrorMessage: true,
    errorTitle: '字段编码',
    error: '请从下拉选择英文编码，或手动填写中文名（如：主诉）',
  });

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