const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const OSS = require('ali-oss')

const log = console.log

const client = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAIOTuuLTaWoGJj',
  accessKeySecret: 'dE5tTGm2lh35eItct2krW2DeH2lf2I',
  bucket: 'webapp-pub'
})

async function uploadTarget(src, dist) {
  try {
    const result = await client.put(dist, path.join(__dirname, src))
    log(chalk.green('上传成功', result.url))
  } catch (e) {
    log(chalk.red('上传失败', src))
    log(e)
  }
}

function generateUploadTarget(src, dist) {
  fs.readdir(path.join(__dirname, src), function (err, files) {
    if (err) {
      log(err)
      return
    }
    files.forEach(function (file) {
      const _src = src + '/' + file
      const _dist = dist + '/' + file
      const stats = fs.statSync(path.join(__dirname, _src))
      // 判断是否为文件
      stats.isFile() && uploadTarget(_src, _dist)
      // 判断是否为文件夹
      stats.isDirectory() && generateUploadTarget(_src, _dist)
    })
  })
}

generateUploadTarget('../dist', '/website/prod/x-training')
