import { Workbook } from "exceljs";
// 合并行/列数量
interface merges {
  header?: number[] | number;
  content?: number[] | number;
}
/**
 * data: 表格内容
 * tableheader: 表头内容
 * fileName: 文件名
 * merges: 合并数据
 * fixedCol: 固定列数量
 */
interface exportPayload {
  data: any[];
  tableheader: string[][];
  fileName: string;
  merges?: merges;
  fixedCol?: number;
  sheetName?: string;
}
export const exportExcel = (payload: exportPayload) => {
  const { data, tableheader, fileName, merges, fixedCol, sheetName } = payload;
  const repeatingData: any = {};
  function computedCol(val: number) {
    const mergesCol = [
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z"
    ];
    const first = Math.floor(val / 26);
    if (first > 0) {
      return `${mergesCol[first - 1]}${mergesCol[val % 26]}`;
    } else {
      return `${mergesCol[val % 26]}`;
    }
  }
  function mergersTable(data: any[], mergeNum: number | number[], move: number) {
    if (typeof mergeNum === "number") {
      mergeRow(data, mergeNum);
    } else {
      if (mergeNum[0] > 0) mergeRow(data, mergeNum[0]);
      if (mergeNum[1] > 0) mergeCol(data, mergeNum[1], move);
    }
  }
  const zm = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "AA",
    "AB",
    "AC",
    "AD",
    "AE",
    "AF",
    "AG",
    "AH",
    "AI",
    "AJ",
    "AK",
    "AL",
    "AM",
    "AI",
    "AN",
    "AO",
    "AP",
    "AQ",
    "AR",
    "AS",
    "AT",
    "AU",
    "AV",
    "AW",
    "AX",
    "AY",
    "AZ",
    "BA",
    "BB",
    "BC",
    "BD",
    "BE",
    "BF",
    "BG",
    "BH",
    "BI",
    "BJ",
    "BK",
    "BL",
    "BM",
    "BN",
    "BO",
    "BP",
    "BQ",
    "BR",
    "BS",
    "BT",
    "BU",
    "BV",
    "BW",
    "BX",
    "BY",
    "BZ",
    "CA",
    "CB",
    "CC",
    "CD",
    "CE",
    "CF",
    "CG",
    "CH",
    "CI",
    "CJ",
    "CK",
    "CL",
    "CM",
    "CN",
    "CO",
    "CP",
    "CQ",
    "CR",
    "CS",
    "CT",
    "CU",
    "CV",
    "CW",
    "CX",
    "CY",
    "CZ",
    "DA",
    "DB",
    "DC",
    "DD",
    "DE",
    "DF",
    "DG",
    "DH",
    "DI",
    "DJ",
    "DK",
    "DL",
    "DM",
    "DN",
    "DO",
    "DP",
    "DQ",
    "DR",
    "DS",
    "DT",
    "DU",
    "DV",
    "DW",
    "DX",
    "DY",
    "DZ",
  ];
  function mergeRow(data: any[], mergeNum: number) {
    for (let i = 0; i < mergeNum; i++) {
      let count = 0;
      data[i].forEach((item: any, index: number) => {
        if (index > 0 && data[i][index - 1] === item) {
          if (repeatingData[`${item}${count}`]) {
            repeatingData[`${item}${count}`][1] += 1;
          } else {
            count += 1;
            repeatingData[`${item}${count}`] = [index - 1, index, i + 1, 0];
          }
        }
      });
    }
  }
  function mergeCol(data: any[], mergeNum: number, move: number) {
    data.forEach((item: any[], index: number) => {
      item.forEach((iten: any, indey: number) => {
        if (index > 0 && indey < mergeNum) {
          if (data[index - 1][indey] === iten) {
            if (repeatingData[iten]) {
              repeatingData[iten][1] += 1;
            } else {
              repeatingData[iten] = [index + move, index + move + 1, indey, 1];
            }
          }
        }
      });
    });
  }
  if (merges) {
    const { header, content } = merges;
    if (header) mergersTable(tableheader, header, 0);
    if (content) mergersTable(data, content, tableheader.length);
  }
  data.unshift(...tableheader);
  const workbook = new Workbook();
  workbook.created = new Date();
    /*const bordersleft = {
    top: { style: "thin" },
    left: { style: "thin" }, // 设置为透明，即不可见
    bottom: { style: "thin" },
    right: { style: "thin" }
  };
  const borders = {
    top: { style: "thin" },
    left: { style: "thin" }, // 设置为透明，即不可见
    bottom: { style: "thin" },
    right: { style: "thin" }
  };*/
  const worksheet = workbook.addWorksheet(sheetName ?? fileName, {
    views: [{ state: "frozen", xSplit: fixedCol,showGridLines:false, ySplit: tableheader.length }]
  });
  worksheet.addRows(data);
  for (let i = 0; i < data.length; i++) {
    worksheet.getRow(i + 1).alignment = { vertical: "middle", horizontal: "center" };
    worksheet.getRow(i + 1).height = 25;
  }
  for (let i = 0; i < data[0].length; i++) {
    worksheet.getColumn(i + 1).width = 20;
  }
  for (let i = 0; i < tableheader.length; i++) {
    worksheet.getRow(i + 1).font = { bold: true, size: 12 };
    worksheet.getRow(i + 1).height = 35;
  }
  for (let i = 1; i <= data.length; i++) {
    worksheet.getCell("A" + i).border = {
      top: { style: "thin" },
      left: { style: "thin" }, // 设置为透明，即不可见
      bottom: { style: "thin" },
      right: { style: "thin" }
    };
    worksheet.getCell("A" + i).font = {bold: true, size: 12}
    worksheet.getCell("B" + i).border = {
      top: { style: "thin" },
      left: { style: "thin" }, // 设置为透明，即不可见
      bottom: { style: "thin" },
      right: { style: "thin" }
    };
    worksheet.getCell("B" + i).font = {bold: true, size: 12}
  }
  const columns = ['A', 'B', 'C', 'D', 'E', 'F'];
  const zmzm =  zm.splice(0,tableheader[0].length + 1);
  console.log(zmzm);
  
  for (let i = 1; i <= data.length; i++) {
    zmzm.forEach(column => {
          worksheet.getCell(column + i).border = {
            top: { style: "thin" },
            left: { style: "thin" }, // 设置为透明，即不可见
            bottom: { style: "thin" },
            right: { style: "thin" }
          };
      
      });
  }
  // if (fixedCol) {
  //   for (let i = 0; i < fixedCol; i++) {
  //     worksheet.getColumn(i + 1).font = { bold: true };
  //     worksheet.getColumn(i + 1).border = {
  //       top: { style: "thick", color: { argb: "000000" } },
  //       left: { style: "thick", color: { argb: "000000" } },
  //       bottom: { style: "thick", color: { argb: "000000" } },
  //       right: { style: "thick", color: { argb: "000000" } }
  //     };
  //   }

  // }
  Object.keys(repeatingData).forEach((key) => {
    const merge = repeatingData[key];
    if (merge[3] === 0) {
      // console.log(`${computedCol(merge[0])}${merge[2]}:${computedCol(merge[1])}${merge[2]}`, merge, key);
      worksheet.mergeCells(`${computedCol(merge[0])}${merge[2]}:${computedCol(merge[1])}${merge[2]}`);
    } else {
      // console.log(`${computedCol(merge[2])}${merge[0]}:${computedCol(merge[2])}${merge[1]}`, merge, key);
      worksheet.mergeCells(`${computedCol(merge[2])}${merge[0]}:${computedCol(merge[2])}${merge[1]}`);
    }
  });
  workbook.xlsx.writeBuffer().then((res) => {
    const blob = new Blob([res]);
    const a = document.createElement("a");
    a.style.display = "none";
    a.download = decodeURI(`${fileName}.xlsx`);
    try {
      a.href = window.URL.createObjectURL(blob);
    } catch (err) {
      console.warn("暂无文件信息.请通知开发人员导入文件模版");
    }
    a.click();
    a.remove();
  });
};
