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

export const prefix = 'upload/saas-dml-live/'

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 function generateObjectName(file: Blob | File, objectName?: string) {
  if (objectName) return `${prefix}${objectName}`
  let fileType = 'png'
  if (file instanceof File && file.name) {
    const matches = file.name.match(/\.(\w+)$/)
    if (matches) {
      fileType = matches[1]
    }
  } else if (file.type) {
    const mimeType = file.type.split('/').pop()
    if (mimeType) {
      fileType = mimeType
    }
  }
  return `${prefix}${md5(new Date().getTime() + Math.random().toString(36).slice(-8))}.${fileType}`
}

// 上传
export async function putUpload(file: Blob | File, objectName?: string) {
  const store = await createStore()
  return store.put(generateObjectName(file, objectName), file)
}

// 追加上传
export async function appendUpload(file: Blob | File, position = '', objectName?: string) {
  const store = await createStore()
  let options = {}
  if (position) options = { position }
  return store.append(generateObjectName(file, objectName), file, options)
}
