let fs = require("fs"); // node , fs 文件流控制
let path = require("path"); // node 什么方法忘了，路径方法
let OSS = require("ali-oss"); // oss 引入

const dirBasePath = path.join(process.cwd(), "/dist/1.0.0"); // 路径引导
const { COMPILE_ENV = "staging" } = process.env; // 获取环境变量，node版本失效，可饮用env作为判断，也可以手动执行修改
let bucket = "customer-vue-test"; // 对应oss文件，默认为预发环境

let accessKeyId = "LTAI5tAhrEnqLFtnWPwZbDue",
  accessKeySecret = "z3S6J1yrc4JoGtkMJkb75oTUsCxdOD";

  console.log(process.env.COMPILE_ENV,'++++++++++')

if (COMPILE_ENV === "prod") {
  bucket = "customer-vue";
} else if (COMPILE_ENV === "dr") {
  bucket = "mmyx-h5-gray";
  accessKeyId = "";
  accessKeySecret = "";
} else if (COMPILE_ENV === "staging") {
  bucket = "customer-vue-test";
}

// oss 账号密码，地址
let client = new OSS({
  region: "oss-cn-hangzhou",
  bucket,
  accessKeyId,
  accessKeySecret,
});

// 上传的方法
// node 日志进度输入
async function put(file, filePath) {
  try {
    let r1 = await client.put(file, filePath);
    console.log("当前进度: %j", r1);
  } catch (e) {
    console.error("上传文件报错", e);
  }
}

// 遍历本地上传的目录文件夹
// node本地文件遍历，fs文档流控制
const fileList = [];

function listFile(dir) {
  let arr = fs.readdirSync(dir);
  arr.forEach(function(item) {
    const o = {};

    let fullPath = path.join(dir, item);
    let stats = fs.statSync(fullPath);
    if (stats.isDirectory()) {
      listFile(fullPath);
    } else {
      const fileDir = fullPath.replace(`${dirBasePath}/`, "");

      console.log(fileDir + "处理后的内容");

      o.file = fileDir;
      o.filePath = fullPath;

      fileList.push(o);
    }
  });

  return fileList;
}

listFile(dirBasePath).forEach(function(item) {
  const { file, filePath } = item;
  put(file, filePath);
});
