
import Event = Laya.Event;
import HttpRequest = Laya.HttpRequest;
import Browser = Laya.Browser;
import { Main } from "../Main";
import UserModel, { NetUserModel } from "./UserModel";
import { WXSdk } from "./WXSdk";
import Game_Tool from "../game_tool/Game_Tool";
import { FYHD_Sdk } from "./FYHD_Sdk";

const PROTOCOL_URL: string = "https://traintaxiapi.94xj.net/";

export class PROTOCOLS {

    public static protocols = {

        Login: "user/login",
        GameResult: "game/play",
        Easter: "game/revival",
        GetCfg: "config/table",
        EquipTrain:"theme/equipTrain",
        ShareGetTrain: "fission/train",
        BuyTrain:"theme/buyTrain",
        DoubleAward:"fission/vd",
        Sign:"sign/sign"
    }
};

export default class NetManager {
    public PostTokenRequest(protocol: string, completecb: Function, errorcb: Function, isload = false): void {
        let args: string = "";
        let url: string = PROTOCOL_URL + protocol;
        args = args = `token=${UserModel.Instance.CurModel.m_token}`;
        let httpRequest = new HttpRequest();
        httpRequest.once(Event.COMPLETE, this, this.onHttpRequestComplete, [completecb, errorcb, httpRequest, isload]);
        httpRequest.once(Event.ERROR, this, this.onHttpRequestError, [errorcb, httpRequest]);
        httpRequest.send(url, args, "post", "text");
        if (isload) {
            WXSdk.ShowLoading("");
        };
    }
    private onHttpRequestComplete(succeedcb: Function, failurecb: Function, httpRequest: HttpRequest, isload): void {
        console.log("jason数据返回 " + httpRequest.data);
        let data: JSON;
        if (isload) {
            WXSdk.HideLoading();
        }
        data = JSON.parse(httpRequest.data);
        if (data["code"] == 0) {
            if (data["user"] != null) {
                UserModel.Instance.CurModel.m_user = data["user"];
            }
            if (succeedcb != null) {
                console.log("上传成功回调方法 " + httpRequest.data);
                succeedcb(data);
            }
        }
        else {
            if (failurecb != null) {
                failurecb(data);
            }
        }
    }
    private onHttpRequestError(errorcb: Function, httpRequest: HttpRequest, isload) {
        if (errorcb != null) {
            errorcb(httpRequest);
        }
        console.log("Error! Http request error, code: " + httpRequest.data);
        if (isload) {
            WXSdk.HideLoading();
        }
    }
    public static get Instance(): NetManager {
        return NetManager.instance || (NetManager.instance = new NetManager());
    }

    private static instance: NetManager;
    //#region 登入
    /******************************* login *****************************/
    public login(progresscb: Function, completecb: Function, errorcb: Function): void {
        console.log("发送登录请求");
        var userInfor = UserModel.Instance;
        var ver = Main.VRE;
        let args: string = `code=${userInfor.m_code}&nickname=${userInfor.m_nickname}&avatar=${userInfor.m_avatar}&gender=${userInfor.m_gender}&country=${userInfor.m_country}&province=${userInfor.m_province}&city=${userInfor.m_city}&device=${userInfor.m_device}&share_id=${userInfor.m_share_id}&scene=${userInfor.m_scene}&v=${ver}`;
        console.log("登录 参数:  " + args);
        let httpRequest = new HttpRequest();
        httpRequest.once(Event.PROGRESS, this, this.onHttpRequestProgress, [progresscb, httpRequest]);
        httpRequest.once(Event.COMPLETE, this, this.onLoginRequestComplete, [completecb, httpRequest]);
        httpRequest.once(Event.ERROR, this, this.onHttpRequestError, [errorcb, httpRequest]);
        httpRequest.send(PROTOCOL_URL + PROTOCOLS.protocols.Login, args, "post", "text");
    }
    private onHttpRequestProgress() {
    }
    private onLoginRequestComplete(completecb: Function, httpRequest: HttpRequest) {
        let data: JSON = JSON.parse(httpRequest.data);
        console.log(data["user"]);
        console.log("登录完成");
        console.log(data["user_base"]);
        if (data["code"] != "0") {
            console.log("登录异常错误！错误信息：", httpRequest.data);
            completecb(data);
            return;
        }
        UserModel.Instance.SetUserModel(new NetUserModel(data["token"], data["configs"], data["app_setting"], data["user"], data["user_base"], data["user_invite"], data["user_lottery"], data["user_treasure"], data["t"], data["user_achievement"], data["user_sign"], data["user_arena"]));
        console.log(UserModel.Instance.CurModel.openid);
        completecb(data);
        WXSdk.ShareMessage();
        FYHD_Sdk.PushData();
    }

    public PostCfgRequest(completecb: Function, errorcb: Function): void {
        let args: string = "";
        let url: string = PROTOCOL_URL + PROTOCOLS.protocols.GetCfg;
        args = `token=${UserModel.Instance.CurModel.m_token}`;
        let httpRequest = new HttpRequest();
        httpRequest.once(Event.COMPLETE, this, () => {
            var data = JSON.parse(httpRequest.data);
            if (data["code"] == 0) {
               if(completecb!=null){
                   if(data["configs"]){
                       completecb(data["configs"]);
                   }
               }
            }
            else {
                if (errorcb != null) {
                    errorcb(data);
                }
            }
        });
        httpRequest.once(Event.ERROR, this,()=>{
            var data = JSON.parse(httpRequest.data);
            if (errorcb != null) {
                errorcb(data);
            }
        });
        httpRequest.send(url, args, "post", "text");

    }
    public HttpPostRequest(protocol: string, param: Array<{ [key: string]: any }>, completecb: Function, errorcb: Function, hasToken: boolean = true, isload = false): void {
        let args: string = "";
        let url: string = PROTOCOL_URL + protocol;
        if (hasToken == true) {
            args = `token=${UserModel.Instance.CurModel.m_token}&`;
        }
        if (protocol == PROTOCOLS.protocols.GameResult || protocol == PROTOCOLS.protocols.Easter||
            protocol==PROTOCOLS.protocols.ShareGetTrain ||protocol==PROTOCOLS.protocols.DoubleAward
        ) {
            let str = "abcdefghijkimnopqrstuvwxyz0123456789";
            let code = "{";
            let mask = "";
            for (let i = 0; i < 4; i++) {
                mask += str[Math.floor(Math.random() * 100) % str.length];
            }
            for (let i = 0; i < param.length; i++) {
                for (let key in param[i]) {
                    code += "\"" + key + "\":";
                    if (typeof param[i][key] === 'string') {
                        code += "\"" + param[i][key] + "\"";
                    } else {

                        code += param[i][key];
                    }
                }
                if (i < param.length - 1) {
                    code += ",";
                }
                else {
                    code += "}";
                }
            }
            args += "_r=" + mask + Game_Tool.get64Encode(code);
        }
        else {
            if (param != null) {
                for (let i = 0; i < param.length; i++) {
                    for (let key in param[i]) {
                        let val: string = param[i][key];
                        args += `${key}=${val}`;
                        if (i < param.length - 1) {
                            args += "&";
                        }
                    }
                }
            }
        }
        let httpRequest = new HttpRequest();
        httpRequest.once(Event.COMPLETE, this, this.onHttpRequestComplete, [completecb, errorcb, httpRequest, isload]);
        httpRequest.once(Event.ERROR, this, this.onHttpRequestError, [errorcb, httpRequest, isload]);
        httpRequest.send(url, args, "post", "text");
        if (isload) {
            WXSdk.ShowLoading("");
        }
    }
}