
//处理微信小游戏启动逻辑
import BehaviorBase from '../framework/BehaviorBase';
import LogicUnitManager from '../framework/LogicUnitManager';
import DataModelManager from '../framework/DataModelManager';
import ConstDefine from '../model/ConstDefine';
import NetConfig from '../net/NetConfig';


export default class BootBehavior extends BehaviorBase
{
    constructor()
    {
        super('BootBehavior');
        this._configData = DataModelManager.getModel('ConfigData');
        this._questionInfoModel = DataModelManager.getModel('QuestionInfoModel');
       
    }


    // 加载游戏列表
    _loadGameList()
    {
        let self = this;
        return  new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest();

                console.log('load remote gamelist file ' + NetConfig.gamelistAddress);

                xhr["open"]('GET', NetConfig.gamelistAddress);
                xhr["onload"] = function () {
                    if (xhr["status"] == 200) {
                        resolve(JSON.parse(xhr["response"]));
                    } else {
                        reject(Error(xhr["statusText"]));
                    }
                };
                xhr["onerror"] = function () {
                    reject(Error(xhr["statusText"]));
                };

                xhr["send"]();
            })
            .catch(function(err)
            {
                console.log('load remote gamelist file failed');
                var config = {"code":0,"msg":null,"data":{"valid":true,"downloadurl":"http://47.92.175.96:90/download/","clientversion":"0","resversion":"0","ios_url":"","wxLogon":0,"isOpenCard":0,"gamelist":[{"KindID":"200","KindName":"斗地主","TypeID":"0","ModuleName":"qipai.land","ClientVersion":"101122049","ResVersion":"0","SortID":"0","KindMark":"3"},{"KindID":"389","KindName":"红中麻将","TypeID":"0","ModuleName":"yule.sparrowhz","ClientVersion":"101122049","ResVersion":"0","SortID":"0","KindMark":"3"}]}};
                return config;
                // return new Promise(function(resolve,reject){
                //     console.log('now load local config file');
                //     cc.loader.loadRes(NetConfig.localConfigAddress,function(err,json){
                //          if(err)
                //          {
                //             console.log('load local config file '+ NetConfig.localConfigAddress + "failed,err=" + err.string);
                //             reject(new Error('load local config file failed'));
                //          }
                //          else
                //          {
                //             console.log('load local config file success');
                //             resolve(json);
                //          }
                //     });
                // });
            }).then(function(cfgObj)
            { 
                console.log("gamelist:" + JSON.stringify(cfgObj))
                self._configData.setGameListData(cfgObj);

            }).catch(function(err)
            {
                console.log('load gamelist err');
                throw err;
            });
    }

    //加载游戏配置
    _loadCfg()
    {
        let self = this;
        return  new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest();

                console.log('load remote config file ' + NetConfig.configAddress);

                xhr["open"]('GET', NetConfig.configAddress);
                xhr["onload"] = function () {
                    if (xhr["status"] == 200) {
                        resolve(JSON.parse(xhr["response"]));
                    } else {
                        reject(Error(xhr["statusText"]));
                    }
                };
                xhr["onerror"] = function () {
                    reject(Error(xhr["statusText"]));
                };

                xhr["send"]();
            })
            .catch(function(err)
            {
                console.log('load remote config file failed');
                return new Promise(function(resolve,reject){
                    console.log('now load local config file');
                    cc.loader.loadRes(NetConfig.localConfigAddress,function(err,json){
                         if(err)
                         {
                            console.log('load local config file '+ NetConfig.localConfigAddress + "failed,err=" + err.string);
                            reject(new Error('load local config file failed'));
                         }
                         else
                         {
                            console.log('load local config file success');
                            resolve(json);
                         }
                    });
                });
            }).then(function(cfgObj)
            { 
                self._configData.setConfigDataObject(cfgObj);

            }).catch(function(err)
            {
                console.log('load cfg err');
                throw err;
            });
           
    }

    //加载游戏题目分类配置
    _loadLevelCfg()
    {
        let self = this;
        return  new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest();

                console.log('load level remote config file ' + NetConfig.remoteQuestionLevelAddress);

                xhr["open"]('GET', NetConfig.remoteQuestionLevelAddress);
                xhr["onload"] = function () {
                    if (xhr["status"] == 200) {
                        resolve(JSON.parse(xhr["response"]));
                    } else {
                        reject(Error(xhr["statusText"]));
                    }
                };
                xhr["onerror"] = function () {
                    reject(Error(xhr["statusText"]));
                };

                xhr["send"]();
            })
            .catch(function(err)
            {
                console.log('load remote level config file failed');
                return new Promise(function(resolve,reject){
                    console.log('now load local config file');
                    cc.loader.loadRes(NetConfig.localQuestionLevelAddress,function(err,json){
                         if(err)
                         {
                            console.log('load level local config file '+ NetConfig.localQuestionLevelAddress + "failed,err=" + err.string);
                            reject(new Error('load level local config file failed'));
                         }
                         else
                         {
                            console.log('load level local config file success');
                            resolve(json);
                         }
                    });
                });
            }).then(function(cfgObj)
            { 
                self._questionInfoModel.setLevelData(cfgObj);

            }).catch(function(err)
            {
                console.log('load level cfg err');
                throw err;
            });
           
    }  
    
    //打开微信小游戏界面上三个点里面的转发选项
    _openShareOption()
    {
        window["wx"]["onShareAppMessage"]((function () {
            this._wxUserInfo = DataModelManager.getModel('PlayerInfoModel').getSelfWXPlayerInfo();
            var query = 'method=' + ConstDefine.MenuShareMessage.shareType + '&wxPlayerInfo=' + JSON.stringify( this._wxUserInfo);
            console.log("onShareAppMessage query:" + query);
            return {
                "title":  ConstDefine.MenuShareMessage.title,
                "imageUrl": ConstDefine.MenuShareMessage.url,
                "query": query,
                "success": function (res) {
                    console.log("onShareAppMessage succ");


                },
                "fail": function () {
                    console.log("onShareAppMessage fail");
                },
                "complete": function() {
                    console.log("onShareAppMessage complete complete");


                }
            }
        }).bind(this));
 
        window["wx"]["showShareMenu"]({
                "withShareTicket": true,
                "success": function () {
                    console.log("showShareMenu success");
                }
        });

        window["wx"]["onShow"]((function (res) {

            let urlParams = {};
            let query = res["query"] || {};
            urlParams["scene"] = parseInt(res["scene"]) || 0;
            console.log('res["scene"]:' + parseInt(res["scene"]) || 0);
            urlParams["shareTicket"] = res["shareTicket"];
            console.log('res["shareTicket"]:' + res["shareTicket"]);
            
            urlParams["query"] = res["query"];

            if(query.method != undefined && query.method!=null)
            {

                console.log('urlParams = ' + JSON.stringify(urlParams));
                DataModelManager.getModel('BootOptionData').setBootOptionData(urlParams);
                let loginLogic = LogicUnitManager.getBehavior('LoginBehavior');
                if(loginLogic)
                {
                    loginLogic.checkBoot();
                    loginLogic.checkGroupRank();
                }
        }

        }).bind(this));


        return Promise.resolve(0);
    }

    _urlParamStr(paramStr, param, decode) {
        if (!paramStr) {
            return;
        }

        decode = decode || true;
        var parts = paramStr.split('&');
        for (var i = 0; i < parts.length; i++) {
            var nv = parts[i].split('=');
            if (!nv[0]) continue;
            param[nv[0]] = nv[1] ? decode ? decodeURIComponent(nv[1]) : nv[1] : true;
        }
    }

    _getQueryFromUrl(url) {
        if (!url) {
            return "";
        }

        var queryPos = url.indexOf("?");
        return queryPos !== -1 ? url.substr(queryPos + 1) : "";
    };

    //分析微信小游戏启动参数
    _parserWechatGameBootOption()
    {
        let optionData = window["wx"]["getLaunchOptionsSync"]();
        
        if(optionData)
        { 
            let urlParams = {};
            let query = optionData["query"] || {};
            
            console.log('optionData = ' + JSON.stringify(optionData));

            let queryQRCode = {};
            let paramQRCode = query["q"];
            console.log("paramQRCode:" + paramQRCode);

            
            urlParams["scene"] = parseInt(optionData["scene"]) || 0;
            console.log('optionData["scene"]:' + parseInt(optionData["scene"]) || 0)
            urlParams["shareTicket"] = optionData["shareTicket"];
            console.log('optionData["shareTicket"]:' + optionData["shareTicket"])
            
            urlParams["contextTicket"] = optionData["contextTicket"];
            console.log('optionData["contextTicket"]:' + optionData["contextTicket"])
            
            urlParams["query"] = optionData["query"];

            console.log('urlParams = ' + JSON.stringify(urlParams));


            //console.log('optionData[]query=' + tsdk.objectInspector(optionData["query"]));
            DataModelManager.getModel('BootOptionData').setBootOptionData(urlParams);
        }
       



        return Promise.resolve(0);
    }

    onBoot()
    {
     
        //this._loadCfg();
        //this._loadLevelCfg();
        // this._loadGameList()
        console.log('BootBehavior onBoot Call');
        if(CC_WECHATGAME)
        {            
           //return this._loadCfg().then((function(ret){
               return Promise.all([this._parserWechatGameBootOption(),this._openShareOption()]);
        //    }).bind(this)).catch(function(err){
        //      console.log('error ouccur');
        //    });
          
       }
    //    else
    //    {
    //        return Promise.reject(Error('BootBehavior boot failed,because it is not in wetchatgame'));
    //    }
    }

}

window['onGameBoot'] = function()
{
    let logic = LogicUnitManager.getBehavior('BootBehavior');
    console.log('window onGameBoot');
    if(logic)
    {
        return logic.onBoot();
    }
    else
    {
        return Promise.reject(Error('onGameBoot,BootBehavior is null'));
    }
};