const fs = require('fs')
const path = require('path')

const OSS = require('ali-oss')

const conf = require('./config')

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

const headers = {
  'x-oss-traffic-limit': 8 * 1024 * 100 * 100 // 设置限速，最小100KB/s。设置为 10000KB/s
}

const DIR_PATH = path.join(__dirname, '../' + conf.DesDir)
const PREFIX_PATH = conf.CDN_DIR
const isUploadStatic = conf.isUploadStatic

let fileCount = 1
async function uploadFile(prefixPath, dirFileName) {
  const upFilePath = prefixPath.replace(new RegExp(DIR_PATH, 'gi'), '') + path.basename(dirFileName)
  try {
    // const result = await client.put(prefixPath + path.basename(dirFileName), dirFileName)
    let result = await client.put(prefixPath + path.basename(dirFileName), dirFileName, {
      headers,
      timeout: 600000 // 默认超时时长为60000ms。超时直接报错，限速上传时注意修改超时时长。设置为600s
    })
    if (result.res.status === 200) {
      console.log('第' + fileCount++ + '个文件，已上传：' + conf.CDN_BASE + upFilePath)
      return { status: 200 }
    }
  } catch (err) {
    console.log('第' + fileCount++ + '个文件，上传失败：' + conf.CDN_BASE + upFilePath)
    return { status: 500, err: err }
  }
}

function uploadfiles(dirPath, callback) {
  const files = fs.readdirSync(dirPath)
  files.forEach(function(filename, i) {
    const filedir = path.join(dirPath, filename)
    const info = fs.statSync(filedir)
    if (info.isDirectory()) {
      if (!(isUploadStatic ? true : filename !== 'static')) {
        return
      }
      const morePath = filedir.replace(new RegExp(DIR_PATH, 'gi'), '') + '/'
      uploadfiles(filedir, function(filedir) {
        uploadFile(path.join(PREFIX_PATH, morePath), filedir)
      })
    } else {
      if (typeof callback === 'function') {
        callback(filedir)
      } else {
        uploadFile(PREFIX_PATH, filedir)
      }
    }
  })
  return true
}

uploadfiles(DIR_PATH, null)
