import { GFun } from './../libs/tc/util/GFun';
import { GCache } from './../libs/tc/util/GCache';
import { Buried } from './../libs/tw/util/Buried';

import layers from "./views/layers";
import { getResPath } from "./utils";
import AssetAdapter from "./AssetAdapter";
import ThemeAdapter from "./ThemeAdapter";
import { DataManager } from "../libs/tw/manager/DataManager";
import Loading from "./loading/Loading";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import { ModuleTypes, ButtonType } from './types/sceneTypes';
import { NetManager } from '../libs/tw/manager/NetManager';
import MsgPanel from './msgPanel/MsgPanel';
import PrizePanel from './prizePanel/PrizePanel';
import WarningPanel from './warningPanel/WarningPanel';
import RulePanel from './rulePanel/RulePanel';
import RankPanel from './rankPanel/RankPanel';
import ToastPanel from './toastPanel/ToastPanel';
import TipsPanel from './tipsPanel/TipsPanel';
import OverPageScene from './overPageScene/OverPageScene';
import ResultScene from './resultScene/ResultScene';
import ResultPanel from './resultPanel/ResultPanel';
import DescribePanel from './describePanel/DescribePanel';
import StartScene from './startScene/StartScene';
import SvgaCtrl from "./ctrls/svgaCtrl";
import Panel from './views/Panel';
import StorePanel from './storePanel/StorePanel';
import HintPanel from './hintPanel/HintPanel';
import ReceivePanel from './receivePanel/ReceivePanel';
import CardPanel from './CardPanel/CardPanel';
import GetCardPanel from './CardPanel/GetCardPanel';
import RedLuckyPanel from './CardPanel/RedLuckyPanel';
import { NetName } from '../libs/tw/enum/NetName';
import NoPrizePanel from './CardPanel/NoPrizePanel';
import WritePanel from './writePanel/WritePanel';
import WXSharePanel from './WXSharePanel/WXSharePanel';
import AcceptPanel from './acceptPanel/AcceptPanel';
import NoTipsPanel from './CardPanel/NoTipsPanel';
import OppoShareCtrl from './ctrls/oppoShareCtrl';
import IosNoLoginPanel from './CardPanel/IosNoLoginPanel';


class Main extends eui.UILayer {
    protected createChildren(): void {
        super.createChildren();
        // alert(1)

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        //遇到输入框注释掉这个代码
        // egret.lifecycle.onPause = () => {
        //     egret.ticker.pause();
        // }

        // egret.lifecycle.onResume = () => {
        //     egret.ticker.resume();
        // }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());

        egret.ImageLoader.crossOrigin = "anonymous";

        //新游戏cfg
        //DataManager.ins.customCfgData = {};

        //GCache.init([DataManager.ins.customCfgData.actId + '', DataManager.ins.customCfgData.consumerId + '']);
        if (window['isDebug']) {
            window['projectId'] = 'projectx';
        } else {
            window['projectId'] = 'projectx/' + window.location.pathname.split('/')[2];
        }
        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);

        Buried.init();
        Buried.appId = window['appid'] ? window['appid'] : 69162;
        Buried.oaId = window.location.pathname.split('/')[2];

        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;

        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.CARD_PANEL, CardPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GETCARD_PANEL, GetCardPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.REDLUCKY_PANEL, RedLuckyPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.NOPRIZE_PANEL, NoPrizePanel);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.STORE_PANEL, StorePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.HITT_PANEL, HintPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RECEIVE_PANEL, ReceivePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.WRITE_PANEL, WritePanel);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.WXSHARE_PANEL, WXSharePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.ACCEPT_PANEL, AcceptPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.NOTIPS_PANEL,NoTipsPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.IOSNO_PANEL,IosNoLoginPanel);
        

        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        this.resErrorListener();
        // RES.loadGroup("msg", 10);
    }

    private resErrorListener(): void {
        //添加资源组加载失败事件
        // RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceError, this);
        // //添加资源加载失败事件
        // RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onResourceError, this);
    }

    private onResourceError(): void {
        let msg = '请刷新重试';
        // if(PanelCtrl.instance.isLoseCoin){
        //     msg = '请联系客服找回积分';
        // }else{
        //     msg = '请刷新重试';
        // }
        // console.log('isLoadedMsg' + PanelCtrl.instance.isLoadedMsg);

        if (PanelCtrl.instance.isLoadedMsg) {

            // PanelCtrl.instance.showMsg('okBtn', 4, null, null, msg);
        } else {
            alert('网络开小差了\n' + msg);
        }
    }

    private async loadResource() {
        try {
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    private async createGameScene() {
        let  channelLittle = GFun.getQueryString('signEnt');
        Buried.channelLittle = channelLittle ;
        console.log('子渠道',Buried.channelLittle);
        //let prize = GFun.getQueryString('prize');
        //获取游戏信息
        Loading.instace.show();
        if(GFun.getQueryString('shareCode') == null){
            window['loginlinkNoInApp'] =  window['loginlinkNoInApp'] + encodeURIComponent(encodeURIComponent("?signEnt="+channelLittle));
        }else{
            window['loginlinkNoInApp'] =  window['loginlinkNoInApp'] + encodeURIComponent(encodeURIComponent("?signEnt="+channelLittle) + encodeURIComponent("&shareCode="+GFun.getQueryString('shareCode')));
        }
      
        NetManager.ins.queryTaskList((success, result) => {
            if (!success && result.code != "100001") {
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: result.message })
            }
            
            NetManager.ins.getWechatInfo((successWechat, resultWeChat) => {
                let data = resultWeChat;
                ///console.log('是否分享',data)
                if (data.success) {
                    window['wx'] && window['wx'].config({
                            debug: true,
                            appId: data.wxappid,
                            timestamp: data.wxtimestamp,
                            nonceStr: data.wxnonceStr,
                            signature: data.wxsignature,
                            jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
                        });
                    window['wx'].ready(function () {
                        window['invokeWX']();
                    });
                }
                NetManager.ins.genInvite((successInvite, resultInvite) => {
                    if (!successInvite && result.code != "100001") {
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: resultInvite.message })
                    }
                    if(successInvite && resultInvite.data){
                        window['shareData'].link = this.changeURLArg(window['shareData'].link,"shareCode",resultInvite.data);
                        window['oppoShareLink'] = window['oppoShareLink'] + encodeURIComponent(encodeURIComponent('&shareCode='+resultInvite.data));
                    }
                    console.log('分享数据', window['shareData'], data,window['oppoShareLink'],window['loginlinkNoInApp']);
                })
            })
            NetManager.ins.getBaseInfo((success2, result2) => {
                if (!success2 && result.code != "100001") {
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: result2.message })
                }
                NetManager.ins.getSubscibeState((success3, result3) => {
                    let pushstatus:any = 0;
                    if (!success3 && result.code != "100001") {
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: result2.message })
                        pushstatus = 99;
                    }
                    
                    if(result3.data){
                        if(result3.data.status == 1 || result3.data.status == 0){
                            pushstatus = result3.data.status
                        }else{
                            pushstatus = 99;
                        }
                    }else{
                        pushstatus = 99;
                    }
                    
                    let data = { baseinfo: result2.data, taskinfo: result.data, pushstatus: pushstatus };
                    // if(!prize){
                        
                        SceneCtrl.instance.change(ModuleTypes.START_SCENE, data);
                    // }else{
                    //     PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL);
                    // }
                })

            })
        })
        await RES.getResAsync('prizeBoxBg_jpg');
        await RES.getResAsync('storePanelBg_jpg');
        await RES.loadGroup('card');
        await RES.loadGroup('startscene');

        await RES.loadGroup('pop');
        await RES.loadGroup('prize_panel');
        await RES.loadGroup('receive_panel');
        await RES.loadGroup('store_panel');
        await RES.loadGroup('write_panel');
        await RES.loadGroup('rule_panel');
        await RES.loadGroup('accept_panel');
        
    }
    private changeURLArg(url, arg, arg_val) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            var tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
    }
}

window['Main'] = Main;