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

console.log("环境变量：", process.env)
console.log("NODE_ENV:", process.env.NODE_ENV)
console.log("VUE_APP_COS_BUCKET:", Vue.prototype.$runtimeConfig.VUE_APP_COS_BUCKET)
console.log("VUE_APP_COS_REGION:", Vue.prototype.$runtimeConfig.VUE_APP_COS_REGION)

const config = {
  Bucket: Vue.prototype.$runtimeConfig.VUE_APP_COS_BUCKET,
  Region: Vue.prototype.$runtimeConfig.VUE_APP_COS_REGION,
}
console.log("COS配置：", config)

export const uploadObject = async (file, onProgress, type, callBackUp) => {
  try {
    console.log(type)
    const response = await getTmpSecretKey()
    console.log("Key  ", response)
    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,
        })
      },
    })

    console.log("初始化成功")
    console.log(process.env)
    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;
    console.log("LIVE_PATH value:", Vue.prototype.$runtimeConfig.VUE_APP_LIVE_PATH);  // 添加这行查看实际值
    console.log("Type of LIVE_PATH:", typeof Vue.prototype.$runtimeConfig.VUE_APP_LIVE_PATH);  // 查看类型
// 检查是否是空字符串或只有空格
    if (Vue.prototype.$runtimeConfig.VUE_APP_LIVE_PATH && Vue.prototype.$runtimeConfig.VUE_APP_LIVE_PATH.trim() !== '') {
      liveKey = `${Vue.prototype.$runtimeConfig.VUE_APP_LIVE_PATH.trim()}/${uploadDay}/${upload_file_name}`;
    } else {
      liveKey = `/course/${uploadDay}/${upload_file_name}`;
    }
    console.log("liveKey={}",liveKey);
    const key = type === 3 ? liveKey : (type === 1 ? courseKey : videoKey);

    console.log("开始上传")

    return new Promise((resolve, reject) => {
      console.log("uploadFile")
      let taskId = null

      const uploadTask = cos.uploadFile(
        {
          Bucket: config.Bucket,
          Region: config.Region,
          Key: key,
          StorageClass: "STANDARD",
          Body: file,
          onTaskReady: (id) => {
            taskId = id
            console.log("Task ready:", taskId)
            if (callBackUp) {
              callBackUp({
                cos,
                taskId,
                cancel: () => {
                  console.log("Cancelling COS upload:", taskId)
                  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,
            }
            console.log("上传成功", result)
            resolve(result)
          }
        },
      )
    })
  } catch (error) {
    console.error("Error during upload:", error)
    throw error
  }
}
