import {
    getALiOssToken,
} from "../api";
//OSS上传需要的参数
//完整路径
// http://strong-info.oss-cn-beijing.aliyuncs.com/studio_course/1634543011057_1.png
const OSS_REGION = 'oss-cn-beijing';
const OSS_BUCKET = 'strong-info';
//OSS上传回显的路径
// export const OSS_ESC = 'aliyuncs.com';
// export const accessKeyId='LTAI5tPsUsCwJKykDA1vWtWP';
// export const accessKeySecret='94ZvQDCoCzepz32pBg7KG6Mj1SyB7T';
// export const OSS_URL1 = '/public/uploads/';
// export const OSS_URL = '/studio_course/';
let client = null;
//过期时间 默认不传，最大时间一小时
const tokenExpireTime = '';

//获取上传OSS所需要的参数
async function getToken() {
    let result = await getALiOssToken({tokenExpireTime: tokenExpireTime});
    if (result.code == 0) {
        let OSS = require('ali-oss');
        client = new OSS({
            region: OSS_REGION,
            accessKeyId: result.data.AccessKeyId,
            accessKeySecret: result.data.AccessKeySecret,
            bucket: OSS_BUCKET,
            stsToken: result.data.SecurityToken,
            refreshSTSToken: async () => {
                let result = await getALiOssToken();
                if (result.code == 0) {
                    return {
                        accessKeyId: result.data.AccessKeyId,
                        accessKeySecret: result.data.AccessKeySecret,
                        stsToken: result.data.SecurityToken,
                    };
                }
            },
        });
    }
}

//上传文件到OSS
//接受参数 files 数组类型、对象类型
//返回参数 uploadFiles  数组类型、对象类型
async function uploadOSS(files,OSS_URL) {
    if (!client) {
        await getToken()
    }
    let uploadFiles = [];
    if (Array.isArray(files)) {
        for (let i = 0; i < files.length; i++) {
            let objectKey = OSS_URL + files[i].lastModified + '_' + files[i].name;
            let result1 = await client.multipartUpload(objectKey, files[i]);
            if (result1.res.status === 200) {
                uploadFiles.push({url: result1.name})
            }
        }
    } else {
        let objectKey = OSS_URL + files.lastModified + '_' + files.name;
        let result1 = await client.multipartUpload(objectKey, files);
        if (result1.res.status === 200) {
            uploadFiles = { url: result1.name};
        }
    }
    return uploadFiles;
}

/** base64变成图片文件*/
function base64toFile(dataurl, filename) {
    let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type: mime});
}
export default {
    getClient: uploadOSS,
    base64toFile:base64toFile
}
