import ObsClient from "esdk-obs-browserjs/src/obs"
import Vue from "vue";
export const uploadToOBS = async (file, progressCallback, type, cancelCallback) => {
  try {
    const obsClient = new ObsClient({
      access_key_id:  Vue.prototype.$runtimeConfig.VUE_APP_OBS_ACCESS_KEY_ID,
      secret_access_key:  Vue.prototype.$runtimeConfig.VUE_APP_OBS_SECRET_ACCESS_KEY,
      server:  Vue.prototype.$runtimeConfig.VUE_APP_OBS_SERVER,
      timeout: 1200,
    })

    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}`
    const key = type === 1 ? courseKey : videoKey

    var callback = (transferredAmount, totalAmount, totalSeconds) => {
      const progress = Number.parseInt((transferredAmount * 100.0) / totalAmount)
      if (progressCallback) {
        progressCallback(progress)
      }
    }

    return new Promise((resolve, reject) => {
      let isCancelled = false

      if (cancelCallback) {
        cancelCallback({
          cancel: () => {
            console.log("Cancelling OBS upload")
            isCancelled = true
            reject(new Error("Upload cancelled by user"))
          },
        })
      }
      //四福堂专属配置
      /*   resolve({
           "RequestId": "",
           "urlPath": ""
         })*/
      obsClient.putObject(
        {
          Bucket: Vue.prototype.$runtimeConfig.VUE_APP_OBS_BUCKET,
          Key: key,
          Body: file,
          ProgressCallback: callback,
        },
        (err, result) => {
          if (isCancelled) {
            return // Don't process result if cancelled
          }

          if (err) {
            reject(err)
            console.error("Error-->" + err)
          } else {
            const a = {
              ...result,
              urlPath: key,
            }
            console.log("上传成功", a)
            resolve(a)
          }
        },
      )
      //注释到这里【四福堂】
    })
  } catch (error) {
    console.error("Error during upload:", error)
    throw error
  }
}
