import axios from 'axios'
import md5 from 'blueimp-md5'
import { getSignature, uploadFile } from '@/api/base'

export async function upload(blob: Blob) {
  const fileType = blob.type.split('/').pop() || 'png'
  const key = 'upload/saas-lab/' + md5(new Date().getTime() + Math.random().toString(36).slice(-8)) + '.' + fileType
  const response: any = await getSignature()
  const params = {
    key,
    host: response.host,
    OSSAccessKeyId: response.accessid,
    policy: response.policy,
    signature: response.signature,
    success_action_status: '200',
    file: blob,
    url: `${response.host}/${key}`,
  }
  await uploadFile(params)
  return params.url
}

export async function uploadFileByUrl(url: string) {
  const res = await axios.get(url, { responseType: 'blob' })
  return upload(res.data)
}
