import OSS from 'ali-oss'
import md5 from 'blueimp-md5'
import { fileTypeFromBlob } from 'file-type'
import { getToken } from '@/api/base'

let store: OSS | null = null

export async function getTokenInfo() {
  const response: any = await getToken()
  return {
    accessKeyId: response.Credentials.AccessKeyId,
    accessKeySecret: response.Credentials.AccessKeySecret,
    stsToken: response.Credentials.SecurityToken,
  }
}

export async function createStore() {
  if (store) return store
  const response = await getTokenInfo()
  return (store = new OSS({
    bucket: 'webapp-pub',
    region: 'oss-cn-beijing',
    accessKeyId: response.accessKeyId,
    accessKeySecret: response.accessKeySecret,
    stsToken: response.stsToken,
    refreshSTSToken: () => getTokenInfo(),
    cname: true,
    endpoint: 'https://webapp-pub.ezijing.com',
  }))
}

export async function parseParams(file: Blob | File, options: any = {}) {
  const { name, prefix = 'upload/saas-dml-pro/', ...rest } = options
  let objectName: string
  if (name) {
    objectName = `${prefix}${name}`
  } else {
    const result = await fileTypeFromBlob(file)
    objectName = `${prefix}${md5(new Date().getTime() + Math.random().toString(36).slice(-8))}.${result?.ext}`
  }
  return { name: objectName, file, options: rest }
}

// 上传
export async function putUpload(file: Blob | File, options?: any) {
  const store = await createStore()
  const params = await parseParams(file, options)
  return store.put(params.name, params.file, params.options)
}

// 追加上传
export async function appendUpload(file: Blob | File, options?: any) {
  const store = await createStore()
  const params = await parseParams(file, options)
  return store.append(params.name, params.file, params.options)
}

export async function multipartUpload(file: Blob | File, options?: any) {
  const store = await createStore()
  const params = await parseParams(file, options)
  const res: any = await store.multipartUpload(params.name, params.file, params.options)
  return { url: `https://webapp-pub.ezijing.com/${res.name}`, ...res }
}
