import TTUploader from 'tt-uploader'
import Vue from "vue";
import { HsyAssumeRoleService } from '@/api/course/userVideo'
const  spaceName = Vue.prototype.$runtimeConfig.VUE_APP_HSY_SPACE
export const uploadToHSY = async (file, onProgress, type, callBackUp) => {
  try {
    const res = await HsyAssumeRoleService()
    //console.log('火山云 STS 凭证：', res)
    const credentials = res.data.result.credentials
    //console.log('火山云 credentials 凭证：', credentials)

    if (!credentials) {
      throw new Error('未获取到火山云 STS 凭证')
    }

    const uploader = new TTUploader({
      appId: '917052',
      userId: '68185444',
      videoConfig: {
        spaceName: spaceName,
      }
    })

    const date = new Date();
    const yyyy = date.getFullYear();
    const MM = String(date.getMonth() + 1).padStart(2, '0');
    const dd = String(date.getDate()).padStart(2, '0');
    const datePath = `${yyyy}${MM}${dd}`;


    const fileName = `${Date.now()}.mp4`;

    const remoteFileName = `course/${datePath}/${fileName}`;

    const fileKey = uploader.addFile({
      file,
      type: 'video',
      fileName:remoteFileName,
      stsToken: {
        CurrentTime: credentials.currentTime,
        ExpiredTime: credentials.expiredTime,
        SessionToken: credentials.sessionToken,
        AccessKeyID: credentials.accessKeyId,
        SecretAccessKey: credentials.secretAccessKey,
      },
    })

    return new Promise((resolve, reject) => {

      // 上传进度
      uploader.on('progress', (info) => {
        onProgress && onProgress({
          percent: info.percent,
        })
      })

      // 上传完成
      uploader.on('complete', (info) => {
        resolve({
          ...info.uploadResult,
          fileKey,
        })
      })

      // 上传失败
      uploader.on('error', (info) => {
        reject(info)
      })

      // 取消上传支持
      if (callBackUp) {
        callBackUp({
          uploader,
          fileKey,
          cancel: () => {
            try {
              uploader.removeFile(fileKey)
              reject(new Error('Upload cancelled by user'))
            } catch (e) {
              reject(e)
            }
          }
        })
      }

      uploader.start(fileKey)
    })

  } catch (error) {
    console.error('火山云上传失败：', error)
    throw error
  }
}
