
import OSS from 'ali-oss'
import request from '@/utils/request'
import { uuid } from '@/utils'

/**
 * 随机创建文件名称.
 */
const radmonFilename = (filename) => {
  const suffix = filename ? filename.substring(filename.lastIndexOf('.')) : ''
  return `manager-${uuid()}${suffix}`
}

/**
 * 获取url.
 */
const getAccessImgUrl = (key) => {
  if (!key) {
    return ''
  }
  if (key.startsWith('/')) {
    return `${process.env.VUE_APP_OSS_URL}${key}`
  }
  return `${process.env.VUE_APP_OSS_URL}/${key}`
}

/**
 * 简单上传
 * @param {*} fileObj 文件对象
 */
const simpleUploadFlie = (fileObj, dir) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/ali-yun/oss/sts',
      method: 'get'
    }).then(res => {
      const stsResult = res.body
      if (stsResult) {
        const client = new OSS({
          endpoint: 'oss-accelerate.aliyuncs.com',
          accessKeyId: stsResult['AccessKeyId'],
          accessKeySecret: stsResult['AccessKeySecret'],
          stsToken: stsResult['SecurityToken'],
          bucket: process.env.VUE_APP_OSS_BUCKET
        })
        try {
          const filename = fileObj.customFilename || radmonFilename(fileObj.file.name)
          client.put(`${dir || 'other'}/${filename}`, fileObj.file).then(ossRes => {
            resolve(ossRes)
          }).catch(er => {
            console.error('error:', er)
            reject(er)
          })
        } catch (er) {
          console.error('error:', er)
          reject(er)
        }
      }
    }).catch(er => {
      console.error(er)
      reject(er)
    })
  })
}

export {
  radmonFilename,
  simpleUploadFlie,
  getAccessImgUrl
}
