import { NetManager } from './../../libs/tw/manager/NetManager';
import { Buried } from './../../libs/tw/util/Buried';
import { GDispatcher } from '../../libs/tc/util/GDispatcher';
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";
export default class LoadingScene extends Scene {
    get skinKey() { return 'Loading' }

    public bg: eui.Image;
    public title1: eui.Image;
    public title2: eui.Image;
    public title3: eui.Image;
    public star1: eui.Image;
    public star2: eui.Image;
    public star3: eui.Image;
    public star4: eui.Image;
    public star5B: eui.Image;
    public star5: eui.Image;
    public star5F: eui.Image;
    public loadingBar: eui.ProgressBar;
    public startBtn: eui.Button;

    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 booksPrecent: number = 0;
    public peoplePrecent: number = 0;
    public bigImagePrecent: number = 0;
    public loadingTW: any;
    public targetValue: number = 0;

    start() {

        egret.Tween.removeAllTweens();

        if (this.loadingBar) {
            this.loadingBar.value = 0;
            this.loadingBar['progressNum'].text = `${Math.ceil(this.loadingBar.value)}%`;

        }

        console.log(`isInApp:${window['isInApp']}`)
        // 初始化埋点信息
        this.initBuired();
        // 初始化标题动画
        this.initTitleAni();
        // 初始化星星动画
        this.initStarAni();
        // 初始化粒子效果
        this.initSprite();
        // 侦听视频能否播放
        this.video.addEventListener('canplay', this.onVideoCanPlay.bind(this));
        this.checkInterval = setInterval(() => {
            this.checkAllResLoaded();
        }, 500)

    }

    // 初始化埋点信息
    initBuired() {
        Buried.init();

        if (window['isInApp']) {
            // 端内
            let loadingDpmIn = Buried.connectDpm(110, 1, 1); // 点击埋点   
            let loadingDcmIn = Buried.connectDcm(202, 0, 0); // 曝光埋点
            this.loadingExposure = Buried.createExposure(loadingDpmIn, loadingDcmIn);

        } else {
            // 端外
            let loadingDpmOut = Buried.connectDpm(110, 10, 1); // 点击埋点   
            let loadingDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
            this.loadingExposure = Buried.createExposure(loadingDpmOut, loadingDcmOut);
        }

        NetManager.ins.showLog(this.loadingExposure);

    }

    // 初始化标题动画
    initTitleAni() {
        this.title1.alpha = 0;
        this.title2.alpha = 0;
        this.title3.alpha = 0;
        let title1TW = egret.Tween.get(this.title1);
        title1TW.to({ alpha: 1 }, 1200).call(() => {
            let title2TW = egret.Tween.get(this.title2);
            title2TW.to({ alpha: 1 }, 1200).call(() => {
                let title3TW = egret.Tween.get(this.title3);
                title3TW.to({ alpha: 1 }, 1200).call(() => {
                    this.isAniEnd = true;
                    this.checkAllResLoaded();
                })
            })
        })
    }

    // 初始化星星动画
    initStarAni() {
        for (let i = 1; i <= 5; i++) {
            let tempY = this[`star${i}`].y;
            let starTW = egret.Tween.get(this[`star${i}`], { loop: true });
            starTW.wait(2000 * Math.random()).call(() => {
                let starTW2 = egret.Tween.get(this[`star${i}`], { loop: true });
                starTW2.to({ y: tempY - 15 }, 1200).to({ y: tempY + 15 }, 2400).to({ y: tempY }, 1200)
            })
        }
    }

    // 初始化粒子效果
    initSprite() {
        for (let i = 0; i < 25; i++) {
            let sprite = new eui.Image();
            sprite.source = `upSprite${[1, 2][Math.round(Math.random())]}_png`;
            sprite.anchorOffsetX = sprite.width / 2;
            sprite.anchorOffsetY = sprite.height / 2;
            sprite.rotation = 360 * Math.random();
            let scale = Math.max(Math.random() * 0.8, 0.5);
            sprite.scaleX = scale;
            sprite.scaleY = scale;
            sprite.x = Math.max(Math.min(750 * Math.random(), 700), 50 + [1, -1][Math.round(Math.random())] * 20 * Math.random());
            sprite.y = 150 + 800 * Math.random();
            let targetY = Math.max(Math.abs(sprite.y - 500 * Math.random()), 150);
            this.addChild(sprite);
            let spriteTW = egret.Tween.get(sprite);
            spriteTW.to({ y: targetY }, Math.max(Math.random() * 10000, 5000)).call(() => {
                this.removeChild(sprite);
            })
        }
        for (let i = 0; i < 60; i++) {
            let sprite = new eui.Image();
            sprite.source = `upSprite${[1, 2][Math.round(Math.random())]}_png`;
            sprite.anchorOffsetX = sprite.width / 2;
            sprite.anchorOffsetY = sprite.height / 2;
            sprite.rotation = 360 * Math.random();
            let scale = Math.max(Math.random() * 0.8, 0.5);
            sprite.scaleX = scale;
            sprite.scaleY = scale;
            sprite.x = Math.max(Math.min(750 * Math.random(), 700), 50);
            sprite.y = 150 + 800 * Math.random();
            sprite.alpha = 0;
            let targetY = Math.max(Math.abs(sprite.y - 500 * Math.random()), 150 + 50 * Math.random());
            this.addChild(sprite);
            let spriteTW = egret.Tween.get(sprite, { loop: true });
            spriteTW.wait(7000 * Math.random()).to({ alpha: 1 }, 1).to({ y: targetY }, Math.max(Math.random() * 10000, 5000))
        }

        this.addChild(this.title1);
        this.addChild(this.title2);
        this.addChild(this.title3);
        this.addChild(this.star1);
        this.addChild(this.star2);
        this.addChild(this.star3);
        this.addChild(this.star4);
        this.addChild(this.star5);
        this.addChild(this.star5F);
        this.addChild(this.loadingBar);
    }

    // 侦听事件
    initEvents() {
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_StartBtn, this);
    }

    removeEvents() {
        RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_StartBtn, this);

    }

    // preload资源组加载进度
    onResourceProgress(event: RES.ResourceEvent): void {
        if (event.groupName == "Normal") {
            this.normalPrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "Books") {
            this.booksPrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "People") {
            this.peoplePrecent = event.itemsLoaded / event.itemsTotal * 100;
        } else if (event.groupName == "BigImage") {
            this.bigImagePrecent = event.itemsLoaded / event.itemsTotal * 100;
        }


        if (!this.isVideoCanPlay) {
            // 视频未加载完毕时，只让进度条到70%
            if (this.loadingBar) {
                this.loadingTW = egret.Tween.get(this.loadingBar, { onChange: this.onLoadingChange.bind(this) });
                this.targetValue = this.normalPrecent * 0.2 + this.booksPrecent * 0.2 + this.peoplePrecent * 0.2 + this.bigImagePrecent * 0.2;

                this.loadingTW.to({ value: this.targetValue }, 200)
                // this.loadingBar.value = ;
                // this.loadingBar['progressNum'].text = `${Math.ceil(this.normalPrecent * 0.2 + this.booksPrecent * 0.2 + this.peoplePrecent * 0.2 + this.bigImagePrecent * 0.2)}%`;
            }
        } else {
            // 视频加载完毕，让进度条到100%
            if (this.loadingBar) {
                this.loadingTW = egret.Tween.get(this.loadingBar, { onChange: this.onLoadingChange.bind(this) });
                this.targetValue = this.normalPrecent * 0.25 + this.booksPrecent * 0.25 + this.peoplePrecent * 0.25 + this.bigImagePrecent * 0.25;
                this.loadingTW.to({ value: this.targetValue }, 200)
                // this.loadingBar.value = this.normalPrecent * 0.25 + this.booksPrecent * 0.25 + this.peoplePrecent * 0.25 + this.bigImagePrecent * 0.25;
                // this.loadingBar['progressNum'].text = `${Math.ceil(this.normalPrecent * 0.25 + this.booksPrecent * 0.25 + this.peoplePrecent * 0.25 + this.bigImagePrecent * 0.25)}%`;
            }
        }
        console.log(`加载进度：${this.targetValue}`)
        if (window['isBigImageLoaded'] || window['isNormalLoaded'] || window['isBooksLoaded'] || window['isPeopleLoaded'] || this.normalPrecent * 0.25 + this.booksPrecent * 0.25 + this.peoplePrecent * 0.25 + this.bigImagePrecent * 0.25 >= 100) {
            this.checkAllResLoaded();
        }

        this.checkAllResLoaded();
    }

    onTap_StartBtn() {
        NetManager.ins.clickLog(this.loadingExposure);
        SceneCtrl.instance.change(ModuleTypes.START_SCENE);

        this.video.volume = 0.0;
        this.video.play();
        this.video.pause();
    }

    onVideoCanPlay(e) {
        window['isVideoCanPlay'] = true;
        this.checkAllResLoaded();
    }

    checkAllResLoaded() {
        if (this.isIOS()) {
            if (this.isAniEnd && window['isBigImageLoaded'] && window['isNormalLoaded'] && window['isBooksLoaded'] && window['isPeopleLoaded']) {
                clearInterval(this.checkInterval);
                if (this.loadingBar.value !== 100) {
                    let loadingTW = egret.Tween.get(this.loadingBar, { onChange: this.onLoadingChange.bind(this) });
                    loadingTW.to({ value: 100 }, 500).call(() => {
                        // SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                        this.loadingBar.visible = false;
                        this.startBtn.visible = true;
                        this.startBtn.alpha = 0.5;
                        let tw = egret.Tween.get(this.startBtn);
                        tw.to({ alpha: 1 }, 500).call(() => {
                            let tw2 = egret.Tween.get(this.startBtn, { loop: true });
                            tw2.to({ alpha: 0.8 }, 2000).to({ alpha: 1 }, 2000);
                        })
                    });
                } else {
                    // SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                    this.startBtn.visible = true;
                    this.loadingBar.visible = false;
                    this.startBtn.visible = true;
                    this.startBtn.alpha = 0.5;
                    let tw = egret.Tween.get(this.startBtn);
                    tw.to({ alpha: 1 }).call(() => {
                        let tw2 = egret.Tween.get(this.startBtn, { loop: true });
                        tw2.to({ alpha: 0.8 }, 2000).to({ alpha: 1 }, 2000);
                    })
                }
            }
        } else {
            if (this.isAniEnd && window['isNormalLoaded'] && window['isVideoCanPlay'] && window['isBigImageLoaded'] && window['isBooksLoaded'] && window['isPeopleLoaded']) {
                clearInterval(this.checkInterval);
                if (this.loadingBar.value !== 100) {
                    let loadingTW = egret.Tween.get(this.loadingBar, { onChange: this.onLoadingChange.bind(this) });
                    loadingTW.to({ value: 100 }, 500).call(() => {
                        SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                    });
                } else {
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                }
            }
        }

    }
    isIOS() {
        const u = navigator.userAgent;
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        return isiOS;
    }
    onLoadingChange() {
        if (this && this.loadingBar) {
            this.loadingBar['progressNum'].text = `${Math.ceil(this.loadingBar.value)}%`;
        }

    }

    onTap_startBtn(e) {
        SceneCtrl.instance.change(ModuleTypes.START_SCENE);
    }
}