/**
 * 门店仓库 ExcelJS 导出（数据来自 export-data）
 * 价格/单位强制文本写出，避免 IEEE 浮点回读假变更
 */
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' } },
};

export type StoreExportRow = {
  drug_id?: number | string;
  drug_number?: string;
  drug_name?: string;
  pinyin_simple?: string;
  unit_name?: string;
  type_text?: string;
  status_text?: string;
  buy_price?: string | number;
  price?: string | number;
  created_at?: string;
};

const LIST_HEADERS = [
  '药品ID',
  'ErpCode',
  '药名',
  '拼音首拼',
  '单位',
  '类型',
  '状态',
  '供货价',
  '当前零售价',
  '创建时间',
] as const;

const PRICE_HEADERS = [
  '药品ID',
  'ErpCode',
  '药名',
  '拼音首拼',
  '单位',
  '当前零售价',
] as const;

function priceToCellText(value: unknown): string {
  if (value === null || value === undefined || value === '') {
    return '';
  }
  return String(value).trim();
}

function forceTextCell(cell: ExcelJS.Cell, text: string) {
  cell.value = text;
  cell.numFmt = '@';
  cell.border = THIN_BORDER;
  cell.alignment = { horizontal: 'center', vertical: 'middle' };
}

function styleHeader(row: ExcelJS.Row) {
  row.height = 28;
  row.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;
  });
}

function styleDataRowFill(row: ExcelJS.Row, index: number) {
  if (index % 2 !== 1) {
    return;
  }
  row.eachCell((cell) => {
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFF2F2F2' },
    };
  });
}

/** 门店列表导出 */
export async function exportStoreListExcel(
  rows: StoreExportRow[],
  sheetName = '门店仓库',
): Promise<ArrayBuffer> {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet(sheetName);
  sheet.columns = [
    { width: 10 },
    { width: 14 },
    { width: 18 },
    { width: 12 },
    { width: 10 },
    { width: 12 },
    { width: 10 },
    { width: 12 },
    { width: 14 },
    { width: 18 },
  ];
  styleHeader(sheet.addRow([...LIST_HEADERS]));
  rows.forEach((item, index) => {
    const row = sheet.addRow([]);
    const values = [
      String(item.drug_id ?? ''),
      String(item.drug_number ?? ''),
      String(item.drug_name ?? ''),
      String(item.pinyin_simple ?? ''),
      String(item.unit_name ?? ''),
      String(item.type_text ?? ''),
      String(item.status_text ?? ''),
      priceToCellText(item.buy_price),
      priceToCellText(item.price),
      String(item.created_at ?? ''),
    ];
    values.forEach((text, i) => forceTextCell(row.getCell(i + 1), text));
    styleDataRowFill(row, index);
  });
  sheet.views = [{ state: 'frozen', ySplit: 1 }];
  const buffer = await workbook.xlsx.writeBuffer();
  return buffer as ArrayBuffer;
}

/** 门店改价模板（预览弹窗） */
export async function exportStorePriceExcel(
  items: Array<{
    drug_id?: number | string;
    drug_number?: string;
    drug_name?: string;
    pinyin_simple?: string;
    unit_name?: string;
    price?: string | number;
  }>,
  sheetName = '门店改价',
): Promise<ArrayBuffer> {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet(sheetName);
  sheet.columns = [
    { width: 10 },
    { width: 14 },
    { width: 18 },
    { width: 12 },
    { width: 10 },
    { width: 14 },
  ];
  styleHeader(sheet.addRow([...PRICE_HEADERS]));
  items.forEach((item, index) => {
    const row = sheet.addRow([]);
    const values = [
      String(item.drug_id ?? ''),
      String(item.drug_number ?? ''),
      String(item.drug_name ?? ''),
      String(item.pinyin_simple ?? ''),
      String(item.unit_name ?? ''),
      priceToCellText(item.price),
    ];
    values.forEach((text, i) => forceTextCell(row.getCell(i + 1), text));
    styleDataRowFill(row, index);
  });
  sheet.views = [{ state: 'frozen', ySplit: 1 }];
  const buffer = await workbook.xlsx.writeBuffer();
  return buffer as ArrayBuffer;
}
