import BaseAPI from '@/api/base_api'
import md5 from 'blueimp-md5'

const httpRequest = new BaseAPI(webConf)

/**
 * 上传文件
 */
// export function uploadFile(data) {
//   return httpRequest.post('/api/lms/util/upload-file', data, {
//     headers: { 'Content-Type': 'multipart/form-data' }
//   })
// }

// 获取oss signature
export function getSignature() {
  return httpRequest.get('/api/usercenter/aliyun/get-signature')
}

// 图片上传
export function uploadAliOSS(data) {
  return httpRequest.post('https://webapp-pub.oss-cn-beijing.aliyuncs.com', data, {
    withCredentials: false,
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

export async function uploadFile({ file }) {
  const prefix = 'upload/lms/'
  const key = prefix + md5(file.name + Date.now()) + file.name.substr(file.name.lastIndexOf('.'))
  const response = await getSignature()
  const params = {
    key,
    OSSAccessKeyId: response.accessid,
    policy: response.policy,
    signature: response.signature,
    success_action_status: '200',
    file,
    url: `${response.host}/${key}`
  }
  await uploadAliOSS(params)
  return { error: '', success: true, url: params.url }
}
