import request from '@/router/axios'

const OSS = require('ali-oss')

let OSSObj = {
  client: undefined
}

const headers = {
  "x-oss-forbid-overwrite": "true",
};

export const Uploader = {

  getOSS() {
    if (OSSObj.client == undefined) {
      return request({
        url: '/admin/systemSet/getOSSAuth',
        method: 'get'
      }).then(r => {
        if (r.data && r.data.code == 0) {
          return r.data.data || true
        } else {
          return Promise.reject("获取OSS客户端失败")
        }
      }).then(auth => {
        let oss = new OSS({
          region: auth.region,
          accessKeyId: auth.accessKeyId,
          accessKeySecret: auth.accessKeySecret,
          bucket: auth.bucket,
          refreshSTSTokenInterval: 3600,
          stsToken: auth.securityToken,
          refreshSTSToken: () => {
            return request({
              url: '/admin/systemSet/getOSSAuth',
              method: 'get'
            }).then(r => {
              if (r.data && r.data.code == 0) {
                let d = r.data.data
                return {
                  accessKeyId: d.accessKeyId,
                  accessKeySecret: d.accessKeySecret,
                  stsToken: d.securityToken
                }
              } else {
                return Promise.reject("获取OSS客户端失败")
              }
            })
          }
        })
        OSSObj.client = oss
        return Promise.resolve(oss)
      })
    }
    return Promise.resolve(OSSObj.client)
  },

  upload(dir, file) {
    if (dir == undefined || dir == '') {
      return Promise.reject("上传文件夹不能为空")
    }
    if (file == undefined) {
      return Promise.reject("文件不能为空")
    }
    return this.getOSS().then(oss => {
      return oss.put(dir + '/' + file.name, file, {headers})
    })
  }

}
