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";
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 video: any = document.getElementById('my_video');
    public loadingExposure: any;
    public checkInterval: any;

    public normalPrecent: number = 0;
    public ydPigPrecent: number = 0;
    public cmPigPrecent: number = 0;
    public shPigPrecent: number = 0;
    public delayPrecent: number = 0;
    public loadingTW: any;
    public targetValue: number = 0;

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

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

        this.loadingBar = new ProgressBar();
        this.addChild(this.loadingBar)
        // setTimeout(() => {

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

        // }
        // 初始化埋点信息
        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);
    }

    removeEvents() {
        RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
    }

    // preload资源组加载进度
    onResourceProgress(event: RES.ResourceEvent): void {
        if (event.groupName == "Normal") {
            this.normalPrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "YdPig") {
            this.ydPigPrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "CmPig") {
            this.cmPigPrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "ShPig") {
            this.shPigPrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "Delay") {
            this.delayPrecent = event.itemsLoaded / event.itemsTotal * 100;
            if (event.itemsLoaded == event.itemsTotal) {
                window['isDelayLoaded'] = true;
            }
        }


        if (this.loadingBar) {
            // egret.Tween.removeTweens(this.loadingTW)
            this.loadingBar.value = this.targetValue;
            this.loadingTW = egret.Tween.get(this.loadingBar, { onChange: this.onLoadingChange.bind(this) });
            this.targetValue = this.normalPrecent * 0.2 + this.ydPigPrecent * 0.2 + this.cmPigPrecent * 0.2 + this.shPigPrecent * 0.2 + this.delayPrecent * 0.2;
            console.log(this.targetValue, this.loadingBar.value)
            this.loadingTW.to({ value: this.targetValue }, 100);
        }

        // if (window['isNormalLoaded'] || window['isDelayLoaded'] || this.normalPrecent * 0.5 + this.delayPrecent * 0.5 >= 100) {
        //     this.checkAllResLoaded();
        // }

        this.checkAllResLoaded();
    }

    checkAllResLoaded() {
        // console.log(`normal:${window['isNormalLoaded']},delay:${window['isDelayLoaded']}`)
        if (window['isNormalLoaded'] && window['isYdPigLoaded'] && window['isCmPigLoaded'] && window['isShPigLoaded'] && window['isDelayLoaded']) {
            if (this.loadingBar.value < 100) {
                // 进度条未满100走到100再进行下一步
                let loadingTW = egret.Tween.get(this.loadingBar, { onChange: this.onLoadingChange.bind(this) });
                loadingTW.to({ value: 100 }, 1000).call(() => {
                    this.handleLoaded();
                });
            } else {
                // 进度条已达到100 进入下一步
                this.handleLoaded();
            }
        }

    }

    //加载成功后操作
    handleLoaded() {
        GameConst.getAllPetsInfo(window['CFG'].activityId, () => {
            //查询当前宠物信息
            console.log(DataManager.ins.getData('getAllPetsInfo').data)
            let petId;
            let identifier;
            var data = DataManager.ins.getData('getAllPetsInfo').data;
            if (data.length) {
                data.forEach(pig => {
                    if (pig.petLevel < 14) {
                        petId = pig.petId;
                        identifier = pig.identifier;
                    }
                });
                if (!petId) {
                    petId = data[data.length - 1].petId;
                    identifier = data[data.length - 1].identifier;
                }
            }
            if (petId) {
                GameConst.getPetInfo(petId, (success) => {
                    if (success) {
                        window['currentPigData'] = {
                            "petId": petId,
                            "identifier": identifier,     //用来判断vip等级和猪的类型
                            "vipLevel": DataManager.ins.getData('getPetInfo').data.vipLevel,
                            "alredyReward": DataManager.ins.getData('getPetInfo').data.alredyReward,
                            "loveValue": DataManager.ins.getData('getPetInfo').data.loveValue,
                            "petLevel": DataManager.ins.getData('getPetInfo').data.petLevel,
                            "usingToys": DataManager.ins.getData('getPetInfo').data.usingToys
                        }
                        //获取签到信息
                        NetManager.ins.getSignInfo((s) => {
                            if (s) {
                                SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE);
                            }
                        }, window['signActivityId'])
                    }
                })
            }
            //出现选择页面
            else {
                SceneCtrl.instance.change(ModuleTypes.PIGTHEME_SCENE);
            }
        })
    }

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

}



// NetManager.ins.getSignInfo(
//     () => {
//         console.log(DataManager.ins.signInfoData)
//         if (DataManager.ins.signInfoData.signInfoVO.acmDay > 0) {
//             // 已经打过卡，即已领养    传入参数注意确认
//             GameConst.getAllPetsInfo(window['CFG'].activityId, () => {
//                 //查询当前宠物信息
//                 console.log(DataManager.ins.getData('getAllPetsInfo').data);
//                 let petId;
//                 let identifier;
//                 DataManager.ins.getData('getAllPetsInfo').data.forEach(pig => {
//                     if (pig.petLevel < 14) {
//                         petId = pig.petId;
//                         identifier = pig.identifier;
//                     }
//                 });
//                 if (petId) {
//                     GameConst.getPetInfo(petId, (success) => {
//                         if (success) {
//                             window['currentPigData'] = {
//                                 "petId": petId,
//                                 "identifier": identifier,     //用来判断vip等级和猪的类型
//                                 "vipLevel": DataManager.ins.getData('getPetInfo').data.vipLevel,
//                                 "alredyReward": DataManager.ins.getData('getPetInfo').data.alredyReward,
//                                 "loveValue": DataManager.ins.getData('getPetInfo').data.loveValue,
//                                 "petLevel": DataManager.ins.getData('getPetInfo').data.petLevel,
//                                 "usingToys": DataManager.ins.getData('getPetInfo').data.usingToys
//                             }
//                             SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE);
//                         }
//                     })
//                 }
//             })
//         } else {
//             // 未打过卡，即未领养宠物，让用户领养宠物
//             SceneCtrl.instance.change(ModuleTypes.PIGTHEME_SCENE);
//         }

//         // SceneCtrl.instance.change(ModuleTypes.PIGTHEME_SCENE);
//     }
//     , window['signActivityId']
// );

// NetManager.ins.getSignInfo(
//     () => {
//         console.log(DataManager.ins.signInfoData)
//         if (DataManager.ins.signInfoData.signInfoVO.acmDay > 0) {
//             // 已经打过卡，即已领养   传入参数注意确认
//             GameConst.getAllPetsInfo(window['CFG'].activityId, () => {
//                 //查询当前宠物信息
//                 console.log(DataManager.ins.getData('getAllPetsInfo').data)
//                 let petId;
//                 let identifier;
//                 DataManager.ins.getData('getAllPetsInfo').data.forEach(pig => {
//                     if (pig.petLevel < 14) {
//                         petId = pig.petId;
//                         identifier = pig.identifier;
//                     }
//                 });
//                 if (petId) {
//                     GameConst.getPetInfo(petId, (success) => {
//                         if (success) {
//                             window['currentPigData'] = {
//                                 "petId": petId,
//                                 "identifier": identifier,     //用来判断vip等级和猪的类型
//                                 "vipLevel": DataManager.ins.getData('getPetInfo').data.vipLevel,
//                                 "alredyReward": DataManager.ins.getData('getPetInfo').data.alredyReward,
//                                 "loveValue": DataManager.ins.getData('getPetInfo').data.loveValue,
//                                 "petLevel": DataManager.ins.getData('getPetInfo').data.petLevel,
//                                 "usingToys": DataManager.ins.getData('getPetInfo').data.usingToys
//                             }
//                             SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE);
//                         }
//                     })
//                 }
//             })
//         } else {
//             // 未打过卡，即未领养宠物，让用户领养宠物
//             SceneCtrl.instance.change(ModuleTypes.PIGTHEME_SCENE);
//         }

//         // SceneCtrl.instance.change(ModuleTypes.PIGTHEME_SCENE);
//     }
//     , window['signActivityId']
// );