import * as XLSX from "xlsx";

/**
 * 解析Excel文件
 * @param file
 * @returns
 */
export const parseExcel = <T>(file: any): Promise<Record<string, T>> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = e.target?.result;
      const workbook = XLSX.read(data, { type: "binary" });
      const result: Record<string, any> = {};
      // 处理sheet并转换sheet数据 第一行为key 后面数据为value
      workbook.SheetNames.forEach((sheetName) => {
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        if (jsonData.length === 0) {
          result[sheetName] = jsonData;
        } else {
          const keys = jsonData[0] as string[];
          const list = [];
          for (let i = 1; i < jsonData.length; i++) {
            const row = jsonData[i] as any[];
            if(row.length === 0) {
              continue;
            }
            const obj: Record<string, any> = {};
            for (let j = 0; j < keys.length; j++) {
              obj[keys[j]] = row[j];
            }
            list.push(obj);
          }
          result[sheetName] = list;
        }
      });

      resolve(result);
    };

    reader.onerror = (e) => {
      reject(e);
    };

    reader.readAsArrayBuffer(new Blob([file], { type: file.type }));
  });
};
