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

export default async function useAliOss(file: any) {
  const auth = (await useFetchOSSToken())?.token
  const client = new OSS({
    region: 'oss-' + 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) => {
    fr.readAsArrayBuffer(file)
    fr.onload = async (e) => {
      const buffer = new OSS.Buffer(e.target && e.target.result)
      const key = `collector/${api.ATTACHMENT}/huamu_${md5(buffer)}_${filename}`
      const res = await client.put(key, buffer)
      resolve(res.url)
    }
  })
}
