import ExcelJS from 'exceljs';

import type { WarehouseBatchPriceItem } from '../api';

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 = [
  '药品ID',
  '商品编码',
  '通用名',
  '拼音首拼',
  '每克供货价',
  '每克零售价',
] as const;

export async function exportWarehousePriceExcel(
  items: WarehouseBatchPriceItem[],
): Promise<ArrayBuffer> {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet('中药价格');

  sheet.columns = [
    { width: 10 },
    { width: 14 },
    { width: 18 },
    { width: 12 },
    { width: 14 },
    { width: 14 },
  ];

  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;
  });

  items.forEach((item, index) => {
    const row = sheet.addRow([
      item.drug_id,
      item.drug_number ?? '',
      item.drug_name ?? '',
      item.pinyin_simple ?? '',
      item.market_price ?? 0,
      item.price ?? 0,
    ]);
    row.eachCell((cell, colNumber) => {
      cell.border = THIN_BORDER;
      cell.alignment = { horizontal: 'center', vertical: 'middle' };
      if (colNumber === 2) {
        cell.numFmt = '@';
      } else if (colNumber >= 5) {
        cell.numFmt = '#,##0.00';
      }
    });
    if (index % 2 === 1) {
      row.eachCell((cell) => {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFF2F2F2' },
        };
      });
    }
  });

  sheet.views = [{ state: 'frozen', ySplit: 1 }];

  const buffer = await workbook.xlsx.writeBuffer();
  return buffer as ArrayBuffer;
}
