import COS from 'cos-js-sdk-v5';
import { Message } from 'element-ui';
import { getTmpSecretKey } from '@/api/common';

const config = {
    Bucket: 'hcl-1323137866',
    Region: 'ap-chongqing',
};

// 上传到腾讯云cos
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({
            getAuthorization: (options, callback) => {
                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    XCosSecurityToken: credentials.sessionToken,
                    StartTime: data.startTime,
                    ExpiredTime: data.expiredTime,
                });
            },
        });


        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;
        return new Promise((resolve, reject) => {
            cos.uploadFile(
                {

                    Bucket: config.Bucket, /* 必须 */
                    Region: config.Region, /* 存储桶所在地域，必须字段 */
                    Key: key, // 文件名
                    StorageClass: 'STANDARD', // 上传类型，可选
                    Body: file, // 上传文件对象
                    // onTaskReady: function (taskId) {
                    //     // 用于中断分片上传回调
                    //     console.log('Task ready:', taskId);
                    //     callBackUp && callBackUp({cos,taskId})
                    // },
                    onProgress: function (progressData) {
                        console.log('COS上传进度=======>:', JSON.stringify(progressData));
                        onProgress(progressData);
                    },
                    // onFileFinish: function (err, data, options) {
                    //     console.log(options.Key + '上传' + (err ? '失败' : '完成'));
                    // },
                },
                (err, data) => {
                    if (err) {
                        reject(err);
                    } else {
                        // 将上传的key包含在返回的数据中
                        const result = {
                            ...data,
                            urlPath: key
                        };
                        console.log('上传成功', result);
                        resolve(result);
                    }
                }
            );
        });
    } catch (error) {
        console.error('Error during upload:', error);
        throw error;
    }
};
