const OSS = require("ali-oss");
const fs = require("fs");
const path = require("path");
const { REACT_APP_ENV = "dev" } = process.env;

/**
 * 打包结束后将打包内容上传至对应oss下的bucket
 * 主要逻辑在package.json 在build命令执行后执行自义定的ossUploading 命令
 * 1.步骤为删除当前bucket的全部文件
 * 2.然后再上传
 */

/**重要bucket*/
// let bucket = "zx-web-enterprisewechat-pro";
// 创建 OSS 客户端实例
var client,bucket,fileName

// 删除已有文件
async function deleteAllFiles() {
  try {
    let result;
    // 分页获取所有文件
    do {
      result = await client.list({
        "max-keys": 1000, // 一次最多获取 1000 个文件
      });

      if (result.objects && result.objects.length) {
        const keys = result.objects.map((item) => item.name);
        console.log("Deleting files:", keys);

        // 删除文件
        await client.deleteMulti(keys);
      }
    } while (result.isTruncated); // 如果还有更多文件，继续循环
    console.log(`已删除bucket:${bucket}内的全部文件`);
  } catch (error) {
    console.error(`删除bucket:${bucket}内的全部文件错误:`, error);
  }
}

// 递归上传文件和目录
async function uploadFilesFromDist(dirPath, ossPath) {
  const files = fs.readdirSync(dirPath);

  for (const file of files) {
    const localFilePath = path.join(dirPath, file);
    const ossFilePath = path.join(ossPath, file).replace(/\\/g, "/"); // 替换反斜杠为斜杠以兼容 OSS

    const stats = fs.statSync(localFilePath);

    if (stats.isDirectory()) {
      // 如果是目录，递归上传
      await uploadFilesFromDist(localFilePath, ossFilePath);
    } else {
      // 如果是文件，上传
      console.log(`正在上传: ${localFilePath} 到 ${ossFilePath}`);
      await client.put(ossFilePath, localFilePath);
    }
  }
}

// 主程序
async function postOss(bucket,fileName) {
  if (!bucket) {
    console.log("bucket不存在")
    return;
  }
  bucket = bucket
  fileName =fileName
  client = new OSS({
    region: "oss-cn-hangzhou",
    accessKeyId: "LTAI5tNCVYS4XZmfUmtAZKK9",
    accessKeySecret: "K1gIGmgf4QLY0arIGWxxV9cuchAyOQ",
    bucket,
  });
  await deleteAllFiles();
  const distPath = path.join(__dirname, fileName);
  await uploadFilesFromDist(distPath, ""); // OSS根目录
}
module.exports = { postOss };
