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

// 生产环境线上部署
export async function ossUpload(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/resource-center/' + 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 localUpload(file: Blob | File) {
  const fileName = file instanceof File && file.name ? file.name : `upload.${file.type.split('/').pop() || 'bin'}`
  const response = await getLocalFileChunk({ file_name: fileName, file_size: file.size })
  const params = {
    file,
    file_name: response.data.detail.file_name,
    now_package_num: 1,
    total_package_num: 1,
  }
  const res = await uploadLocalFile(params)

  return res.data.detail.uri
}

export async function upload(blob: Blob | File) {
  return import.meta.env.MODE === 'school' ? localUpload(blob) : ossUpload(blob)
}

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