/**
 * @description http请求管理类
 * @author 邹勇
 */
export default class HttpSystem {
    constructor() {
    }

    /**
     * 游戏接口，通用
     * @param url 接口完整地址
     * @param data 加密前数据
     * @param async 是否异步请求（后端要求防阻塞）
     */
    public async sendData(url, data: any, async = true) {
        let encode = '';
        let dataN = null;
        data.timestamp = Math.floor(new Date().getTime() / 1000);
        data.appVersion = gData.appData.appVersion;
        data.tfChannel = gData.appData.tfChannel;
        data.versioncfg = gData.appData.version;
        encode = mk.encrypt.encrypt(JSON.stringify(data), gData.loginData.sessionKey, gData.appData.appId);
        dataN = {
            "uin": gData.loginData.uin,
            "encrypt": encode
        }
        let result = await this.sendRequest(url, 'POST', JSON.stringify(dataN), false, async);
        return this.checkData(result);
    }

    /**
     * http请求 登录用
     * @param url 请求头
     * @param method 'GET' || 'POST' 
     * @param data 数据
     * @param isRsa 是否加密
     * @param async 是否异步请求
     */
    public sendRequest(url, method: string = 'POST', data: string = null, isRsa: boolean = true, async = true) {
        url = gData.httpData.getServerUrl() + url;
        return new Promise<any>((resolve: (data: any) => void, reject) => {
            let requesttimes = 0;
            let httpRequest = new XMLHttpRequest();
            let send = () => {
                httpRequest.open(method, url, async);
                httpRequest.setRequestHeader("Content-Type", 'application/json;charset=UTF-8');
                if (isRsa && data != null) {
                    data = mk.encrypt.rsaEncrypt(data);
                }
                httpRequest.send(data);
            };

            // httpRequest.timeout = 30000;
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        var responseStr = httpRequest.responseText;
                        let response = JSON.parse(responseStr);
                        mk.console.logSingle("response:" + url, response)
                        resolve(response);
                    }
                    else {
                        mk.console.error("httpRequest.status", httpRequest.status);
                        reject({ errcode: 1, errmsg: "status..." + httpRequest.status });
                    }
                }
            }

            httpRequest.ontimeout = function (e) {
                requesttimes++;
                if (requesttimes >= 3) {
                    mk.console.error("http.ontimeout", url);
                    reject({ errcode: 1, errmsg: "ontimeout" });
                }
                else {
                    send();
                }
            };
            httpRequest.onerror = function (e) {
                mk.console.error("http.onerror", url);
                reject({ errcode: 1, errmsg: "onerror" });
            };
            send();
        });
    }

    /** 
     * 检测用明文还是密文
     * @param response 返回消息
     * @param forceData true 明文  false 有密文优先密文，没密文情况下用明文
     */
    checkData(response, forceData = false) {
        let data = null
        if (forceData) {
            data = response.data;
        }
        else {
            if (response.encrypt) {
                data = mk.encrypt.decrypt(response.encrypt, gData.loginData.sessionKey, gData.appData.appId);
                data = JSON.parse(data);
            }
            else if (response.data) {
                data = response.data;
            }
        }
        response.data = data;
        return response;
    }
}
