import request from "../utils/request"
import COS from "cos-js-sdk-v5"

const tencentBucket = "daya-online-1303457149"
const ossType = "tencent"

export async function fileUpload(fileName:string,file:Blob) {
   const { data } = await getUploadSign(fileName)
   return await onOnlyFileUpload(data.signature, {
      fileName,
      file
   })
}

const getUploadSign = async (fileName:string) => {
   const fileUrl = "yjl/" + fileName
   return request.post("/getUploadSign", {
      data: {
         postData: {
            key: fileUrl
         },
         pluginName: ossType,
         bucketName: tencentBucket,
         filename: fileUrl
      },
      requestType: "json",
      params: { pluginName: ossType }
   })
}

const onOnlyFileUpload = async (signature: string, params: { fileName: string; file: Blob }) => {
   let file = ""
   let errorObj: any = null
   const cos = new COS({
      Domain: "https://oss.dayaedu.com",
      Protocol: "https",
      getAuthorization: async (options, callback: any) => {
         callback({ Authorization: signature })
      }
   })
   await cos
      .uploadFile({
         Bucket: tencentBucket /* 填写自己的 bucket，必须字段 */,
         Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
         Key: `yjl/${params.fileName}`,
         /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
         Body: params.file, // 上传文件对象
         SliceSize: 1024 * 1024 * 500 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
         onProgress: function (progressData) {
            // onProgress({ percent: Math.ceil((progressData.percent || 0) * 100) })
         }
      })
      .then((res: any) => {
         if (res.Location?.indexOf("http") >= 0) {
            file = res.Location
         } else {
            file = "https://" + res.Location
         }
      })
      .catch((error: any) => {
         errorObj = error
      })
   if (file) {
      return file
   } else {
      throw new Error(errorObj)
   }
}
