import ObsClient from "esdk-obs-browserjs/src/obs";


export const uploadToOBS = async(file,progressCallback,type) =>  {
    try {
        const obsClient = new ObsClient({
            access_key_id: 'K2UTJGIN7UTZJR2XMXYG',
            secret_access_key: 'sbyeNJLbcYmH6copxeFP9pAoksM4NIT9Zw4x0SRX',
            server: 'https://obs.cn-north-4.myhuaweicloud.com'
        });
        let fileName = file.name || ""
        const upload_file_name = new Date().getTime() + '.' + fileName.split(".")[fileName.split(".").length - 1];
        let date =  new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let strDate = date.getDate()
        let uploadDay = `${year}${month}${strDate}`
        let videoKey = `userVideo/${uploadDay}/${upload_file_name}`
        let courseKey = `course/${uploadDay}/${upload_file_name}`
        let key = type ===1 ? courseKey : videoKey;
        var callback = function (transferredAmount, totalAmount, totalSeconds) {
            // 获取上传进度百分比
            const progress = parseInt(transferredAmount * 100.0 / totalAmount);
            console.log("OBS上传进度=========>",progress);
            if (progressCallback) {
              progressCallback(progress);
            }
          };
        return new Promise((resolve, reject) => {
            //上传对象
            obsClient.putObject({
                Bucket: 'jzzx-hw079058881',//桶名称
                Key: key,//文件名
                Body: file,
                ProgressCallback: callback,//进度回调
            }, (err, result) => {
                if(err){
                    reject(err);
                    console.error('Error-->' + err);
                }else{
                  // 将上传的key包含在返回的数据中
                  const a = {
                    ...result,
                    urlPath: key
                  };
                  console.log('上传成功', a);
                  resolve(a);
                }
            });
        });
    } catch (error) {
        console.error('Error during upload:', error);
        throw error;
    }
}
