import { getFs } from '../nodejs/fs.mjs';
import { getXlsx } from '../third-party/xlsx.mjs';

function getJsonFromSheet(dataPath) {
  var xlsx = getXlsx();
  var _getFs = getFs(),
    readFileSync = _getFs.readFileSync;
  var excelBuffer = readFileSync(dataPath, {
    encoding: 'utf-8'
  });
  // 解析数据
  var result = xlsx.read(excelBuffer, {
    type: 'binary',
    cellHTML: false
  });
  return xlsx.utils.sheet_to_json(result.Sheets.Sheet1);
}
/**
 * excel 转 json
 * @param {object} params 参数
 * @returns jsonData
 * @example
 *
 * const options = {
 *   header: ['id', 'name', 'age'], // 可选：自定义表头
 *   range: 1,                      // 可选：跳过第一行（标题行）
 *   defval: null,                  // 可选：空单元格的默认值
 *   raw: false,                    // 可选：是否保留原始数据格式
 * };
 *
 * excelToJson({
 *   filePath: CONFIG.xlsxPath,
 *   sheetIndex: 1,
 *   options,
 * });
 *
 * // [
 * //   { id: 1, name: '2', age: '3' },
 * //   { id: 1, name: '2', age: '3' }
 * // ];
 *
 */
function excelToJson(_ref) {
  var filePath = _ref.filePath,
    _ref$sheetIndex = _ref.sheetIndex,
    sheetIndex = _ref$sheetIndex === void 0 ? 0 : _ref$sheetIndex,
    _ref$options = _ref.options,
    options = _ref$options === void 0 ? {} : _ref$options;
  var xlsx = getXlsx();
  // 读取 Excel 文件
  var workbook = xlsx.readFile(filePath);
  // 获取第一个工作表名
  var sheetName = workbook.SheetNames[sheetIndex];
  // 获取工作表
  var worksheet = workbook.Sheets[sheetName];
  // 转换为 JSON
  var jsonData = xlsx.utils.sheet_to_json(worksheet, options);
  return jsonData;
}
/**
 * json 转 excel
 * @param {object} params 参数
 * @example { workbook, worksheet }
 *
 * const jsonData = [
 *   { id: 1, name: '2', age: '3' },
 *   { id: 1, name: '2', age: '3' },
 * ];
 *
 * jsonToExcel({
 *   jsonData,
 *   outputPath: CONFIG.outputFilePath,
 *   options: {
 *     header: ['id', 'name', 'age'],  // 可选：自定义表头顺序
 *     skipHeader: false,              // 可选：是否跳过表头行
 *   },
 *   sheetName: 'addedData',
 * });
 */
function jsonToExcel(_ref2) {
  var jsonData = _ref2.jsonData,
    outputPath = _ref2.outputPath,
    _ref2$options = _ref2.options,
    options = _ref2$options === void 0 ? {} : _ref2$options,
    _ref2$sheetName = _ref2.sheetName,
    sheetName = _ref2$sheetName === void 0 ? 'Sheet1' : _ref2$sheetName,
    _ref2$overwrite = _ref2.overwrite,
    overwrite = _ref2$overwrite === void 0 ? true : _ref2$overwrite;
  var xlsx = getXlsx();
  var fs = getFs();
  var workbook;
  if (fs.existsSync(outputPath)) {
    workbook = xlsx.readFile(outputPath);
  } else {
    workbook = xlsx.utils.book_new();
  }
  // 创建工作表
  var worksheet = xlsx.utils.json_to_sheet(jsonData, options);
  if (workbook.SheetNames.includes(sheetName)) {
    if (overwrite) {
      // 删除现有sheet
      var sheetIndex = workbook.SheetNames.indexOf(sheetName);
      workbook.SheetNames.splice(sheetIndex, 1);
      delete workbook.Sheets[sheetName];
    } else {
      throw new Error("\u5DE5\u4F5C\u8868 \"".concat(sheetName, "\" \u5DF2\u5B58\u5728"));
    }
  }
  xlsx.utils.book_append_sheet(workbook, worksheet, sheetName);
  // 写入文件
  xlsx.writeFile(workbook, outputPath, {
    bookType: 'xlsx',
    type: 'file' // 输出类型
  });
  return {
    workbook: workbook,
    worksheet: worksheet
  };
}

export { excelToJson, getJsonFromSheet, jsonToExcel };
