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

export async function upload(blob: Blob | File) {
  let fileType = 'png'
  if (blob instanceof File && blob.name) {
    const matches = blob.name.match(/\.(\w+)$/)
    if (matches) {
      fileType = matches[1]
    }
  } else if (blob.type) {
    const mimeType = blob.type.split('/').pop()
    if (mimeType) {
      fileType = mimeType
    }
  }
  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)
}
