import { initstatistics } from './../statistics';
import { equipmentConfig } from './../mainScene/EquipmentConfig';
import { ResGroupNameArr } from './../Main';
import { weidianNet } from './../NetConst';
import { DataManager } from './../../libs/tw/manager/DataManager';
import { NetManager } from './../../libs/tw/manager/NetManager';
import { Buried } from './../../libs/tw/util/Buried';
import Scene from "../views/Scene";
import { ModuleTypes } from "../types/sceneTypes";
import SceneCtrl from '../ctrls/sceneCtrl';
import GameConst from '../GameConst';
// import BridgeFactory from "../../libs/JSBridge/bridge/BridgeFactory";

import ProgressBar from "./ProgressBar";
import PanelCtrl from '../ctrls/panelCtrl';
import ToastCtrl from '../ctrls/toastCtrl';
import Waiting from '../waiting/Waiting';
export default class LoadingScene extends Scene {
    get skinKey() { return 'Loading' }

    public bg: eui.Image;
    public loadingBar;

    public loading: egret.tween.TweenGroup;
    public isNormalLoaded: boolean = false;
    public isVideoCanPlay: boolean = false;
    public isAniEnd: boolean = false;
    public loadingExposure: any;
    public checkInterval: any;

    public targetValue: number = 0;

    start() {
        egret.Tween.removeAllTweens();

        this.percentWidth = 100;
        this.percentHeight = 100;

        initstatistics()

        // 初始化埋点信息
        this.initBuired();

        this.checkAllResLoaded();
    }

    // 初始化埋点信息
    initBuired() {
        // const dpm = Buried.connectDpm(40, 1, 1);
        // const dcm = Buried.connectDcm(230, window['skinID'], 0);
        // this.loadingExposure = Buried.createExposure(dpm, dcm);

        // //发送曝光埋点
        // NetManager.ins.showLog(this.loadingExposure);
    }


    // 侦听事件
    initEvents() {
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    private i = 0;
    onEnterFrame() {
        this.i++;
        if (this.i % 500 == 0) {
            this.checkAllResLoaded()
        }
    }

    removeEvents() {
        RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    // preload资源组加载进度
    private proecss = 0;
    async onResourceProgress(event: RES.ResourceEvent) {
        for (let i = 2; i < ResGroupNameArr.length; i++) {
            if (event.groupName == ResGroupNameArr[i]) {
                if (event.groupName == ResGroupNameArr[ResGroupNameArr.length - 1]) {
                    if (event.itemsLoaded == event.itemsTotal) {
                        window['allLoaded'] = true;
                    }
                }

                this[`${ResGroupNameArr[i]}Precent`] = Math.round(event.itemsLoaded * 100 / (event.itemsTotal - 2))

                if (this.loadingBar && this[`${ResGroupNameArr[i]}Precent`] == 100) {
                    egret.Tween.removeTweens(this.loadingBar)
                    this.proecss += 100 / (ResGroupNameArr.length - 2);

                    this.log("loading:" + this.proecss + "%")
                    this.processAni(this.proecss);
                }
            }
        }

        this.checkAllResLoaded();
    }

    processAni(targetValue) {
        return new Promise(r => {
            egret.Tween.get(this.loadingBar)
                .to({ value: targetValue }, 330)
                .call(() => {
                    r();
                })
        })
    }

    checkAllResLoaded() {
        if (window['allLoaded']) {
            if (this.loadingBar.value < 100) {
                // 进度条未满100走到100再进行下一步
                egret.Tween.removeTweens(this.loadingBar)
                let loadingTW = egret.Tween.get(this.loadingBar);
                loadingTW.to({ value: 100 }, 1000).call(() => {
                    this.handleLoaded();
                });
            } else {
                // 进度条已达到100 进入下一步
                this.handleLoaded();
            }
        }

    }

    //加载成功后操作
    handleLoaded() {
        weidianNet.index((s) => {
            if (!s) {
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { msg: "网络异常，请刷新重试~", type: "reload" })
                return
            }
            weidianNet.getTaskInfo((ss) => {
                if (!ss) {
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { msg: "网络异常，请刷新重试~", type: "reload" })
                    return
                }

                //轮播图片
                weidianNet.exchangeList((s) => {
                    Waiting.instance.hide();
                    if (!s) {
                        ToastCtrl.instance.show("网络开小差了，再试一次吧~")
                        return
                    }
                    weidianNet.getPrize((ss) => {
                        
                        // 判断是否有店铺
                        const { hasStore } = DataManager.ins.getData("index").data;
                        if (hasStore) {
                            if(GameConst.getQueryString("shareCode")){
                                weidianNet.help(() => {
                                    weidianNet.index((ss) => {
                                        if (!ss) {
                                            Waiting.instance.hide();
                                            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { msg: "网络开小差了，再试一次吧~", type: "reload" })
                                            return
                                        }
                                        Waiting.instance.hide();
                                        weidianNet.getShopsInfo(() => {
                                            weidianNet.getFriendsInfo(() => {
                                                SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE, false);
                                            }, window['projectxId'])
                                        }, window["projectxId"])
                                    }, window['projectxId'])
                                }, GameConst.getQueryString("shareCode"),false)
                            }else{
                                weidianNet.getShopsInfo((sss) => {
                                    weidianNet.getFriendsInfo((ssss) => {
                                        SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE,false);
                                    }, window['projectxId'])
                                }, window['projectxId'])
                            }
                            
                            
                        } else {
                            SceneCtrl.instance.change(ModuleTypes.BEGIN_SCENE)
                        }
                    }, window["projectxId"])
                }, window['projectxId']);

            }, window['projectxId'])
        }, window['projectxId'])


    }

    // onLoadingChange() {
    //     if (this && this.loadingBar && this.loadingBar['progressNum']) {
    //         this.loadingBar['progressNum'].text = `加载中  ${Math.ceil(this.loadingBar.value)}%`;
    //     }
    // }

}
