
import { DataManager } from './../libs/tw/manager/DataManager';
import { ResGroupNameArr } from './consts/ResConst';
import { NetPromise } from './promises/NetPromise';
import { GDispatcher } from './../libs/tc/util/GDispatcher';
import { ABNetManager } from './../libs/tc/manager/ABNetManager';
import { INetData } from './../libs/tc/interface/INetData';
import MainBase from "../libs/tl/MainBase";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import { ModuleTypes } from "./types/ModuleTypes";
import Msg from "./pops/msg/Msg";
import GameConst from './consts/GameConst';

import Waiting from './waiting/Waiting';
import SVGACtrl from './ctrls/svgaCtrl';
import PrizePanel from './pops/prizePanel/PrizePanel';
import MainScene from './scenes/MainScene';
import ToastCtrl from './ctrls/toastCtrl';
import NoPrizePanel from './pops/prizePanel/NoPrizePanel';
import RulePanel from './pops/rule/RulePanel';

class Main extends MainBase {

    protected registerModules() {
        super.registerModules();

        // 注册所有Panel
        PanelCtrl.instance.registerClass(ModuleTypes.MSG_PANEL, Msg);
        PanelCtrl.instance.registerClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerClass(ModuleTypes.NOPRIZE_PANEL, NoPrizePanel);
        // 注册所有Scene
        SceneCtrl.instance.registerClass(ModuleTypes.MAIN_SCENE, MainScene);

        // NetManager.ins.onNotSuccess = (msg) => {
        //     showAlertPanel(msg)
        // }
    }

    // 获取数据
    protected async getData() {
        super.getData();
        DataManager.ins.customCfgData = window['CFG']
    }

    // 设置派发事件
    protected GDispatchEvent() {
        // 侦听接口错误  弹错误弹窗
        GDispatcher.addEvent(ABNetManager.ERROR, (net: INetData, msg = '') => {
            const msgData = {
                net: net,
                msg: msg,
            };
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData)
        }, this);

        // 监听当预加载资源加载完毕
        GDispatcher.addEvent('PreloadLoaded', () => {
            Waiting.instance.show()

            // this.createGameScene()
        }, this);
        GDispatcher.addEvent('PlayLoaded', () => {
            // Waiting.instance.hide()

        }, this);
    }

    loadSvga() {
        return new Promise(async (r) => {

            //     await Promise.all([
            //     ])
            //         .then(() => {
            r();
            //         })
            //         .catch(() => {
            //             PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { msg: "网络异常，请稍后再试~", title: "很遗憾", type: "reload" })
            //         })


        })
    }

    onResourceLoadComplete(event) {


        for (let i = 0; i < ResGroupNameArr.length; i++) {
            if (event.groupName == ResGroupNameArr[i]) {
                // debugger
                // this.loadBg("startBg.png");
                GDispatcher.dispatchEvent(`${ResGroupNameArr[i]}Loaded`);
                window[`is${ResGroupNameArr[i]}Loaded`] = true;
                if (i <= ResGroupNameArr.length - 2) {
                    this.trace(`${ResGroupNameArr[i]}组加载完成`);
                    RES.loadGroup(ResGroupNameArr[i + 1]);
                    this.trace(`开始加载${ResGroupNameArr[i + 1]}资源`);
                } else if (i == ResGroupNameArr.length - 1) {
                    this.trace(`${ResGroupNameArr[i]}组加载完成`);
                    GameConst.stage = this.stage;
                    this.loadSvga()
                        .then(() => {
                            console.log("svga加载完成");

                            window['allLoaded'] = true

                            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
                            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
                            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);

                            this.createGameScene()
                        })
                        .catch(e => {
                            console.error(e);

                        })
                    setTimeout(() => {
                        console.log(GameConst.stage.width, GameConst.stage.height)
                    }, 100);
                }
            }
        }
    }


    // 创建游戏场景
    protected async createGameScene() {
        super.createGameScene();
        //获取UA信息
        GameConst.userAgent = navigator.userAgent.toLowerCase();
        console.log(GameConst.userAgent);

        GameConst.stage = this.stage;
        setTimeout(() => {
            console.log(GameConst.stage.width, GameConst.stage.height)
        }, 100);

        // 开始计时停留时长
        // initstatistics();

        NetPromise.getRemainTimes()
            .then(() => {
                return NetPromise.getPrizeInfo()
            })
            .then(() => {
                return NetPromise.queryAllUserRecords([1])
            })
            .then(() => {
                Waiting.instance.hide()

                SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);

            })
            .catch((e) => {
                console.error(e);
                Waiting.instance.hide()
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { msg: "网络异常，请刷新重试~", type: "reload" })
            })
    }

    /**
     * 资源组加载出错
     */
    protected onResourceLoadError(event: RES.ResourceEvent): void {
        this.trace("preload组加载失败");
        //忽略加载失败的项目
        this.onResourceLoadComplete(event);
    }

}

window['Main'] = Main;


egret.runEgret({
    renderMode: "webgl", audioType: 0, calculateCanvasScaleFactor: function (context: any) {
        var backingStore = context.backingStorePixelRatio ||
            context.webkitBackingStorePixelRatio ||
            context.mozBackingStorePixelRatio ||
            context.msBackingStorePixelRatio ||
            context.oBackingStorePixelRatio ||
            context.backingStorePixelRatio || 1;
        return (window.devicePixelRatio || 1) / backingStore;
    }
});