/**
 * @description 错误日志管理类
 * @author 邹勇
 */
export default class BuglySDK {
    constructor() {
        this.initELKHandler();
    }

    /**
     * 接入第三方腾讯bugly
     */
    private initBugly(){

    }

    /**
     * 错误日志发送elk服务器
     */
    private initELKHandler() {
        if (cc.sys.isNative) {
            let __handler;
            if (window['__errorHandler']) {
                __handler = window['__errorHandler'];
            }

            window['__errorHandler'] = function (...args) {
                console.log('游戏报错,原生系统');
                BuglySDK.handleError(...args);
                if (__handler) {
                    __handler(...args);
                }
            }
        }
    }


    /** 上次发送错误日志的时间 */
    static lastSendErrorTime: number = new Date().getTime();
    /** 最近发送的错误日志 */
    static lastSendErrors: string[] = [];

    static handleError(...args) {
        //简化错误日志
        let errors = "";
        for (let i = 0; i < args.length; i++) {
            if (typeof args[i] == 'string' && args[i].length > 20) {
                errors += args[i] + '\n';
            }
            else if (args[i] instanceof Array) {
                for (let j = 0; j < args[i].length; j++) {//安卓内捕获的错误优化缩减字段
                    errors += args[i][j];
                }
            }
        }
        if (errors.indexOf('TypeError') != -1) {
            errors = errors.slice(errors.indexOf('TypeError') + 'TypeError'.length + 2);
        }
        let [a, start, d, s, q] = [0, '', '', '', '[]@'];
        while (a < errors.length) {
            s = errors.charAt(a);
            if (q.indexOf(s) != -1) {
                if (start == '') {
                    start = s;
                }
                else {
                    if ((start == '[' && s == ']') || (start == '@' && s == ']')) {
                        start = '';
                        d += ' | ';
                    }
                }
            }
            else if (start == '') {
                d += s;
            }
            a++;
        }
        //超过长度无法加密，加密Long服务器无法解析
        if (d.length > 120) {
            d = d.slice(0, 120);
        }

        //相同错误 一定时间禁止连续发送
        let time = new Date().getTime();
        if (BuglySDK.lastSendErrors.indexOf(d) != -1 && time - BuglySDK.lastSendErrorTime < 30000) {
            return;
        }
        BuglySDK.lastSendErrors.push(d);
        BuglySDK.lastSendErrorTime = time;
        if (BuglySDK.lastSendErrors.length > 5) {
            BuglySDK.lastSendErrors = BuglySDK.lastSendErrors.slice(BuglySDK.lastSendErrors.length - 5);
        }

        // 拼接服务类型（0测试服 1测试服）和 玩家uin 
        let uin = gData.httpData.serverType + ":" + gData.loginData.uin;

        let senddata = {
            "level": "error",
            "game": gData.appData.appNameBugly + ":" + uin,
            "message": d
        };

        const httpRequest = new XMLHttpRequest();
        httpRequest.responseType = "text";
        const send_url = 'https://elktest.duiweize.com/api/logs/record';
        httpRequest.open("POST", send_url);
        httpRequest.setRequestHeader("Content-Type", 'application/json;charset=UTF-8');

        httpRequest.onerror = function (e) {
            console.log("handleError.onError:", e);
        };

        let str = JSON.stringify(senddata);
        str = mk.encrypt.rsaEncrypt(str);

        httpRequest.send(str);
    }
}