/**
 * 总仓 ExcelJS 导出
 * - list：列表「导出」完整列（来自 export-data）
 * - price：改价模板列（预览弹窗下载模板）
 * 价格/单位一律文本原样写出，避免浮点改写
 */
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' } },
};

/** export-data 行结构 */
export type WarehouseExportRow = {
  drug_id?: number | string;
  drug_number?: string;
  drug_name?: string;
  pinyin_simple?: string;
  unit_name?: string;
  type_text?: string;
  status_text?: string;
  market_price?: string | number;
  price?: string | number;
  created_at?: string;
};

const LIST_HEADERS = [
  '药品ID',
  '商品编码',
  '通用名',
  '拼音首拼',
  '单位',
  '类型',
  '状态',
  '每克供货价',
  '每克零售价',
  '创建时间',
] as const;

const PRICE_HEADERS = [
  '药品ID',
  '商品编码',
  '通用名',
  '拼音首拼',
  '单位',
  '每克供货价',
  '每克零售价',
] as const;

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

function resolveUnitName(item: { unit_name?: string; drug?: { unit?: { name?: string } } }): string {
  const direct = (item.unit_name ?? '').trim();
  if (direct) {
    return direct;
  }
  const nested = item.drug?.unit?.name;
  return nested != null ? String(nested).trim() : '';
}

/**
 * 强制单元格为文本：ExcelJS addRow 遇「0.14」可能自动转 number，
 * 再经 IEEE 回读会漂成 0.139999… / 0.90，造成假变更
 */
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-data → ExcelJS
 */
export async function exportWarehouseListExcel(
  rows: WarehouseExportRow[],
  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: 14 },
    { 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 ?? ''),
      resolveUnitName(item),
      String(item.type_text ?? ''),
      String(item.status_text ?? ''),
      priceToCellText(item.market_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 exportWarehousePriceExcel(
  items: WarehouseBatchPriceItem[] | WarehouseExportRow[],
  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 },
    { 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 ?? ''),
      resolveUnitName(item),
      priceToCellText(item.market_price),
      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;
}
