import COS from "cos-js-sdk-v5"
import { getUploadSignApi } from "@/api/user"
import { httpAjax } from "@/plugins/httpAjax"
import loadingBar from "@/plugins/loadingBar"

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

export default async function fileUpload(
  fileName: string,
  file: Blob,
  filePath: string,
  isAddTimestamp = true,
  loadingBarOpt?: { isLoading: boolean; text?: string }
) {
  loadingBarOpt || (loadingBarOpt = { isLoading: true })
  loadingBarOpt.isLoading && loadingBar.loading(true, loadingBarOpt.text || "资源上传中")
  // 上传名称加上时间戳
  if (isAddTimestamp) {
    fileName = addTimestampBeforeExtension(fileName)
  }
  const resUploadSign = await getUploadSign(fileName, filePath)
  if (resUploadSign.code === 200) {
    try {
      const resUpload = await onOnlyFileUpload(resUploadSign.data.signature, {
        fileName,
        file,
        filePath
      })
      loadingBarOpt.isLoading && loadingBar.loading(false)
      if (resUpload.statusCode === 200) {
        return resUpload.Location.includes("http") ? resUpload.Location : `https://${resUpload.Location}`
      } else {
        return Promise.reject("")
      }
    } catch {
      loadingBarOpt.isLoading && loadingBar.loading(false)
      return Promise.reject("")
    }
  } else {
    loadingBarOpt.isLoading && loadingBar.loading(false)
    return Promise.reject("")
  }
}

const getUploadSign = async (fileName: string, filePath: string) => {
  const fileUrl = `pptList/${filePath || "errPath/"}` + fileName
  return httpAjax(
    getUploadSignApi,
    {
      postData: {
        key: fileUrl
      },
      pluginName: ossType,
      bucketName: tencentBucket,
      filename: fileUrl
    },
    { pluginName: ossType }
  )
}

const onOnlyFileUpload = (signature: string, params: { fileName: string; file: Blob; filePath: string }) => {
  const cos = new COS({
    Domain: "https://oss.dayaedu.com",
    Protocol: "https",
    getAuthorization: async (options, callback: any) => {
      callback({ Authorization: signature })
    }
  })
  return cos.uploadFile({
    Bucket: tencentBucket /* 填写自己的 bucket，必须字段 */,
    Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
    Key: `pptList/${params.filePath || "errPath/"}${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) })
    }
  })
}

function addTimestampBeforeExtension(filename: string) {
  const dotIndex = filename.lastIndexOf(".")
  const name = filename.substring(0, dotIndex)
  const extension = filename.substring(dotIndex)
  return `${name}_${Date.now()}${extension}`
}
