import STAGE from "./stage";
import LAYOUT from "./view";
import { gsap } from "gsap";
import Resource from "./preload";
import utils from '@/utils/index.js';
import Matter from 'matter-js';
import decomp from 'poly-decomp';


class game {
    // 构造器
    constructor() {
        // 开始debug
        this.debug = process.env.NODE_ENV === "development" ? true : false;       // process.env !== "production", // 游戏测试模式是否开启
        // 需要显示的页面
        this.showPageIndex = 0;  // 0 loading | 1 story  | 2 rule | 3 game index | 4 result | 5 poster
        this.needUpdate = true;

        this.scene = 1;   // 1 - loading | 2 - index

        this.webGL = true;//window.deviceInfo.system == 'IOS' ? true : false;  // 是否开启webGL

        this.momentFPS = [];

        this.averageFPS = 60;  //平均帧率

        this.nowPlayingAnimation = null;  // 当前正在播放的动画

        this.playingSound = null; // 当前正在播放的声音

        this.afterResLoadedStatus = false;    // 语言资源全部加载完毕状态

        this.otherLoadedStatus = false;  // 对应语言剩余资源全部加载完毕状态

        this.langConfig = { id: 2 };  //语言配置 默认为普通话

        this.playingSounds = [];   // 将播放过的音频推入数据记录

        // 选择语言后的后置资源加载
        this.afterLoaderArr = [];

        // 备用资源加载 更多反应资源加载
        this.otherLoaderArr = [];

        this.utils = utils;

        // init Matter
        this.Matter = Matter;
        this.Engine = Matter.Engine,
            this.Render = Matter.Render,
            this.Runner = Matter.Runner,
            this.Bodies = Matter.Bodies,
            this.Composite = Matter.Composite;
        Matter.Common.setDecomp(decomp)
    }

    // 初始化
    init(pointer) {
        this.vue = pointer;
        // 初始化画布
        this.stage = new STAGE().createStage(this);
        //实例化layout
        this.VIEW = new LAYOUT(this);

        // 保存帧率
        // this.saveMomentFPS = setInterval(() => {
        //     if (this.FPS > 30)
        //         this.momentFPS.push(this.FPS)
        //     // console.log(this.momentFPS.length)
        //     if (this.momentFPS.length > 20)
        //         this.momentFPS.shift();
        // }, 10);


        // 绑定事件
        // this.bindEvents();


        // 初始化主资源加载器
        this.loadingRes();

        // 初始化物理引擎
        this.initMatterEngine();

    }

    // 开发debug模式
    devDebugMode() {

    }

    loadingRes() {
        this.loadingLoader = utils.preload({
            imgList: Resource.before.imgList,
            // audioList: Resource.main.audioList,
            loadStart: () => {
                // console.log(this.VIEW.loading_progress_bar.graphics.command.w)
            },
            progressCallBack: (progress) => {
                // progress;  // 0.99   


            },
            completeCallBack: (result) => {
                // all loaded triger
                // 初始化 loading 界面
                this.gameView = this.VIEW.loading(this);
                this.VIEW.createLoadingParticle();
                this.scene = 1;
                this.loadMainRes();
            },
        });
    }

    // 主资源
    loadMainRes() {
        this.mainLoader = utils.preload({
            imgList: Resource.main.imgList,
            // audioList: Resource.main.audioList,
            loadStart: () => {
                this.scene = 2;
                // console.log(this.VIEW.loading_progress_bar.graphics.command.w)
            },
            progressCallBack: (progress) => {
                // progress;  // 0.99
                console.log()
                gsap.to(this.VIEW.loading_progress_bar.graphics.command, {
                    w: 30 + 432 * progress,
                    duration: 0.1,
                    onUpdate: () => {

                    }
                });

                this.VIEW.loading_progress_text.text =
                    Math.floor(progress * 100) + "%";

                this.webGL && this.VIEW.loadingCacheContainer.updateCache();
            },
            completeCallBack: (result) => {
                // all loaded triger
                this.VIEW.createGamePage(this);
                setTimeout(() => {
                    this.VIEW.hideLoading();
                    this.webGL && this.VIEW.loadingCacheContainer.updateCache();
                }, 100)
                // this.mainResLoaded();
            },
        });
    }

    // 主资源加载完毕 显示首页
    mainResLoaded() {
        gsap.to([this.gameView.loading_progress_bg, this.gameView.loading_progress_bar, this.gameView.loading_text, this.gameView.loading_progress_text,], {
            alpha: 0,
            onUpdate: () => {
                this.webGL && this.VIEW.loadingCacheContainer.updateCache();
            }
        })
        gsap.fromTo(this.gameView.loading_start, { alpha: 0, scaleX: 0.95, scaleY: 0.95 }, { alpha: 1, scaleX: 1, scaleY: 1, ease: "elastic.out(1, 0.3)" })
    }


    // 求数组平均数
    getArrAverage(arr) {
        return arr.reduce((num, item, index) => {
            if (index != arr.length - 1) {
                return num + item;
            } else {
                return (num + item) / arr.length;
            }
        });
    }

    // 获取平均fps
    getAverageFPS() {
        // 计算平均帧率
        this.saveMomentFPS && clearInterval(this.saveMomentFPS)
        this.averageFPS = this.getArrAverage(this.momentFPS);
        if (this.averageFPS <= 50) {
            console.log('低等性能手机，刷新率为', this.averageFPS)
        }
        else if (this.averageFPS > 50 && this.averageFPS < 70) {
            console.log('中等性能手机，刷新率为', this.averageFPS)
        }
        else if (this.averageFPS >= 70) {
            console.log('高性能手机，高刷新率为', this.averageFPS)
        }

        // 计算出全局speed
        this.globalSpeed = 60 / this.averageFPS;
        console.log(this.globalSpeed)
    }

    // 初始化物理引擎
    initMatterEngine() {
        // create an engine 
        this.myEngine = this.Engine.create();
        this.myEngine.gravity.y = 0;
        this.myWorld = this.myEngine.world;



        // create a renderer
        this.myRender = this.Render.create({
            // element: this.vue.$refs.container,
            engine: this.myEngine,
            canvas: this.vue.$refs.matter,
            options: {
                width: 375,// 375, //window.innerWidth,
                height: 812, //812,  //window.innerHeight,
                pixelRatio: 1, // 设置像素比 window.devicePixelRatio
                background: 'transparent',
                wireframeBackground: "transparent",
                showAngleIndicator: false,
                wireframes: false,
                showDebug: false,
                showVelocity: true,
            }
        });

        // create two boxes and a ground
        // var boxA = this.Bodies.rectangle(100, 200, 80, 80);
        // var boxB = this.Bodies.rectangle(150, 50, 80, 80);
        // var boxC = this.Bodies.rectangle(150, 50, 80, 80);
        // var boxD = this.Bodies.rectangle(150, 50, 80, 80);
        // var ground = this.Bodies.rectangle(0, 800, 750, 10, { isStatic: true });


        // add all of the bodies to the world
        // this.Composite.add(this.myWorld, [boxA, boxB, boxC, boxD, ground]);

        // create runner
        this.Render.run(this.myRender);

        // run the engine
        this.myRunner = this.Runner.create();
        this.Runner.run(this.myRunner, this.myEngine);
    }

    //debug mode destroyed

    //game model
    model() {
        let M = {};
        return M
    }

    //game viewer
    view() {
        let V = {};
        let A = {};

        this.adaptY = _stage.adaptScreen();

        this.gameView = _layout.init(this, V, A);

        V.checkIPhoneX = () => {
            let windowW = window.innerWidth;
            let windowH = window.innerHeight;
            if (windowH < 1130) {

            }

            if (windowW / windowH < 0.56) {        // ios phone X  640*1386 wechat(640*1277) || 750*1624  wechat(750*1496)
                this.phoneX = true;
            } else {                                                  // ios other
                this.phoneX = false;
            }
        }
        V.checkIPhoneX();

        A.commonBtnAni = (target, callbacks) => {
            let timeline = new TimelineMax({
                onComplete: () => {
                    timeline.kill();
                    callbacks && callbacks();
                }
            });
            timeline
                .to(target, .4, { scaleX: .9, scaleY: .9 })
                .to(target, .2, { scaleX: 1, scaleY: 1 })
        }

        return {
            layout: V,
            ani: A
        };
    }

    // 静音音频
    silenceSoundInit() {
        var audioTag = document.createElement("audio");
        audioTag.controls = false;
        audioTag.preload = "auto";
        audioTag.loop = false;   // looping this seems to cause clicking on older iOS devices
        audioTag.src = silenceDataURI;
        document.addEventListener("visibilitychange", function () {
            if (document.visibilityState == 'visible') audioTag.play();
        });

        this.silenceAudio = audioTag;
    }

    // 播放音效
    playSound(musicId, spe) {
        // 移除所有声音
        // createjs.Sound.removeAllSounds();
        // 暂停上一个音频
        // console.log(this.playingSound)
        if (this.playingSound) {
            console.log('准备暂停音频=>', this.playingSound.name)
            this.playingSound.paused = true;
            this.playingSound.destroy();
        }


        console.log('准备播放音频=>', musicId)
        // let props = new createjs.PlayPropsConfig().set({
        //     interrupt: createjs.Sound.INTERRUPT_ANY,
        //     loop: 0,
        //     volume: 1
        // });
        this.playingSound = createjs.Sound.play(('sound-' + musicId));  //如果声音的最大实例数已经在播放，如何中断同一源的任何当前播放的音频实例。值在Sound类上被定义为INTERRUPT_TYPE常量
        this.playingSound.name = musicId
        // return sound
    }

    // 绑定事件
    bindEvents() {
        this.gameView.loading_start
            .on('mousedown', (e) => {
                this.silenceAudio.play();
                // createjs.Sound.play('sound-silence', { loop: -1 });
                console.log(this.vue.$BGM.paused, this.vue.$BGM.mute)
                // 如果存在背景音乐 如果音乐被暂停同时用户未静音的话
                if (this.vue.$BGM && this.vue.$BGM.paused && !this.vue.$BGM.mute) {
                    console.log('playing bgm music')
                    this.vue.$BGM.play();
                }
                this.gameView.loading_start.mouseEnabled = false;
                // console.log('点击了开始')
                // 埋点
                this.vue.$Utils.addTrackEvent("用户点击了开始", '用户loading页点击了开始');
                this.vue.$Utils.btnTouched(e.currentTarget, () => {


                    // 将canvas设置为不可交互
                    let style = this.stage.stage.canvas.className;
                    this.stage.stage.canvas.className = 'none'

                    // 初始化 view
                    this.VIEW.init();

                    // 隐藏loading
                    this.VIEW.hideLoading();
                    // 播放guide动画
                    this.changeSpriteAnimation('guide');
                    // 播放声音
                    this.playSound('guide');
                    // 显示按钮动画
                    this.vue.showLangBtnAni();
                })
            })
    }

}

export default game