import { read, utils, write } from 'xlsx';

// 静态资源路径
const baseUrl = import.meta.env.VITE_HISTORY_BASE_URL;
export const xlsxUrl = `${
  baseUrl.length === 1 && baseUrl.indexOf('/') === 0
    ? ''
    : baseUrl.indexOf('/') === -1
    ? '/' + baseUrl
    : baseUrl
}/alarmHelp`;

/**
 * 读取本地文件
 * @param id 表格ID
 * @returns 数据数组
 * @example
 * readLoalXlsx('20001').then(res=>{
 *   console.log(res)
 * });
 */
export async function readLoalXlsx(id: string): Promise<Record<string, any>[]> {
  let fileBolb = await (await fetch(`${xlsxUrl}/${id}.xlsx`)).arrayBuffer();
  if (!fileBolb.byteLength) {
    fileBolb = await (await fetch(`${xlsxUrl}/all.xlsx`)).arrayBuffer();
  }
  return readSheet(fileBolb, 0);
}

/**
 * 读取表格数据 工作表
 * @param fileBolb 文件对象
 * @param index 文件保存路径
 * @return 表格对象列表
 */
export async function readSheet(
  fileBolb: Blob | ArrayBuffer,
  index: number = 0
): Promise<Record<string, string>[]> {
  const workBook = read(fileBolb);
  let workSheet = workBook.Sheets[workBook.SheetNames[index]];
  return utils.sheet_to_json<Record<string, string>>(workSheet);
}

/**
 * 写入表格数据，一般用于导出
 * @param filePath 文件路径
 * @param sheetName 工作表名称
 * @return xlsx文件流， 使用saveAs函数保存
 * @example
 * writeSheet(res.data, from.logType).then(fileBlob =>
 *   saveAs(fileBlob, `${from.logType}_${Date.now()}.xlsx`)
 * );
 *
 */
export async function writeSheet(data: any[], sheetName: string) {
  if (data.length === 0) {
    return new Blob([], { type: 'application/octet-stream' });
  }
  const workSheet = utils.json_to_sheet(data);
  // 设置列宽度，单位厘米
  workSheet['!cols'] = Object.keys(data[0]).map(() => {
    return { wch: 20 };
  });
  const workBook = utils.book_new();
  utils.book_append_sheet(workBook, workSheet, sheetName);
  const excelBuffer = write(workBook, { type: 'array', bookType: 'xlsx' });
  return new Blob([excelBuffer], { type: 'application/octet-stream' });
}
