import OSS from 'ali-oss'
import { useFetchAuth } from '@/hooks/useFetch'
import md5 from 'md5'
import { api } from '@/ajax'

export default async function useAliOss(file: any) {
  const auth = (await useFetchAuth())?.token
  const client = new OSS({
    region: auth.region,
    accessKeyId: auth.access_key_id,
    accessKeySecret: auth.access_key_secret,
    bucket: auth.bucket,
    stsToken: auth.security_token,
  })
  const fr = new FileReader()
  const filename = file.name

  return new Promise((resolve: any) => {
    fr.readAsArrayBuffer(file)
    fr.onload = async (e) => {
      const buffer = new OSS.Buffer(e.target && e.target.result)
      const key = `collector/${api.ACTIVITY}/huamu_${md5(buffer)}_${filename}`
      const res = await client.put(key, buffer)
      resolve(res.url)
    }
  })
}
