import type { Range } from "xlsx";
import { writeFile, utils } from "xlsx";

export const exportExcel = (fileData: any[], headerName: any[], headerProp: string[], fileName: string) => {
  // console.log(fileData, headerName, headerProp, fileName);
  const repeatingData: any = {};
  const name: string[][] = [[], [], []];
  const data = fileData.map((obj) => {
    return headerProp.map((prop) => obj[prop]);
  });
  name[0].push("省份", "储备仓库", ...headerName.map((item) => item.matypename2));
  name[1].push("省份", "储备仓库", ...headerName.map((item) => item.matypename3));
  name[2].push("省份", "储备仓库", ...headerName.map((item) => item.matypename4));
  name[0].forEach((item, index) => {
    const itemIndex = name[0].findIndex((ite) => ite === item);
    if (itemIndex !== index) {
      repeatingData[item] = { s: { r: 0, c: itemIndex }, e: { r: 0, c: index } };
    }
  });
  const cols = data.map((item) => item[0]);
  cols.forEach((item, index) => {
    const itemIndex = cols.findIndex((ite) => ite === item);
    if (itemIndex !== index) {
      repeatingData[item] = { s: { r: itemIndex + 3, c: 0 }, e: { r: index + 3, c: 0 } };
    }
  });
  data.unshift(...name);
  const ws = utils.aoa_to_sheet(data);
  const wb = utils.book_new();
  // 设置单元格样式
  const cellRef = utils.encode_cell({ c: 0, r: 0 });
  const cell = ws[cellRef];
  if (!cell.s) cell.s = {};
  cell.s.alignment = {
    horizontal: "center",
    vertical: "center"
  };
  const merges: Range[] = [];
  Object.keys(repeatingData).forEach((item) => {
    merges.push(repeatingData[item]);
  });
  ws["!merges"] = [
    { s: { r: 0, c: 0 }, e: { r: 2, c: 0 } },
    { s: { r: 0, c: 1 }, e: { r: 2, c: 1 } },
    { s: { r: 3, c: 0 }, e: { r: 3, c: 1 } },
    ...merges
  ];
  utils.book_append_sheet(wb, ws, fileName);
  writeFile(wb, `${fileName}.xlsx`);
  // console.log(cellRef, cell);
};
