import { sys } from "cc";

var wx=window["wx"];
var currentSDK = "1.0.2";
var gameID = 10003;
var gameName="QiangShenZhanJi";

export  class LiangLiangSDK
{
    static userID; 
    static token;
    static _ok = false;
    static _initOK = false;
    static _loginOK = false;
    static _listOK = false;
    static _config ;

    private  static _checkOK()
    {
        if(LiangLiangSDK._initOK &&LiangLiangSDK._loginOK && LiangLiangSDK._listOK )
        {
            LiangLiangSDK._ok = true;
        }
    }

    /**
     * 初始化
     * @param successcallback
     * @param failcallback 
     */
    static Init(successcallback,failcallback)
    {
        LiangLiangSDK.HttpRequest("https://www.wiseplanet.com.cn/api/getGameInfo",{"gameId": gameID,"version":currentSDK},"POST",(result)=>
        {
            console.log(result);
            LiangLiangSDK._config = result.data;

            LiangLiangSDK._initOK = true; 
            LiangLiangSDK._checkOK();
            this.Login(()=>{
                console.log("登录成功");
                this.LoadIconDataList(()=>{
                    console.log("加载互导数据成功："+this._data);
                    successcallback();
                },()=>{ 
                    console.log("加载互导数据失败");
                    successcallback();
                })
            },()=>{
                console.log("登录失败");
                failcallback();
            })
 
        },(fail)=>
        {
            console.log("fail : " + fail)
            failcallback();
        })
    }

    static Login(successcallback,failcallback)
    {
        let self = this;
        if(wx)
        {
            wx.login({
                success (res) 
                {
                    if (res.code)
                    {
                        let option=wx.getLaunchOptionsSync();
                        if(option==null){
                            throw new Error("调用 wx.getLaunchOptionsSync 获取数据为空！");
                        }
						let channelId = 0;
						if (option.query && JSON.stringify(option.query) != "{}") {
							if (option.query.channel_id) {
								channelId = Number(option.query.channel_id);
							}
						}
                        LiangLiangSDK.HttpRequest("https://www.wiseplanet.com.cn/user/login",{"gameId": gameID,"code":res.code,"channelId" : channelId},"POST",(result)=>
                        {
                            console.log(result);
                            self.userID = result.data.userId;
                            self.token = result.data.token;
                            LiangLiangSDK._loginOK = true;

                            LiangLiangSDK._checkOK();

                            successcallback();
                        },(fail)=>
                        {
                            console.log("fail : " + fail)
                            failcallback();
                        })
                    } 
                    else 
                    {
                        console.log('登录失败！' + res.errMsg)
                        failcallback();
                    }
                }
            })
        }
        else
        {
            LiangLiangSDK._loginOK = true;
            LiangLiangSDK._checkOK();
        }
    }

    static _data:any[];
    private static _errorIndex:number=0;
    private static _errorTotal:number=3;
    static LoadIconDataList(successcallback,failcallback)
    {
        this._LoadIconDataList(()=>{
            successcallback();
        },()=>{
            if(this._errorIndex<this._errorTotal){
                this.LoadIconDataList(successcallback,failcallback);
                this._errorIndex++;
            }else{
                failcallback();
            }
        });
    }

    private static _LoadIconDataList(successcallback,failcallback):void{
        if(wx!=null)
        {
            var url = "https://www.maoxingame.com/"+gameName+"/wx_server/xl_sdk_resources/xl_channel_app_config.json";
            cc.loader.load(url, function (err, data) 
            {
    
                if(err)
                {
                    console.error(err)
                    failcallback();
                }
                else
                {
                    LiangLiangSDK._listOK = true;
                    LiangLiangSDK._checkOK();
                    LiangLiangSDK._data = data;
                    successcallback();
                }
                console.log(data);
            });    
        }
        else
        {
            LiangLiangSDK._listOK = true;
            LiangLiangSDK._checkOK();
            LiangLiangSDK._data = [{
                app_id:"",
                skipIcon:true,
                name:"一个测试名字"
            }];
        }
    }

    static HttpRequest(url, data, method, success, fail)
    {
/*        if(CC_WECHATGAME1)
        {
            wx.request({
                url: url, //仅为示例，并非真实的接口地址
                data: data,
                header: {
                  'content-type': 'application/json' // 默认值
                },
                success (res) {
                  console.log(res.data)
                },
                fail(res)
                {
                    console.log("HttpRequest Fail" + res);
                }
              })
        }
        else*/
        {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    var response = xhr.responseText;
                    if (xhr.status >= 200 && xhr.status < 400) {
                        var result = {};
                        if(response)
                        {
                            try {
                                result = JSON.parse(response)
                            } catch (e) {
                                console.error('json parse error ', response)
                                if (fail)
                                    fail(e);
                            }    
                        }
                        if (success)
                            success(result);
                    } else {
                        console.error('error ', response)
                        if (fail)
                            fail(response);
                    }
                } else {
                }
            };
            xhr.timeout = 3000;
            xhr.ontimeout = function (event) {
                console.error('error ', event)
                if (fail)
                    fail(event);
            }
            xhr.open(method, url, true);
            if (method == "POST") {
                xhr.open('POST', url);
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.send(JSON.stringify(data));
            } else {
                xhr.send();
            }
        }

    }

    static object2Query(obj) 
    {
        var args = []
        for (var k in obj)
            args.push(k + "=" + obj[k])
        return args.join("&"); // 返回对象  
    }


    static CpaReport(data)
    {
        var body:any = {};
        body.gameId = gameID;
        body.token = LiangLiangSDK.token;
        body.cpaId = data.game_id
        console.log("开始上报跳转数据" + JSON.stringify(body));
        LiangLiangSDK.HttpRequest("https://www.wiseplanet.com.cn/user/cpaClick",body, "POST",()=>{}, ()=>{});
    }

    static GetList(count:number):any[]
    {
        if(!LiangLiangSDK._ok)  //如果服务器请求错误 则直接返回一个空的列表
        {
            return [];
        }
        var ret = [];
        for(var i = 0;i < count;i++)
        {
            ret.push(LiangLiangSDK._data[Math.floor(Math.random() * LiangLiangSDK._data.length * 0.99999)]);
        }
        return ret;
    }

    static CanJumpOut():boolean
    {
        if(!LiangLiangSDK._config)
        {
            return false;
        }
        if(currentSDK != LiangLiangSDK._config.version)
        {
            return false;
        }
        {
            if(!LiangLiangSDK._ok)
            {
                console.log("不允许跳转1")
                return false;
            }
            if(!LiangLiangSDK._data || LiangLiangSDK._data.length == 0)
            {
                console.log("不允许跳转2")
                return false;
            }
            console.log("允许跳转")
            return true
        }
        return false;
    }

    static CanWuChu():boolean
    {
        if(!LiangLiangSDK._config)
        {
            return false;
        }
        if(currentSDK != LiangLiangSDK._config.version)
        {
            return false;
        }
        if(!LiangLiangSDK._config.mistakeSwitch)
        {
            return false;
        }
        //上海forbidSwitch   为true
        if(LiangLiangSDK._config.forbidSwitch)
        {
            return false;
        }
        return true;
    }
}