import moment from "moment";
import store from "@/store";
let savaData = {},
    checkData = {}, // 当前上传的节点文件和上一次提交进度
    timer = null,  // 网速定时器
    bytesReceivedPerSecond = {}; // 时间节点上传文件总量
export function OSSclose() {
    if (timer) {
        clearInterval(timer);
        timer = null;
        store.state.trials.uploadTip = '0KB/s'
    }
    bytesReceivedPerSecond = {};
    savaData = {};
    checkData = {};
    saveFinishedData(savaData);
}
export async function customerHttp(OSSclient, data, progressFn) {
    // 拿到上传到的file
    const uploadFile = data.file;
    // 拿到上传的size
    const uploadFileSize = uploadFile.size; // 这里拿到的单位是字节(uploadFileSize/ 1024 / 1024
    // = 多少兆)
    // 设置每一片的大小,partSize 指定上传的每个分片的大小，范围为100 KB~5 GB。
    // 分片标准为5MB,文件总大小大于5GB分片为20MB
    let partSize = 5 * 1024 * 1024;
    if (uploadFileSize < partSize) {
        partSize = uploadFileSize;
    }
    if (uploadFileSize > 5 * 1024 * 1024 * 1024) {
        partSize = 20 * 1024 * 1024;
    }
    // 设置所有的文件上传所有的唯一的saveFileId
    const saveFileId = `${uploadFileSize}_${data.path}`;
    if (data.speed) {
        setTimer();
    }
    initPage();
    let res = await multipartUpload(OSSclient, partSize, saveFileId, uploadFile, data, progressFn);
    return res;
}

async function multipartUpload(OSSclient, partSize, saveFileId, uploadFile, data, progressFn) {
    try {
        // object-name目前我是用的uploadFile.name,其实也是要根据你们的项目而定,
        // 有没有具体的规定, 要不要加项目名, 要不要加对应的环境;
        // 上传的参数
        const uploadParams = {
            partSize,
            progress: (percentage, checkpoint) => {
                savaData[saveFileId] = checkpoint;
                if (!checkData[saveFileId]) {
                    checkData[saveFileId] = 0
                }
                if (data.speed) {
                    let time = new Date().getTime();
                    let timeList = Object.keys(bytesReceivedPerSecond).sort((a, b) => a - b);
                    let bytesTime = timeList.find(item => time - item < 1000);
                    if (bytesTime) {
                        bytesReceivedPerSecond[bytesTime] += data.file.size * (percentage - checkData[saveFileId]);
                    } else {
                        // console.log("未查询到时间")
                        if (timeList.length > 0) {
                            bytesReceivedPerSecond[timeList[timeList.length - 1]] += data.file.size * (percentage - checkData[saveFileId]);
                        } else {
                            bytesReceivedPerSecond[time] = data.file.size * (percentage - checkData[saveFileId]);
                        }
                    }
                }
                savaData["lastSaveTime"] = new Date();
                progressFn(percentage, data.file, checkData[saveFileId])
                checkData[saveFileId] = percentage;
                if (percentage === 1) {
                    delete checkData[saveFileId]
                }
                // 在上传过程中,把已经上传的数据存储下来
                saveFinishedData(savaData);
            },
            // headers: {
            //     "Content-Disposition": `attachment; filename=hahaha.dcm`,
            //     "Cache-Control": "public, no-cache"
            // }
        };
        // 断点续传
        await resumeUpload(uploadParams, saveFileId);
        const res = await OSSclient.multipartUpload(
            data.path,
            uploadFile,
            uploadParams
        );
        if (res.res.status === 200) {
            // 重新去掉某个缓存进行设置
            delete savaData[saveFileId];
            saveFinishedData(savaData);
        } else if (res.res.status === 404) {
            delete savaData[saveFileId];
            saveFinishedData(savaData);
        }
        return res;
    } catch (e) {
        console.log(e);
        delete savaData[saveFileId];
        saveFinishedData(savaData);
        // 捕获超时异常。
        if (e.code === "ConnectionTimeoutError") {
            console.log("TimeoutError");
            // do ConnectionTimeoutError operation
        }
        return false;
    }
}
async function resumeUpload(uploadParams, saveFileId) {
    if (localStorage.getItem("upload-function-name")) {
        const obj = JSON.parse(localStorage.getItem("upload-function-name"));
        if (Object.keys(obj).includes(saveFileId)) {
            uploadParams.checkpoint = obj[saveFileId];
        }
    }
}
// 存储到内存
function saveFinishedData(finishedData) {
    localStorage.setItem(
        "upload-function-name",
        JSON.stringify(finishedData)
    );
}
function initPage() {
    // 判断是不是有缓存
    const localData = localStorage.getItem("upload-function-name");
    if (!localData) return;
    savaData = JSON.parse(localData);
    // 当前时间 > 存储时间(1000 * 60 * 60表示1h,意思就是这些数据你要存多久,
    // 可以是1h也可以是多少天,随意)
    if (
        moment(new Date()).diff(moment(savaData.lastSaveTime)) >
        1000 * 60 * 60
    ) {
        localStorage.removeItem("upload-function-name");
    }
}
function setTimer() {
    if (timer) return false;
    timer = setInterval(() => {
        // console.log(Object.assign({}, bytesReceivedPerSecond))
        let timeList = Object.keys(bytesReceivedPerSecond).sort((a, b) => a - b);
        if (timeList.length > 0) {
            let totalBytes = timeList.reduce((sum, bytes) => sum + bytesReceivedPerSecond[bytes], 0) / (5 * 1024);
            let unit = 'KB/s';
            if (totalBytes > 1024) {
                totalBytes = totalBytes / 1024;
                unit = "MB/s";
            }
            store.state.trials.uploadTip = totalBytes.toFixed(3) + unit;
        }
        if (timeList.length >= 5) {
            delete bytesReceivedPerSecond[timeList[0]]
        }
        let time = new Date().getTime();
        bytesReceivedPerSecond[time] = 0;
    }, 1000)
}