import axios from "axios";
import {uuid} from "~/utils/index";
import request from "~/utils/request";
import Crypto from 'crypto-js';


const Base64 = {
    // private property
    _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
    // public method for encoding
    encode: function (input: string) {
        let output = '';
        let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        let i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
    // public method for decoding
    decode: function (input: string) {
        let output = '';
        let chr1, chr2, chr3;
        let enc1, enc2, enc3, enc4;
        let i = 0;
        input = input.replace(/[^A-Za-z0-9+\/=]/g, '');
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 !== 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 !== 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
    // private method for UTF-8 encoding
    _utf8_encode: function (input: string) {
        input = input.replace(/\r\n/g, '\n');
        let output = '';
        for (let n = 0; n < input.length; n++) {
            const c = input.charCodeAt(n);
            if (c < 128) {
                output += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                output += String.fromCharCode((c >> 6) | 192);
                output += String.fromCharCode((c & 63) | 128);
            } else {
                output += String.fromCharCode((c >> 12) | 224);
                output += String.fromCharCode(((c >> 6) & 63) | 128);
                output += String.fromCharCode((c & 63) | 128);
            }
        }
        return output;
    },
    // private method for UTF-8 decoding
    _utf8_decode: function (input: string) {
        let output = '';
        let i = 0;
        let c = 0, c2 = 0;
        while (i < input.length) {
            c = input.charCodeAt(i);
            if (c < 128) {
                output += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = input.charCodeAt(i + 1);
                output += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = input.charCodeAt(i + 1);
                let c3 = input.charCodeAt(i + 2);
                output += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return output;
    },
};


class MultipleStageUpload {
    private readonly presets: object;
    private readonly bucket: string;
    private readonly filepath: string;
    private readonly onProgress?: (percent: number) => void;
    private retried: number = 0;


    constructor(presets: object, bucket: string, filepath: string, onProgress?: (percent: number) => void) {
        this.presets = presets;
        this.bucket = bucket;
        this.filepath = filepath;
        this.onProgress = onProgress;
    }

    private get url(): string {
        return "https://v0.api.upyun.com/" + this.bucket + this.filepath;
    }

    upyunHeaderParse = (headers: any): any => {
        return {
            uuid: headers["x-upyun-multi-uuid"],
            next_part: headers["x-upyun-next-part-id"],
            next_size: headers["x-upyun-next-part-size"],
            remain_size: headers["x-upyun-remain-size"]
        }
    }

    init = async (file: File) => {
        this.retried = 0;
        const {status, headers} = await axios({
            url: this.url, method: 'PUT',
            headers: {
                ...this.presets,
                "X-Upyun-Multi-Stage": "initiate",
                "X-Upyun-Multi-Length": file.size.toString(),
                "Content-Length": "0",
                "X-Upyun-Multi-Type": file.type,
            }
        });
        if (status === 204) {
            let options = this.upyunHeaderParse(headers);
            return this.upload(file, options);
        }
    };
    upload = async (file: File, {uuid, cursor = 0, next_part, next_size, remain_size}: any): Promise<any> => {
        if (Number(remain_size) <= 0) {
            return this.done(uuid);
        }
        let next_cursor = cursor + Number(next_size);
        let data = file.slice(cursor, next_cursor);
        try {
            const {status, headers} = await axios({
                url: this.url, data, method: 'PUT',
                headers: {
                    ...this.presets,
                    "X-Upyun-Multi-Stage": "upload",
                    "X-Upyun-Multi-Uuid": uuid,
                    "Content-Length": next_size,
                    "X-Upyun-Part-Id": next_part,
                }
            });
            if (status === 204) {
                if (this.onProgress) {
                  this.onProgress(Math.ceil((next_cursor / file.size) * 100));
                }
                let options = this.upyunHeaderParse(headers);
                return this.upload(file, {...options, cursor: next_cursor})
            }
        } catch (e: any) {
            console.log(e)
            // retry
            if (this.retried < 3) {
                this.retried++;
                return this.upload(file, {uuid, cursor, next_part, next_size, remain_size});
            }
            return {r: false, e: e.message, d: e.data};;
        }

    };
    done = async (uuid: string) => {
        return axios({
            url: this.url, method: 'PUT',
            headers: {
                ...this.presets,
                "X-Upyun-Multi-Stage": "complete",
                "X-Upyun-Multi-Uuid": uuid,
                "Content-Length": "0",
            }
        }).then(({status, data}) => {
            // @ts-ignore
            return status === 201 ? {r: true, d: `https://upyun.${UPYUN_DOMAIN}${this.filepath}`} : {r: false, e: data};
        }).catch((error) => {
            return {r: false, e: error.message, d: error.data};
        });
    }
}

class UpYun {

    private readonly bucket: string;
    private readonly signUrl: string = '/api/v1/uc/upyun_token';

    constructor(bucket: string, signUrl?: string) {
        this.bucket = bucket;
        if (signUrl) this.signUrl = signUrl;
    }

    sign = async (path: string) => {
        const date = (new Date()).toUTCString();
        const data = ['PUT', path, date].join('&')
        let { r, d, e} = await request({
            url: this.signUrl, method: 'post', data,
            headers: {
                // since some version, axios will add double quote if data is string, to avoid that, set the content type to text/plain
                // refer: https://github.com/axios/axios/issues/4034#issuecomment-915244277
                'Content-Type': 'text/plain'
            }
        });

        return { r, d: {authorization: d, 'x-date': date}, e };
    };

    upload = async (file: any, directory: string = 'music-room', onProgress?: (percent: number) => void) => {

        let name = uuid(), ext = file.name.split('.').pop();
        let filepath = `/${directory}/${name}.${ext}`;
        const {r, d, e} = await this.sign('/' + this.bucket + filepath);
        if (!r) return e;

        if (file.size > 1024 * 1024) {
            let multi = new MultipleStageUpload(d, this.bucket, filepath, onProgress);
            return multi.init(file);
        }

        return axios({
            url: `https://v0.api.upyun.com/${this.bucket}${filepath}`,
            headers: d, data: file, method: 'PUT'
        }).then(({status, data}) => {
            if (onProgress) {
                onProgress(100);
            }
            // @ts-ignore
            return status === 200 ? {r: true, d: `https://upyun.${UPYUN_DOMAIN}${filepath}`} : {r: false, e: data};
        }).catch((error) => {
            console.log(error)
            return {r: false, e: error.message, d: error.data};
        });
    };

}

// @ts-ignore
const hwUpYun = new UpYun(UPYUN_BUCKET);

const UpyunAccess = {
    cache: {} as {[key: string]: {url: string, etime: number}},
    sign: (url?: string) => {
        if (!url) return;
        let {origin, pathname} = new URL(url);
        url = origin + pathname;
        let cached = UpyunAccess.cache[url];
        if (cached) {
            // 读取缓存，如果还有半小时以上才会过期，则直接返回缓存的url
            if (cached.etime - Math.ceil(Date.now() / 1000) >= 1800) {
                return cached.url;
            }
            // 删除缓存
            delete UpyunAccess.cache[url];
        }
        const secret = "C29DBA1F1EA4462088136C3A85C2FBFC";
        const etime = Math.ceil(Date.now() / 1000) + 3600; // 1小时有效
        const sign = Crypto.MD5(`${secret}&${etime}&${pathname}`).toString();
        let signed = url + "?_upt=" + sign.substring(12, 12 + 8) + etime;
        UpyunAccess.cache[url] = {url: signed, etime };
        return signed;
    },
    getSign: async (url?: string) => {
        if (!url) return;
        let {origin, pathname} = new URL(url.replace(/"/g, ""));
        url = origin + pathname;
        let cached = UpyunAccess.cache[url];
        if (cached) {
            // 读取缓存，如果还有半小时以上才会过期，则直接返回缓存的url
            if (cached.etime - Math.ceil(Date.now() / 1000) >= 1800) {
                return cached.url;
            }
            // 删除缓存
            delete UpyunAccess.cache[url];
        }
        const {r, d, e} = await request({url: '/api/ngx/upt', params: {uri: url}})
        if (r) {
            // 防止返回的内容仅包含数字，被自动转换成了数字
            let upt = d.toString().trim(), etime = Number.parseInt(upt.substring(8));
            let result = url + "?_upt=" + upt
            UpyunAccess.cache[url] = {url: result, etime };
            return result;
        }
    }
}

export {Base64, hwUpYun, UpyunAccess};

export default UpYun;
