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 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)
    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)
