import { fileUpload, getSignature } from '@/api/system'
import md5 from 'blueimp-md5'

export default function(blobInfo, succFun, failFun) {
  const file = blobInfo.blob()
  const fileName = file.name
  const key = 'upload/cms-admin/' + md5(fileName + new Date().getTime()) + fileName.substr(fileName.lastIndexOf('.'))
  getSignature()
    .then(response => {
      const { accessid, policy, signature, host } = response
      const data = { key, OSSAccessKeyId: accessid, policy, signature, success_action_status: '200' }
      const fileUrl = `${host}/${key}`
      const formData = new window.FormData()
      formData.append('key', data.key)
      formData.append('OSSAccessKeyId', data.OSSAccessKeyId)
      formData.append('policy', data.policy)
      formData.append('signature', data.signature)
      formData.append('success_action_status', '200')
      formData.append('file', file)
      fileUpload(formData).then(res => {
        succFun(fileUrl)
      }).catch((err) =>
        failFun(err.message || '上传出错了')
      )
    })
    .catch(err => {
      console(err)
    })
}
