import COS from "cos-js-sdk-v5"
import { getTmpSecretKey } from "@/api/common"


const config = {
  Bucket: process.env.VUE_APP_COS_BUCKET,
  Region: process.env.VUE_APP_COS_REGION,
}

export const uploadObject = async (file, onProgress, type, callBackUp) => {
  try {
    const response = await getTmpSecretKey()
    const data = response.data
    const credentials = data && data.credentials

    if (!data || !credentials) {
      console.error("未获取到参数")
      return
    }

    const cos = new COS({
      Timeout: 1200 * 1000,
      getAuthorization: (options, callback) => {
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          XCosSecurityToken: credentials.sessionToken,
          StartTime: data.startTime,
          ExpiredTime: data.expiredTime,
        })
      },
    })

    const fileName = file.name || ""
    const upload_file_name = new Date().getTime() + "." + fileName.split(".")[fileName.split(".").length - 1]
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const strDate = date.getDate()
    const uploadDay = `${year}${month}${strDate}`
    const videoKey = `/userVideo/${uploadDay}/${upload_file_name}`
    const courseKey = `/course/${uploadDay}/${upload_file_name}`
    let liveKey;
// 检查是否是空字符串或只有空格
    if (process.env.VUE_APP_LIVE_PATH && process.env.VUE_APP_LIVE_PATH.trim() !== '') {
      liveKey = `${process.env.VUE_APP_LIVE_PATH.trim()}/${uploadDay}/${upload_file_name}`;
    } else {
      liveKey = `/course/${uploadDay}/${upload_file_name}`;
    }

    const key = type === 3 ? liveKey : (type === 1 ? courseKey : videoKey);



    return new Promise((resolve, reject) => {
      let taskId = null

      const uploadTask = cos.uploadFile(
        {
          Bucket: config.Bucket,
          Region: config.Region,
          Key: key,
          StorageClass: "STANDARD",
          Body: file,
          onTaskReady: (id) => {
            taskId = id
            if (callBackUp) {
              callBackUp({
                cos,
                taskId,
                cancel: () => {
                  cos.cancelTask(taskId)
                  reject(new Error("Upload cancelled by user"))
                },
              })
            }
          },
          onProgress: (progressData) => {
            onProgress(progressData)
          },
        },
        (err, data) => {
          if (err) {
            reject(err)
          } else {
            const result = {
              ...data,
              urlPath: key,
            }
            resolve(result)
          }
        },
      )
    })
  } catch (error) {
    console.error("Error during upload:", error)
    throw error
  }
}
