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 } from './types/sceneTypes';
import { NetManager } from '../libs/tw/manager/NetManager';
import ToastPanel from './toastPanel/ToastPanel';
import StartScene1 from './startScene/StartScene';
import TopLayerCtrl from './ctrls/topLayerCtrl';
import RulePanel from './panels/RulePanel';
import PrizePanel from './panels/PrizePanel';
import ExchangeSucPanel from './panels/ExchangeSucPanel';
import LotBoxPanel from './panels/LotBoxPanel';
import NoRedMaplePanel from './panels/ShareSucPanel';
import OutOfPrizePanel from './panels/OutOfPrizePanel';
import SignSucPanel from './panels/SignSucPanel';
import SpotIntroPanel from './panels/SpotIntroPanel';
import ExMsgPanel from './panels/ExMsgPanel';
import { NetName } from '../libs/tw/enum/NetName';
import GameOverPanel from './panels/GameOverPanel';
import Scene2 from './scene2/Scene2';
import Scene3 from './scene3/Scene3';
import Scene4 from './scene4/Scene4';
import Scene5 from './scene5/Scene5';
import Scene6 from './scene6/Scene6';
import ShareSucPanel from './panels/ShareSucPanel';
import BagPanel from './panels/BagPanel';
import PrizePanel2 from './panels/PrizePanel2';
import LoadingScene from './loadingScene/LoadingScene';
import { GDispatcher } from '../libs/tc/util/GDispatcher';

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";

        DataManager.ins.getGameInfoData = {};
        window['CFG'] = {};
        if (window['isdebug']) {
            window['CFG'].projectId = '/projectx';// + '/' + window.location.pathname.split('/')[2];
        } else {
            window['CFG'].projectId = '/projectx' + '/' + window.location.pathname.split('/')[2];
        }

        window['space'] = 100;

        if (decodeURIComponent(this.getQueryString('str')) == 'app') {
            window['isresult'] = false;
        } else if (decodeURIComponent(this.getQueryString('str')) == 'weixin') {
            window['isresult'] = true;
        } else {
            window['isresult'] = false;
        }
        // GCache.init([DataManager.ins.customCfgData.actId + '', DataManager.ins.customCfgData.consumerId + '']);

        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        TopLayerCtrl.instance.init(layers.topLayer);
        Buried.init();
        Buried.appId = window['appid'] ? window['appid'] : 62244;
        Buried.oaId = window.location.pathname.split('/')[2];

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

        SceneCtrl.instance.registerSceneClass(ModuleTypes.LOADIND_SCENE, LoadingScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene1);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.SCENE2, Scene2);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.SCENE3, Scene3);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.SCENE4, Scene4);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.SCENE5, Scene5);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.SCENE6, Scene6);


        // PanelCtrl.instance.registerPanelClass(ModuleTypes.RANK_PANEL, RankPanel);
        TopLayerCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GAMEOVER_PANEL, GameOverPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHARE_SUC_PANEL, ShareSucPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL2, PrizePanel2);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.BAG_PANEL, BagPanel);

        var param = {
            "callback": 'modelRe'
        }
        // if(window['ThirdApp']){
        //     window['ThirdApp'].getNewDeviceInfo(param);
        // }

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

    // private modelRe(rpdata) {
    //     if(rpdata){
    //      window['isapp'] = true //端内
    //    }
    // }
    //获取Cookie信息
    private getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }

    /**
     * 获取url后面的参数值
     * name ：参数键值
     */
    private getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    private async runGame() {

        console.log('this.stage.innerHeight', window.innerHeight);
        console.log('this.stage.stageWidth', window.innerWidth);

        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 {
            // const loadingView = new LoadingUI();
            // this.stage.addChild(loadingView);
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
            // await RES.loadGroup("msg", 10);
            // this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        //获取游戏信息
        // Loading.instace.show();
        //进度条
        SceneCtrl.instance.change(ModuleTypes.LOADIND_SCENE);

        NetManager.ins.getDomain((success) => {
            if (!success) {
                TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: '活动太火爆了，请稍后重试~' });
                Loading.instace.hide();
                return;
            }
            window['CFG'].domainUrl = DataManager.ins.getData(NetName.GET_DOMAIN).data.activityDomain;
            if (!window['isdebug']) {
                window['CFG'].projectId = window['CFG'].domainUrl + window['CFG'].projectId;
            }

            NetManager.ins.getWechatInfo((success) => {
                let data = DataManager.ins.getData(NetName.GET_WECHAT_INFO);
                console.log('getWechatInfo', data);
                if (data.success) {
                    window['wx'] &&
                        window['wx'].config({
                            debug: false,
                            appId: data.wxappid,
                            timestamp: data.wxtimestamp,
                            nonceStr: data.wxnonceStr,
                            signature: data.wxsignature,
                            jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
                        });
                    window['wx'].ready(function () {
                        window['invokeWX']();
                    });
                }

                NetManager.ins.getInfo((success) => {

                    if (success) {

                        this.getGameRes(true);
                    } else {
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: '活动太火爆了，请稍后重试~' });
                        return;

                    }
                })
            });
        })
    }

    //加载游戏中的资源
    private async getGameRes(success: boolean) {
        if (window['isdebug']) {

            window['resPath'] = '';
        }
        if (success) {
            Buried.init();
            try {
                if (window['isresult']) {//是否直接进入结果页
                    await this.preload1();
                    SceneCtrl.instance.change(ModuleTypes.SCENE6);
                } else {
                    await this.preload();
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                }
            } catch (err) {
                if (window['isresult']) {
                    SceneCtrl.instance.change(ModuleTypes.SCENE6);
                    await this.delayload1();
                } else {
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                    await this.delayload();
                }
                return;
            }
        } else {
            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: '网络异常' });
        }

        Loading.instace.hide();
        await this.delayload();

    }

    private async preload() {
        try {
            await RES.loadGroup('common');
            await RES.loadGroup('start_scene');
            await RES.getResAsync('bg01_jpg');
            await RES.getResAsync('bg02_jpg');
            await RES.getResAsync('bg03_jpg');
            GDispatcher.dispatchEvent("PROGRESS", 0.3);
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/qt01.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/qt02.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/qt03.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/startBtn0.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/startBtn1.svga') as SVGA.EgretMovieClip;
            GDispatcher.dispatchEvent("PROGRESS", 0.6);
            await RES.getResAsync('s2Bg_jpg');
            await RES.loadGroup('scene2');
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene2/sunshine.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene2/s2Role.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene2/s2Kid.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene2/wuqi0.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene2/wuqi1.svga') as SVGA.EgretMovieClip;
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene2/wuqi2.svga') as SVGA.EgretMovieClip;
            GDispatcher.dispatchEvent("PROGRESS", 0.9);
            // await RES.getResByUrl('https://yun.duiba.com.cn/db_games/activity/music/w20191006/sound2.mp3');
            await PanelCtrl.instance.getSound('https://yun.duiba.com.cn/db_games/activity/music/w20191006/sound2.mp3', this);
            await PanelCtrl.instance.getSound('https://yun.duiba.com.cn/db_games/activity/music/w20191006/sound3.mp3', this);
            GDispatcher.dispatchEvent("PROGRESS", 1);
        } catch (error) {
            console.log('err3', error);
            // SceneCtrl.instance.change(ModuleTypes.START_SCENE);
            await this.delayload();
        }

        return new Promise((resolve) => {
            resolve();
        });
    }

    private async delayload() {
        await RES.getResAsync('s3Bg_jpg');
        await RES.loadGroup('scene3');

        await PanelCtrl.instance.getSvga('resource/assets/svga/scene3/s3svg0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene3/s3svg1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene3/s3svg2.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene3/s3svg3.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene3/s3svg4.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene3/s3svg5.svga') as SVGA.EgretMovieClip;


        await RES.getResAsync('s4Bg_jpg');
        await RES.loadGroup('scene4');

        await PanelCtrl.instance.getSound('https://yun.duiba.com.cn/db_games/activity/music/w20191006/sound4.mp3', this);
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4wuqi0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4wuqi1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4wuqi2.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4kid.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4role1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4role0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4light0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4light1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4longzi0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4longzi1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4longzi2.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4dianxin0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene4/s4dianxin1.svga') as SVGA.EgretMovieClip;


        await RES.getResAsync('s5Bg_jpg');
        await RES.loadGroup('scene5');

        await PanelCtrl.instance.getSound('https://yun.duiba.com.cn/db_games/activity/music/w20191006/sound5.mp3', this);
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene5/s5wuqi0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene5/s5wuqi1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/scene5/s5wuqi2.svga') as SVGA.EgretMovieClip;

        for (let i = 0; i < 7; i++) {
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene5/s5mv' + i + '.svga') as SVGA.EgretMovieClip;
        }

        await RES.getResAsync('s6Bg_jpg');
        await RES.loadGroup('scene6');

        let data = DataManager.ins.getData(NetName.GET_INFO).data;
        if (data.actPayload == 1) {//显示红包按钮
            if (window['isapp']) {//分享获取小食
                await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn01.svga') as SVGA.EgretMovieClip;
            } else {//点击抽取
                await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn11.svga') as SVGA.EgretMovieClip;
            }
        } else {//显示螃蟹
            if (window['isapp']) {//分享获取小食
                await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn00.svga') as SVGA.EgretMovieClip;
            } else {//点击抽取
                await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn10.svga') as SVGA.EgretMovieClip;
            }
        }

        for (let i = 0; i < 3; i++) {
            await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6mv' + i + '.svga') as SVGA.EgretMovieClip;
        }


        await RES.loadGroup('prize_panel');
        await RES.loadGroup('gameover_panel');

        return new Promise((resolve) => {
            resolve();
        });
    }

    private async preload1() {
        try {
            await RES.getResAsync('s6Bg_jpg');
            await RES.loadGroup('scene6');
            GDispatcher.dispatchEvent("PROGRESS", 0.3);
            let data = DataManager.ins.getData(NetName.GET_INFO).data;
            if (data.actPayload == 1) {//显示红包按钮
                if (window['isapp']) {//分享获取小食
                    await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn01.svga') as SVGA.EgretMovieClip;
                } else {//点击抽取
                    await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn11.svga') as SVGA.EgretMovieClip;
                }
            } else {//显示螃蟹
                if (window['isapp']) {//分享获取小食
                    await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn00.svga') as SVGA.EgretMovieClip;
                } else {//点击抽取
                    await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn10.svga') as SVGA.EgretMovieClip;
                }
            }
            GDispatcher.dispatchEvent("PROGRESS", 0.6);
            for (let i = 0; i < 3; i++) {
                await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6mv' + i + '.svga') as SVGA.EgretMovieClip;
            }
            GDispatcher.dispatchEvent("PROGRESS", 1);
        } catch (error) {
            console.log('err5', error);
            // SceneCtrl.instance.change(ModuleTypes.START_SCENE);
            await this.delayload1();
        }

        return new Promise((resolve) => {
            resolve();
        });
    }


    private async delayload1() {

        await RES.loadGroup('prize_panel');
        await RES.loadGroup('gameover_panel');

        return new Promise((resolve) => {
            resolve();
        });
    }

}



window['Main'] = Main;