
import Event = Laya.Event;
import HttpRequest = Laya.HttpRequest;
import Browser = Laya.Browser;
import UserModel, { NetUserModel } from "./UserModel";
import GameTool from "../Util/GameTool";
import { UserInfoManager } from "../GameLogic/UserInfoManager";
import GameSetting from "./GameSetting";
import { WXSdk } from "./WXSdk";
import { PlayerManager } from "../GameLogic/PlayerManager";

// let param = [{ "t": UserModel.Instance.CurModel.ServerTime }, { "channel": "video" },{"play_id":GameController.Instance.player_id}];
// NetManager.Instance.HttpPostRequest(PROTOCOLS.protocols.Easter, param,
//     (data: any) => {
//         console.log(data);
//         GameController.Instance.EasterGame();
//         ViewManager.Instance.CloseView(ViewType.easter_ui);
//         ViewManager.Instance.CloseView(ViewType.hutui2_ui);
//     },
//     (data) => {
//         console.log(data);
//         WXSdk.ShowToast("复活失败", false);
//     }, true, true);

// } else {
// WXSdk.ShowToast("只有看完整个视频才会有奖励哦", false);
// }

const PROTOCOL_URL: string = "https://gungangapi.xwxgame.com/";

export class PROTOCOLS {

    public static protocols = {
        //user
        Login: "user/login",
        Userauth: "user/auth",
        BuyLand: "shop/land",
        UserSync: "user/sync",
        ShopBuild: "shop/build",
        ShopUpgrade: "shop/upgrade",
        ShopSale: "shop/sale",
        RoleUpgrade: "role/upgrade",
        Fissionvd: "fission/vd",
        DailyTaskrefresh: "dailytask/refresh",
        DailyTaskrewards: "dailytask/rewards",

        Rankingvmoney: "ranking/vmoney",
        Lotterylottery: "lottery/lottery",
        AchievementgetRewards: "achievement/getRewards",
        Fissiondeduct: "fission/deduct",
        Sign: "sign/sign",
        InvitegetRewards: "invite/getRewards",
        InvitetargetRewards: "invite/targetRewards",

        GameResult: "game/play",
        Easter: "game/revival",
        GetCfg: "config/table",
        DoubleAward: "fission/vd",
        //kun
        KunDiscard: "kun/discard",//丢弃
        KunEquip: "kun/equip",//使用
        KunMove: "kun/move",//移动
        KunBuy: "kun/buy",//购买


        Opentreasure: "treasure/open",
        Entertreasure: "treasure/enter",

        Buy: "theme/buy",
        Equip: "theme/equip",
        themefission: "theme/fission",
        Start: "game/start",

        //att
        UpgradeAttr:"attr/upgrade"
    }
};

export default class NetManager {
    public PostTokenRequest(protocol: string, completecb: Function, errorcb: Function, isload = true): 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 {

        let data: JSON;
        if (isload) {
            WXSdk.HideLoading();
        }
        data = JSON.parse(httpRequest.data);
        console.log("请求成功:" + JSON.stringify(data));
        if (data["code"] == 0) {
            //if (data["user"] != null) {
            // UserModel.Instance.CurModel.m_user = data["user"];
            UserModel.Instance.RefreshModel(data);

            // }
            if (succeedcb != null) {
                succeedcb(data);
            }
        }
        else {
            if (failurecb != null) {
                var mess = GameTool.SpliteString(data["message"], ",")[0];
                failurecb(mess);
            }
        }
    }
    private onHttpRequestError(errorcb: Function, httpRequest: HttpRequest, isload) {
        if (errorcb != null) {
            var data = JSON.parse(httpRequest.data);
            errorcb(data);
        }
        console.log("Error! Http request error, code: " + 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 = GameSetting.VER;
        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.channel}&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);
        console.log("登录完成");
        if (data["code"] != "0") {
            var errInfo = JSON.stringify(httpRequest.data);
            console.log("登录异常错误！错误信息：", errInfo);
            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"], data["is_new"], data["user_shop"], data["user_daily_task"], data["user_video"]
        ));

        UserInfoManager.Appseting(data["app_setting"]);
        var ver = data["table_version"];
        UserModel.Instance.CurModel.JundgCfg(ver, (c) => {
            if (c) {
                UserInfoManager.GameInfo();

                completecb(data);
            }
        });
        WXSdk.ShareMessage();


    }

    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 = true): void {
        let args: string = "";
        let url: string = PROTOCOL_URL + protocol;
        if (hasToken == true) {
            args = `token=${UserModel.Instance.CurModel.m_token}&`;
        }
        if (protocol == PROTOCOLS.protocols.UserSync || protocol == PROTOCOLS.protocols.Fissionvd || protocol == PROTOCOLS.protocols.Lotterylottery
            || protocol == PROTOCOLS.protocols.Fissiondeduct || protocol == PROTOCOLS.protocols.KunBuy || protocol == PROTOCOLS.protocols.KunDiscard
            || protocol == PROTOCOLS.protocols.KunEquip || protocol == PROTOCOLS.protocols.KunMove || protocol == PROTOCOLS.protocols.Start || protocol == PROTOCOLS.protocols.GameResult
            || protocol == PROTOCOLS.protocols.themefission || protocol == PROTOCOLS.protocols.Opentreasure||protocol==PROTOCOLS.protocols.UpgradeAttr
        ) {
            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 + GameTool.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("");
        }
    }
    // public UserSyncInfo(test?, callback?) {
    //     var num = test ? test : PlayerManager.Instance.Coin;
    //     num = PlayerManager.Instance.Coin = Math.floor(num);
    //     var vmoney = num.toString();
    //     let param = [{ "t": UserModel.Instance.CurModel.ServerTime }, { "vmoney": vmoney }];
    //     NetManager.Instance.HttpPostRequest(PROTOCOLS.protocols.UserSync, param,
    //         (data: any) => {
    //             UserInfoManager.PlayerInfo();
    //             if (callback) callback();
    //         },
    //         (data) => {
    //             console.log(data);
    //         }, true, false);
    // }

    private static errorRequest(arg?, callback?) {
        let httpRequest: Laya.HttpRequest = new Laya.HttpRequest();
        if (callback) {
            httpRequest.once(Laya.Event.PROGRESS, this, () => { callback.progress && callback.progress(httpRequest) });
            httpRequest.once(Laya.Event.ERROR, this, () => { callback.error && callback.error(httpRequest) });
            httpRequest.once(Laya.Event.COMPLETE, this, () => { callback.complete && callback.complete(httpRequest) });
        }
        httpRequest.send("https://r.94xj.net/e", arg, "post", "json", ["Content-Type", "application/json"]);
    }
    public static ErrorReport() {
        let arg = {
            "code": 1003,
            "msg": "invalid code",
            "user_id": 0,
            "game": "parkourrace",
            "type": "backend",
            "platform": "weixin"
        };
        this.errorRequest(arg,
            {
                complete: (request: Laya.HttpRequest) => {
                },

                error: (request: Laya.HttpRequest) => {

                }
            })
    }

}