import { Buried } from './../libs/tw/util/Buried';
import { GDispatcher } from './../libs/tc/util/GDispatcher';
import { DataManager } from './../libs/tw/manager/DataManager';
import { ABNetManager } from './../libs/tc/manager/ABNetManager';
import { INetData } from './../libs/tc/interface/INetData';
import MainBase from "../libs/tl/MainBase";
import { NetManager } from "../libs/tw/manager/NetManager";
import Alert from "./alert/Alert";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import { ModuleTypes } from "./types/sceneTypes";
import RulePanel from './rulePanel/RulePanel';
import Msg from "./alert/Msg";
import GameConst, { wait, initstatistics } from './GameConst';
import Waiting from './waiting/Waiting';
import StartScene from './startScene/StartScene';
import PlayScene from './playScene/PlayScene';
import ToastCtrl from './ctrls/toastCtrl';
// import SVGACtrl from './ctrls/svgaCtrl';
import LoginPanel from './login/LoginPanel';
import GetCreditsPanel from './recordPanel/RecordPanel';
import RankPanel from './rankPanel/RankPanel';

import EndPanel from './endPanel/EndPanel';
import RecordPanel from './recordPanel/RecordPanel';
import PrizePanel from './prize/PrizePanel';
import NoPrizePanel from './prize/NoPrizePanel';
import TurnTablePanel from "./turnTablePanel/TurnTablePanel/TurnTablePanel";
import TurnTableIDouPanel from "./turnTablePanel/TurnTableIDouPanel/TurnTableIDouPanel";
import TurnTablePrizePanel from "./turnTablePanel/TurnTablePrizePanel/TurnTablePrizePanel";
import TurnTableNoPrizePanel from "./turnTablePanel/TurnTableNoPrizePanel/TurnTableNoPrizePanel";
import { iqiyi } from './NetConst';
import GetCardPanel from './cards/GetCardPanel';
import MyCardScene from './cards/MyCardScene';
import ExchangeScene from './cards/ExchangeScene';
import ExchangeCardPanel from './cards/ExchangeCardPanel';
import HongBaoPanel from './cards/HongBaoPanel';
import TurnTableTipsPanel from "./turnTablePanel/TurnTableTipsPanel/TurnTableTipsPanel";
import NoNetWorkPanel from "./NoNetWorkPanel/NoNetWorkPanel";
import ComposePanel from './cards/ComposePanel';
import TurnTableNoSharePanel from "./turnTablePanel/TurnTableTipsPanel/TurnTableNoSharePanel";

class Main extends MainBase {

    protected registerModules() {

        // 注册Toast
        ToastCtrl.instance.registerClass();
        // 注册所有Panel
        PanelCtrl.instance.registerClass(ModuleTypes.LOGIN_PANEL, LoginPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.GETCREDITS_PANEL, GetCreditsPanel)
        PanelCtrl.instance.registerClass(ModuleTypes.MSG_PANEL, Msg);
        PanelCtrl.instance.registerClass(ModuleTypes.RULE_PANEL, RulePanel);

        PanelCtrl.instance.registerClass(ModuleTypes.RANK_PANEL, RankPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.RECORD_PANEL, RecordPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerClass(ModuleTypes.NOPRIZE_PANEL, NoPrizePanel);

        PanelCtrl.instance.registerClass(ModuleTypes.GETCARD_PANEL,GetCardPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.EXCHANGECARD_PANEL,ExchangeCardPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.HONGBAO_PANEL,HongBaoPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.COMPOSE_PANEL,ComposePanel);
        //////////////////////////////////////// 大转盘 ////////////////////////////////////////
        PanelCtrl.instance.registerClass(ModuleTypes.TURNTABLE_PANEL, TurnTablePanel);
        PanelCtrl.instance.registerClass(ModuleTypes.TURNTABLE_IDOU_PANEL, TurnTableIDouPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.TURNTABLE_PRIZE_PANEL, TurnTablePrizePanel);
        PanelCtrl.instance.registerClass(ModuleTypes.TURNTABLE_NOPRIZE_PANEL, TurnTableNoPrizePanel);
        PanelCtrl.instance.registerClass(ModuleTypes.TURNTABLE_TIPS_PANEL, TurnTableTipsPanel);
        PanelCtrl.instance.registerClass(ModuleTypes.TURNTABLE_NOSHARE_PANEL, TurnTableNoSharePanel);

        PanelCtrl.instance.registerClass(ModuleTypes.NO_NETWORK_PANEL, NoNetWorkPanel);

        // // 注册所有Scene
        SceneCtrl.instance.registerClass(ModuleTypes.START_SCENE, StartScene);
        SceneCtrl.instance.registerClass(ModuleTypes.PLAY_SCENE, PlayScene);
        SceneCtrl.instance.registerClass(ModuleTypes.MYCARD_SCENE,MyCardScene);
        SceneCtrl.instance.registerClass(ModuleTypes.EXCHANGE_SCENE,ExchangeScene)
        PanelCtrl.instance.registerClass(ModuleTypes.END_PANEL,EndPanel)

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

    // 获取数据
    public updateCount: number = 0;

    protected async getData() {
        super.getData()
        //加载svga
        // let mv = await SVGACtrl.instance.load("http://yun.duiba.com.cn/db_games/activity/garbageSorting1.00/guideTips.svga");
        // let soundArr = ["numCountDown_mp3", "rightTips_mp3"]
        // preloadSound(soundArr);
    }


    // 设置派发事件
    protected GDispatchEvent() {
        GDispatcher.addEvent(ABNetManager.ERROR, (net: INetData, msg = '') => {
            const msgData = {
                net: net,
                msg: msg,
                // sureBtnTxt: TlLang.lang_011
            };
            //PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData)
        }, this);
        // 监听当预加载资源加载完毕
        GDispatcher.addEvent('PreloadLoaded', () => {
            Waiting.instance.show()
            this.createGameScene()
            //  Waiting.instance.hide()
        }, this);
        // GDispatcher.addEvent('DelayLoaded', () => {

        //     Waiting.instance.hide()
        //     this.createGameScene()
        // }, this);
    }

    protected onResourceLoadComplete(event: RES.ResourceEvent): void {
        if (event.groupName == "Preload") {
            this.trace("preload组加载完成");
            //this.trace("开始加载Normal资源");
            // this.loadBg("startBg.png");
            GDispatcher.dispatchEvent('PreloadLoaded');
            window['isPreloadLoaded'] = true;
                RES.loadGroup("startscene");
            } else if (event.groupName == "startscene") {
                this.trace("startscene组加载完成");
                this.trace("开始加载card资源");
                GDispatcher.dispatchEvent('startsceneLoaded');
                RES.loadGroup("card");
            } else if (event.groupName == "card") {
                this.trace("card组加载完成");
                this.trace("开始加载task资源");
                GDispatcher.dispatchEvent('cardLoaded');
                RES.loadGroup("task");
            }  else if (event.groupName == "task") {
                this.trace("task组加载完成");
                this.trace("开始加载chouka资源");
                GDispatcher.dispatchEvent('taskLoaded');
                RES.loadGroup("chouka");
            } else if (event.groupName == "chouka") {
                this.trace("chouka组加载完成");
                GDispatcher.dispatchEvent('choukaLoaded');
            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);
        }
    }

    // 创建游戏场景
    protected createGameScene() {
        super.createGameScene();
        //获取UA信息
        let userAgent = navigator.userAgent.toLowerCase();
        console.log(userAgent);
        GameConst.stage = this.stage;
        setTimeout(() => {
            console.log(GameConst.stage.width, GameConst.stage.height)
        }, 100);

        Buried.init();
        // 端内发接口
        iqiyi.getAllCards((ss) => {
            if (!ss) {
                // ToastCtrl.instance.show("网络异常，请重试");
                PanelCtrl.instance.show(ModuleTypes.NO_NETWORK_PANEL);
                return;
            }
            let carddata = DataManager.ins.getData("getAllCards").data;
            iqiyi.getCompletedNum((sss) => {
                if (!sss) {
                    // ToastCtrl.instance.show("网络异常，请重试");
                    PanelCtrl.instance.show(ModuleTypes.NO_NETWORK_PANEL);
                    return;
                }
                let numdata = DataManager.ins.getData("getCompletedNum").data;
                iqiyi.getTasks((ssss) => {
                    if (!ssss) {
                        // ToastCtrl.instance.show("网络异常，请重试");
                        PanelCtrl.instance.show(ModuleTypes.NO_NETWORK_PANEL);
                        return;
                    }
                    let taskdata = DataManager.ins.getData("getTasks").data;
                    console.log(GameConst.getQueryString("shareCode"))
                        if(GameConst.getQueryString("shareCode") && GameConst.getQueryString("type") == "1"){
                            iqiyi.doHelp((m)=>{
                                //huanduan
                                if(!m){
                                    // ToastCtrl.instance.show("网络异常，请重试");
                                    if(DataManager.ins.getData("doHelp").desc){
                                        ToastCtrl.instance.show(DataManager.ins.getData("doHelp").desc)
                                    }else{
                                        PanelCtrl.instance.show(ModuleTypes.NO_NETWORK_PANEL);
                                    }
                                    // return
                                }
                                history.pushState("", document.title, "//activity.m.duiba.com.cn/customActivity/iqiyi/scream/index?activityId=3737913&dbnewopen&signEnt="+GameConst.getQueryString("signEnt"));
                                console.log(document.URL);
                                iqiyi.getCollectNum((res)=>{
                                    Waiting.instance.hide();
                                    if (!ssss) {
                                        // ToastCtrl.instance.show("网络异常，请重试");
                                        PanelCtrl.instance.show(ModuleTypes.NO_NETWORK_PANEL);
                                        return;
                                    }
                                    let collectdata = DataManager.ins.getData("getCollectNum").data;
                                    let data = { carddata: carddata, numdata: numdata,collectdata:collectdata, taskdata: taskdata, taskY: false }
                                    initstatistics()
                                    SceneCtrl.instance.change(ModuleTypes.START_SCENE, data);
                                }, window["CFG"].activityId)
                                
                            }, window["CFG"].activityId, GameConst.getQueryString("shareCode"))
                        }else{
                            iqiyi.getCollectNum((res)=>{
                                Waiting.instance.hide();
                                if (!ssss) {
                                    // ToastCtrl.instance.show("网络异常，请重试");
                                    PanelCtrl.instance.show(ModuleTypes.NO_NETWORK_PANEL);
                                    return;
                                }
                                let collectdata = DataManager.ins.getData("getCollectNum").data;
                                let data = { carddata: carddata, numdata: numdata,collectdata:collectdata, taskdata: taskdata, taskY: false }
                                initstatistics()
                                SceneCtrl.instance.change(ModuleTypes.START_SCENE, data);
                            }, window["CFG"].activityId)
                            
                        }
                }, window["CFG"].activityId)
            }, window["CFG"].activityId)
        }, window["CFG"].activityId);

        //////////////////////////////////// 测试 ////////////////////////////////////
        // SceneCtrl.instance.change(ModuleTypes.START_SCENE, {numdata:0});
        //////////////////////////////////////////////////////////////////////////////
        // huanbeiNet.getTask((s) => {
        //     console.log(window['projectId'])
        //     Waiting.instance.hide()
        //     if(!s) {
        //         ToastCtrl.instance.show(`活动太火爆了，请稍后再来~`);
        //     } else {
        //         let data = DataManager.ins.getData("getTask").data;
        //         SceneCtrl.instance.change(ModuleTypes.START_SCENE, data);
        //     }

        // }, window['projectId'], false, window['pageId'])
    }

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

    isIOS() {
        const u = navigator.userAgent;
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        return isiOS;
    }

}

window['Main'] = Main;
egret.ImageLoader.crossOrigin = "anonymous";
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;
    }
});