import XLSX2 from "xlsx";
import XLSX from "xlsx-style";
const workbook2blob = (workbook) => {
  // 生成excel的配置项
  let wopts = {
    // 要生成的文件类型
    bookType: "xlsx",
    // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    bookSST: false,
    type: "binary"
  };
  let wbout = XLSX.write(workbook, wopts);
  // 将字符串转ArrayBuffer
  function s2ab(s) {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
  let buf = s2ab(wbout);
  let blob = new Blob([buf], {
    type: "application/octet-stream"
  });
  return blob;
};
// 将blob对象 创建bloburl,然后用a标签实现弹出下载框
const openDownloadDialog = (blob, fileName) => {
  if (typeof blob === "object" && blob instanceof Blob) {
    blob = URL.createObjectURL(blob); // 创建blob地址
  }
  let aLink = document.createElement("a");
  aLink.href = blob;
  // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
  aLink.download = fileName || "";
  let event;
  if (window.MouseEvent) event = new MouseEvent("click");
  //   移动端
  else {
    event = document.createEvent("MouseEvents");
    event.initMouseEvent(
      "click",
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    );
  }
  aLink.dispatchEvent(event);
};
// 列自适应宽度
const setColFitWidth = (tableData, headerList, sheet) => {
  function getCellWidth(value) {
    // 判断是否为null或undefined
    if (!value) {
      return 10;
    } else if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
      // 判断是否包含中文
      return value.toString().length * 2.1;
    } else {
      return value.toString().length * 1.1;
    }
  }
  let colWidths = []; // 所有列的名称数组
  // 计算每一列的所有单元格宽度
  // 先遍历行
  tableData.forEach((row) => {
    // 遍历列
    for (const key in row) {
      let index = headerList.findIndex((v) => v === key);
      if (!colWidths[index]) {
        colWidths[index] = [];
      }
      colWidths[index].push(getCellWidth(row[key]));
    }
  });
  sheet["!cols"] = [];
  // 每一列取最大值最为列宽
  colWidths.forEach((widths, index) => {
    // 计算列头的宽度
    widths.push(getCellWidth(headerList[index]));
    // 设置最大值为列宽
    sheet["!cols"].push({ wch: Math.max(...widths, 10) });
  });
  return sheet;
};
/**
 * 导出Excel表格
 * @param sheetListInfo sheet列表信息 [{list:数组数据, name: sheet名称}]
 * @param excelName Excel表格名称
 */
export const exportToExcel = (sheetListInfo, excelName) => {
  const wb = XLSX2.utils.book_new();
  sheetListInfo.forEach((sheetItem, sheetIndex) => {
    let headerList = [];
    sheetItem.list.forEach((item) => {
      for (const key in item) {
        headerList.push(key);
        item[key] = item[key] || "";
      }
    });
    let sheet = XLSX2.utils.json_to_sheet(sheetItem.list);
    // 设置每个单元格的样式
    let range = XLSX.utils.decode_range(sheet["!ref"]);
    for (let R = range.s.r; R <= range.e.r; ++R) {
      for (let C = range.s.c; C <= range.e.c; ++C) {
        let cell_ref = XLSX.utils.encode_cell({ r: R, c: C });
        let cell = sheet[cell_ref];
        if (cell) {
          if (!cell.s) cell.s = {};
          cell.s.alignment = { horizontal: "center", vertical: "middle" };
        }
      }
    }
    sheet = setColFitWidth(sheetItem.list, headerList, sheet);
    XLSX2.utils.book_append_sheet(
      wb,
      sheet,
      sheetItem.name || `sheet${sheetIndex + 1}`
    );
  });
  const workbookBlob = workbook2blob(wb);
  // 导出最后的总表
  openDownloadDialog(workbookBlob, excelName + ".xlsx");
};
