import * as XLSX from 'xlsx';
import { describe, expect, it } from 'vitest';

import { parseMaterialsFromExcel } from './materialImportParser';

function makeWorkbookFile(sheets: Record<string, unknown[][]>, fileName = '采购清单.xlsx') {
  const workbook = XLSX.utils.book_new();
  Object.entries(sheets).forEach(([sheetName, rows]) => {
    XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet(rows), sheetName);
  });
  const buffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
  const file = new File([buffer], fileName, {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  });
  Object.defineProperty(file, 'arrayBuffer', {
    value: async () => buffer,
  });
  return file;
}

describe('parseMaterialsFromExcel', () => {
  it('parses multiple sheets with decorated header aliases, quantities, and blank row filtering', async () => {
    const file = makeWorkbookFile({
      土建: [
        ['项目', '2026 第一批'],
        ['材料名称（必填）', '规格型号/参数', '需求数量', '单位', '备注说明'],
        ['球墨铸铁井盖', 'DN700', '1,200.5 套', '套', '含防盗链'],
        ['', '', '', '', ''],
      ],
      电气: [
        ['物资名称', '型号规格', '采购数', '单位'],
        ['配电箱', 'AL-1', '2台', '台'],
      ],
    });

    await expect(parseMaterialsFromExcel(file)).resolves.toEqual([
      expect.objectContaining({
        material_name: '球墨铸铁井盖',
        specification: 'DN700',
        quantity: 1200.5,
        unit: '套',
        remarks: '含防盗链',
      }),
      expect.objectContaining({
        material_name: '配电箱',
        specification: 'AL-1',
        quantity: 2,
        unit: '台',
      }),
    ]);
  });

  it('returns an empty list when no sheet contains a valid material header', async () => {
    const file = makeWorkbookFile({
      说明: [
        ['项目名称', '说明'],
        ['一标段', '仅用于说明，没有采购物料表头'],
      ],
    });

    await expect(parseMaterialsFromExcel(file)).resolves.toEqual([]);
  });
});
