const XLSX = require("xlsx");
const fs = require("fs");
const path = require("path");
const { json } = require("stream/consumers");
const { log } = require("console");
const folderPath = "./configs";
const scope = [
  "SpecialRingConfig",
  // "StdItems",
  // "Monster",
  // "ItemMergeConfig",
  // "MergeConfig",
  // "NpcTransConf"
  //  "MergeTotal", "RecyclingSettingConfig", "UpstarConfig",
].filter(Boolean);

function handleJson2ArrayJson(jsonData) {
  const arr = [];
  const findElement = (obj) => {
    for (const key in obj) {
      if (isNaN(key) && Object.hasOwnProperty.call(obj, key)) {
        if(typeof obj[key] === "object")
            obj[key] = JSON.stringify(obj[key]);
      } else if (typeof obj[key] === "object") {
        findElement(obj[key]);
      }
    }
    arr.push(obj);
  };
  findElement(jsonData);
  return arr;
}
function json2excel(jsonData, fileName) {
  if (!Array.isArray(jsonData)) jsonData = Object.values(jsonData);
  const data = handleJson2ArrayJson(jsonData)?.filter(Boolean);
  
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(data);
  XLSX.utils.book_append_sheet(workbook, worksheet, fileName);
  XLSX.writeFile(workbook, `./excels/${fileName}.xlsx`);
}

const start = () => {
  const files = fs.readdirSync(folderPath);

  // 过滤出所有的 JSON 文件
  const jsonFiles = files.filter((file) => path.extname(file) === ".json").filter((file) => scope.map((e) => `${e}.json`).includes(file));
  jsonFiles.forEach((file) => {
    const json = JSON.parse(fs.readFileSync(path.join(folderPath, file), "utf8"));
    const filename = path.basename(file, path.extname(file));
    json2excel(json, filename);
  });
};
start();
