
let fs = require('fs')
let path = require('path')
let OSS = require('ali-oss')

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

let DIR_PATH = path.join(__dirname, '../client-dist')
let PREFIX_PATH = 'static/build/learn-enterprise/'

let count = 1
async function uploadFile (prefixPath, dirFileName) {
  try {
    let result = await client.put(prefixPath + path.basename(dirFileName), dirFileName)
    if (result.res.status === 200) {
      console.log('第' + (count++) + '个文件：' + path.basename(dirFileName) + '，已上传。')
    }
  } catch (err) {
    console.log(err)
    let text = await function () { return 1 }
    console.log(text)
  }
}

function findfiles (dirPath, callback) {
  fs.readdir(dirPath, function (err, files) {
    if (err) {
      console.log(err)
    } else {
      files.forEach(function (filename) {
        var filedir = path.join(dirPath, filename)
        fs.stat(filedir, function (error, stats) {
          if (error) {
            console.log('获取文件stats失败')
          } else {
            var isFile = stats.isFile()
            var isDir = stats.isDirectory()
            if (isFile && typeof callback === 'function') {
              callback(filedir)
            }
            if (isDir && filename !== 'static') {
              var morePath = filedir.replace(new RegExp(DIR_PATH + '/', 'g'), '') + '/'
              findfiles(filedir, function (filedir) {
                uploadFile(PREFIX_PATH + morePath, filedir)
              })
            }
          }
        })
      })
    }
  })
}

findfiles(DIR_PATH, function (filedir) {
  uploadFile(PREFIX_PATH, filedir)
})
