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
  console.log('auth', auth)
  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) => {
      console.log('e', e)
      const buffer = new OSS.Buffer(e.target && e.target.result)
      console.log('buffer', buffer)
      const key = `collector/${api.ACTIVITY}/huamu_${md5(buffer)}_${filename}`
      console.log('key', key)
      const res = await client.put(key, buffer)
      console.log('res', res)
      resolve(res.url)
    }
  })
}
