/**
 * build成功后的运行逻辑
 */
const path = require("path");
const fs = require("fs");
const oss = require("ali-oss");
const { execSync } = require("child_process");
class saveOssGitte {
  constructor() {
    this.localDir = "dist/";
    this.baseOssDir = "operate/products/";
    this.client = new oss({
      region: "oss-cn-chengdu",
      // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
      accessKeyId: "LTAI4GEBqfF1GX4VwsYU2Wpg",
      accessKeySecret: "rVIv0E1lRfXOCrAmkFTZnfgWiuv4ea",
      bucket: "smcic-index",
    });
    // this.execFun();
    this.delDir();
  }

  /**
   * 上传git
   */
  execFun() {
    try {
      execSync("git add .");
      execSync(`git commit -m "${process.argv[2] || "提交"}"`);
      execSync("git push -u origin master");
      //   execSync("git push -u github master");
      console.log("上传git---完成");
    } catch (e) {
      console.log("上传git---失败");
      console.error(e);
    }
  }

  /**
   * 获得上传目录下的所有文件路径
   * 删除oss指定路径下文件
   */
  async delDir() {
    let list = await this.client.list({
      prefix: this.baseOssDir,
    });
    (list.objects || []).splice(0, 1);
    //   删除文件
    await Promise.all(
      list.objects.map(async v => {
        try {
          await this.client.delete(v.name);
        } catch (error) {
          error.failObjectName = v.name;
          return error;
        }
      })
    );
    console.log("oss文件清除---完成");
    try {
      console.log(path.resolve(__dirname, "./" + this.localDir))
      await this.getFiles(path.resolve(__dirname, "./" + this.localDir));
      console.log("数据上传oss---完成");
    } catch (err) {
      console.log(err)
      console.log("数据上传oss---失败");
    }
  }
  /**
   * 获取localDir下的所有文件路径
   * @param {string} pathDir
   */
  async getFiles(pathDir) {
    const dirList = fs.readdirSync(pathDir) || [];
    for (let i = 0; i < dirList.length; i++) {
      const P = [pathDir, dirList[i]];
      const stat = fs.lstatSync(P.join("/"));
      if (!stat.isDirectory()) {
        console.log(P)
        await this.upFileOSS(P);
      } else this.getFiles(P.join("/"));
    }
  }

  /**
   * 上传文件到oss
   * @param {string} filePath
   */
  async upFileOSS(filePath) {
    try {
      // 填写OSS文件完整路径和本地文件的完整路径。OSS文件完整路径中不能包含Bucket名称。
      // 如果本地文件的完整路径中未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
      let dir = filePath[0].split("/");
      dir = dir.reverse()[0] + "/";
      if (dir === this.localDir) dir = "";
      await this.client.put(
        this.baseOssDir + dir + filePath[1],
        path.normalize(filePath.join("/"))
        // 自定义headers
        //,{headers}
      );
    } catch (e) {
      console.error("未成功上传：", filePath.join("\\"));
      console.log("err--->", e);
    }
  }
}

new saveOssGitte();
