import HttpRequest = Laya.HttpRequest
import Event = Laya.Event;
import { AccountManager } from "./AccountManager";
import { WXSDK } from "./WXSDK";
import { Global } from "../Global";

const JtSniperApiUrl: string = "https://jtsniperapi.xwxgame.com/";

export class JtSniper {
    public static DengLu = "user/login";//用户登陆					// not token
    public static KaiShi = "game/start";//游戏开始
    public static JieShu = "game/play";//游戏结束
    public static QianDao = "sign/sign";//签到
    public static Chengjiu = "achievement/getRewards";//领取成就奖励
    public static Config = "config/table";//获取配置表
    public static FenXiang = "fission/share";//普通分享回调
    public static LiXian = "fission/offline";//获取离线奖励
    public static vd = "fission/vd";//观看视频奖励翻倍
    public static FuHuo = "game/revival";//复活
    public static gadagdag = "treasure/click";//领取点击奖励
    public static Invite = "invite/getRewards";//领取邀请奖励
    public static Lottery = "lottery/lottery";//抽奖
    public static ShareGetSkin = "theme/fission";//分享/看视频得皮肤
    public static WearEquip = "theme/equip";//装备皮肤
    public static BuyEquip = "theme/buy";//购买装备
    public static ShouQuan = "user/auth";//用户授权
    public static JinBi = "user/sync";//金币同步
};
export class ServerManager {

    constructor() { }

    private static ins: ServerManager;
    static get Instance(): ServerManager {
        if (ServerManager.ins) {
            return ServerManager.ins
        }
        else {
            return new ServerManager();
        }
    }

    //本地服务器登陆
    public Login(progresscb: Laya.Handler, completecb: Laya.Handler, errorcb: Laya.Handler): void {
        var Account = AccountManager.Instance;
        var ver = Global.VERSION;
        let Data: string = `code=${Account.code}&nickname=${Account.nickName}&avatar=${Account.avatarUrl}&gender=${Account.gender}&country=${Account.country}&province=${Account.province}&city=${Account.city}& device=${Account.device}$&share_id=${Account.share_id}&scene=${Account.scene}&v=${ver}`;

        let httpRequest = new HttpRequest();
        httpRequest.once(Event.PROGRESS, this, this.Progress, [progresscb, httpRequest]);
        httpRequest.once(Event.COMPLETE, this, this.Complete, [completecb, httpRequest]);
        httpRequest.once(Event.ERROR, this, this.Errorcb, [errorcb, httpRequest]);
        httpRequest.send(JtSniperApiUrl + JtSniper.DengLu, Data, "post", "text");
    }
    public Progress(_progresscb: Laya.Handler, _httpreq: HttpRequest) {
        if (_progresscb) {
            _progresscb.run();
        }
    }
    public Complete(_completecb: Laya.Handler, _httpreq: HttpRequest) {

        let data: JSON = JSON.parse(_httpreq.data);
        console.log(data);
        if (data["code"] != "0") {
            console.log("登录异常错误！错误信息sssssssss：", _httpreq.data["code"]);
            return;
        }
        console.log("-----------sss", data["t"]);
        AccountManager.Instance.SFSFSF = data["t"];
        this.RessetConfig(data, _completecb);
    }
    RessetConfig(data, completecb: Laya.Handler) {
        AccountManager.Instance.ReSetting(data, (flag) => {
            if (flag) {
                completecb.runWith(data);
            }
            else {
                this.RessetConfig(data, completecb);
            }
        });
    }
    public Errorcb(_errorcb: Laya.Handler, _httpreq: HttpRequest) {
        if (_errorcb != null) {
            _errorcb.runWith(_httpreq);
        }
    }

    /*
   * 通用Http Post协议发送
   * protocol 		对应“PROTOCOLS”字典中协议名称
   * hasToken		是否使用token，目前只有login协议不需要token，其他都需要token，所以此处自动组合
   * param			参数列表，key是字段名，val是值，值需要先转string
   * completecb	协议发送成功回调函数
   * errorcb		协议发送失败回调函数
   * return		返回值为void
   */
    public SendHttp(protocol: string, param: Array<{ [key: string]: string }>, completecb: Laya.Handler, errorcb: Laya.Handler, hasToken: boolean = true): void {
        let sfaasfsfa: string = "";
        let daadsads: string = JtSniperApiUrl + protocol;
        // chechk add token
        if (hasToken == true) {
            sfaasfsfa = `token=${AccountManager.Instance.curplayerData.zhengshu}&`;
        }
        //WXSDK.openload("连接网络中...");
        if (protocol == JtSniper.KaiShi || protocol == JtSniper.JieShu ||  protocol == JtSniper.vd || protocol == JtSniper.Lottery || protocol == JtSniper.ShareGetSkin ) {
            let asddsa = "abcdefghijkimnopqrstuvwxyz0123456789";
            let adsassda = "{";
            let saafsafs = "";
            for (let i = 0; i < 4; i++) {
                saafsafs += asddsa[Math.floor(Math.random() * 100) % asddsa.length];
            }
            for (let i = 0; i < param.length; i++) {
                for (let key in param[i]) {
                    adsassda += `\"${key}\":\"${param[i][key]}\"`;
                }
                if (i < param.length - 1) {
                    adsassda += ",";
                }
                else {
                    adsassda += "}";
                }
            }
            sfaasfsfa += "_r=" + saafsafs + this.SFGSGSG(adsassda);
        }
        else {
            if (param != null) {
                for (let i = 0; i < param.length; i++) {
                    for (let key in param[i]) {
                        let val: string = param[i][key];
                        sfaasfsfa += `${key}=${val}`;
                        if (i < param.length - 1) {
                            sfaasfsfa += "&";
                        }
                    }
                }
            }
        }
        let httpRequest = new HttpRequest();
        httpRequest.once(Event.COMPLETE, this, this.onHttpRequestComplete, [completecb, errorcb, httpRequest]);
        httpRequest.once(Event.ERROR, this, this.Errorcb, [errorcb, httpRequest]);
        httpRequest.send(daadsads, sfaasfsfa, "post", "text");
    }

    private onHttpRequestComplete(succeedcb: Laya.Handler, failurecb: Laya.Handler, httpRequest: HttpRequest): void {
        let data: JSON = JSON.parse(httpRequest.data);

        if (data["code"] == 0) {
            AccountManager.Instance.ReSetting(data);
            if (succeedcb != null) {
                // WXSDK.closeload();
                //console.log("上传成功回调方法 " + httpRequest.data);
                succeedcb.runWith(data);
            }
        }
        else {
            if (failurecb != null) {
                failurecb.runWith(data);
            }
            //wxsdk.openload("连接网络失败...");
            // Laya.timer.once(5000, this, () => { WXSDK.closeload(); })
            console.log("Error! Http request complete error, code: " + data["code"] + " message: " + data["message"]);
        }
    }

    private SFGSGSG(str): string {
        var c1, c2, c3;
        var SFSFFSFSFSFS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var i = 0, len = str.length, SFFSSFFS = '';
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                SFFSSFFS += SFSFFSFSFSFS.charAt(c1 >> 2);
                SFFSSFFS += SFSFFSFSFSFS.charAt((c1 & 0x3) << 4);
                SFFSSFFS += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                SFFSSFFS += SFSFFSFSFSFS.charAt(c1 >> 2);
                SFFSSFFS += SFSFFSFSFSFS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                SFFSSFFS += SFSFFSFSFSFS.charAt((c2 & 0xF) << 2);
                SFFSSFFS += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            SFFSSFFS += SFSFFSFSFSFS.charAt(c1 >> 2);
            SFFSSFFS += SFSFFSFSFSFS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            SFFSSFFS += SFSFFSFSFSFS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            SFFSSFFS += SFSFFSFSFSFS.charAt(c3 & 0x3F)
        }
        return SFFSSFFS;
    }

}