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 MsgPanel from './msgPanel/MsgPanel';
import GameScene from './gameScene/GameScene';
import RevivePanel from './revivePanel/RevivePanel';
import OverPanel from './overPanel/OverPanel';
import OutWinPanel from './outWinPanel/OutWinPanel';
import OutNoTimesPanel from './outNoTimesPanel/OutNoTimesPanel';
import RecheckPanel from './recheckPanel/RecheckPanel';
import PrizePanel from './prizePanel/PrizePanel';
import NoPrizePanel from './PrizePanel/NoPrizePanel';
import GuidePanel from './guidePanel/GuidePanel';
import StartScene from './startScene/StartScene';
import { NetPromise } from './NetPromise';
import RedScene from './redScene/RedScene';
import PubPanel from './pubPanel/PubPanel';
import Toast from './alert/Toast';
import SelectKhPanel from './selectKhPanel/SelectKhPanel';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import { ABNetManager } from '../libs/tc/manager/ABNetManager';
import TaskTipsPanel from './taskTipsPanel/TaskTipsPanel';
import { NetName } from '../libs/tw/enum/NetName';

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

        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        // Buried.init();

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

        SceneCtrl.instance.registerSceneClass(ModuleTypes.GAME_SCENE, GameScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, Toast);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.RED_SCENE, RedScene);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GUIDE_PANEL, GuidePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.REVIVE_PANEL, RevivePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.OVER_PANEL, OverPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.OUTWIN_PANEL, OutWinPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.OUTNOTIMES_PANEL, OutNoTimesPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RECHECK_PANEL, RecheckPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.NOPRIZE_PANEL, NoPrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PUB_PANEL, PubPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SELECTKH_PANEL, SelectKhPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TASKTIPS_PANEL, TaskTipsPanel);

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

    private async runGame() {
        await this.loadResource()
        GDispatcher.addEvent(ABNetManager.ERROR, this.onError, this)
        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, null, null, msg);

        } else {
            NetPromise.ins.showToast('网络开小差了\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 {
        //获取游戏信息
        Buried.init();

        console.log("isNotLoginUser")
        console.log(NetPromise.ins.getCookie("isNotLoginUser"))

        /* if(NetPromise.ins.getCookie("isNotLoginUser")=="true"){
            NetPromise.ins.not_login=false;
        } */

        try{
            let location = window["App"].getLocation();
        }catch(e){}
      
        //纬度范围
        let latitudeScope = [30.40, 31.54]
        //经度范围
        let longitudeScope = [120.51, 122.12]

        //120度51分至122度12分，北纬30度40分至31度53

        //纬度
        let latitude = window["latitude"];
        //经度
        let longitude = window["longitude"];

        console.log("latitude", latitude)
        console.log("longitude", longitude)
        //31.24
        //121.50
        //alert(`经度：${latitude},纬度：${longitude}`)
        if (latitude >= latitudeScope[0] && latitude <= latitudeScope[1] && longitude >= longitudeScope[0] && longitude <= longitudeScope[1]) {
            console.log("是上海")
            NetPromise.ins.isShanghai = true
        } else {
            NetPromise.ins.isShanghai = false
        }

        NetPromise.ins.getProjectUserInfo()
            .then(() => {
                console.log("DataManager.ins.getData(NetName.getProjectUserInfo)")
                console.log(DataManager.ins.getData(NetName.getProjectUserInfo).data.loginJs)
                window["$"]("body").append(DataManager.ins.getData(NetName.getProjectUserInfo).data.loginJs)

                if (this.getCookie("isNotLoginUser")=="true") {
                    if (window['requirelogin']) {
                        window['requirelogin']();
                    }
                }




                // window["$"]("body").append(`<script>
                // function requirelogin(){
                //            loginForComm("http://activity.m.duibatest.com.cn/customActivity/cmbc/shanghai/auto/login", "http://activity.m.duibatest.com.cn/customActivity/cmbc/shanghai/auto/login"); 
                // }
                // function loginForComm(beforeUrl,toUrl){
                //     var p = {
                //             'beforeUrl':beforeUrl,  //跳转失败地址
                //             'toUrl':toUrl   //跳转地址
                //         };
                //     cmbcParams = p;
                //     setWebitEvent("setFuncParams()", "loginForComm");
                // }
                // </script>`)

                NetPromise.ins.gotoIndex()
            })
            .catch(() => {
                NetPromise.ins.gotoIndex()
            })

    }

    getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

        if (arr = document.cookie.match(reg))

            return unescape(arr[2]);
        else
            return null;
    }

    private onError(net: any, desc: any, result): void {
        /*  console.log(desc);
         console.log(result); */
        var msg: string;
        var msgArr: any = window['errorMessage'];
        if (!isNaN(desc)) {
            msg = msgArr[desc] ? msgArr[desc] : '活动太火爆了，请稍后再来～';
        } else {
            msg = desc;
        }

        var code;

        if (result) {
            code = result.code;
        }

        console.log("net")
        console.log(net)

        //let ss= `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=39.984154,116.307490&key=c9f96da1767b93ef5e370c2f7708561e&radius=1000&extensions=base`

        if (code == -1004 || code == -1006 || code == -1007 || code == -1008 || code == -1009 || code == "600032") {
            // this.showToast("接口繁忙，稍等片刻重试~");
        } else if (code == "100001") {
            //100009 不允许openBs访问
            //100001 Duiba未登录
            NetPromise.ins.not_login = false;
            NetPromise.ins.showToast("登陆后才能参加活动！");
        } else if (code == "2002007013" || code == "600033") {
            GDispatcher.dispatchEvent("updatePetText", code)
        } else {
            if (msg) {
                NetPromise.ins.showToast(msg);
            } else {
                NetPromise.ins.showToast("活动太火爆了，请稍后再来～");
            }
        }
    }
}

window['Main'] = Main;