import { Base64 } from "./Utils/Base64";

cc.Class({
    extends: cc.Component,

    properties: {
        wrap: cc.Node,
        shooter: cc.Prefab,
        inGameUI: cc.Node,
        endUI: cc.Node,
        share1UI: cc.Node,
        share2UI: cc.Node,
        waveMng: cc.Node,
        bottleMng: cc.Node, //对象池[Bottle]
        shootWrap: cc.Node, //容器[shoot]
        bottleWrap: cc.Node, //容器[Bottle]
        modeHit: cc.Node, //必中模式
        audioMng: cc.Node, //音效管理
        tMask: cc.Node,
        tButton: cc.Node,
    },

    onLoad() {
        console.log('gameInit');
        
        // cc.director.getCollisionManager().enabled = true;
        let physicsManager = cc.director.getPhysicsManager();
        physicsManager.enabled = true;
        physicsManager.enabledAccumulator = true;
        physicsManager.FIXED_TIME_STEP = 1/20;      //修改物理引擎更新步长
        // physicsManager.debugDrawFlags = 1;

        // cc.director.getCollisionManager().enabledDebugDraw = true;
        this.audioMng = this.audioMng.getComponent('AudioMng');
        this.bottleMng = this.bottleMng.getComponent('BottleMng');
        this.bottleMng.init(this);
        this.waveMng = this.waveMng.getComponent('WaveMng');
        this.waveMng.init(this);

        //UI 初始化
        this.inGameUI = this.inGameUI.getComponent('InGameUI');
        this.inGameUI.init(this);

        this.endUI = this.endUI.getComponent('EndUI');
        this.endUI.init(this);

        this.share1UI = this.share1UI.getComponent('Share1');
        this.share1UI.init(this);

        this.share2UI = this.share2UI.getComponent('Share2');
        this.share2UI.init(this);

        this.modeHit = this.modeHit.getComponent('BottleHit');
        this.modeHit.init(this);

        this.gameReviveCount = 0;
    },

    start() {
        this.gameStart()
    },

    gamePause() {
        this.waveMng.endWave();
    },

    resume() {

    },

    /**
     * 初始化箭矢
     */
    readyShooter() {
        let shooter = cc.instantiate(this.shooter)
        this.shootWrap.addChild(shooter);
        shooter.getComponent('Shooter').init(this);
    },

    resetShooter(node) {
        if(node) {
            this.delShooter(node);
        }
        this.readyShooter();
    },

    delShooter (node) {
        this.shootWrap.removeChild(node);
    },

    /**
     * 激活模式
     * @param {String} modeType 模式类型
     */
    activeMode(modeType) {
        console.log(this.gameMode, modeType);
        if (this.gameMode == modeType) {
            return
        } else {
            console.log(`=========== enterMode: ${modeType} ===========`);
            switch (modeType) {
                case 'subline':
                    this.gameMode = 'subline';
                    this.inGameUI.showSubline();
                    break;
                case 'undead':
                    this.gameMode = 'undead';
                    this.inGameUI.showUndead();
                    break;
                case 'bingo':
                    this.gameMode = 'bingo';
                    this.bingoHit = 0;      //华彩模式下必中瓶模式完成次数，最多为1
                    this.inGameUI.showBingo();
                    break;
                case 'gold':
                    this.inGameUI.addGold();
                    break;
                case 'hit':
                    this.gameMode = 'hit';
                    this.bingoHit = 1;      //华彩模式下必中瓶模式完成次数，最多为1
                    break;
                default:
                    break;
            }
        }
    },

    runHitMode (bottleType) {
        this.activeMode('hit');
        this.modeHit.startHit(bottleType);
    },

    /**
     * 重置为Normal模式
     */
    resetMode() {
        this.gameMode = 'normal';
    },

    /**
     * 游戏准备
     */
    gameReady() {
        console.log('=========== gameReady ===========');
        this.state = 'gameReady';

        this.gameMode = 'normal';
        this.tMask.active = true;
        this.tButton.active = true;
    },

    /**
     * 游戏开始
     */
    gameStart() {
        console.log('=========== gameStart ===========');
        /** 更新状态 */
        this.state = 'gameStart';
        this.gameMode = 'normal';

        /** 播放背景音乐 */
        this.audioMng.stopAll();
        this.scheduleOnce(() => {
            this.audioMng.playBgm();
        }, 0.3)

        /** 隐藏部分UI内容 */
        this.tMask.active = false;
        this.tButton.active = false;

        /** 准备箭矢 */
        this.readyShooter();

        /** 开始量产花瓶 */
        this.waveMng.startWave();
    },

    gameRestart() {
        cc.director.loadScene("Game");
        // this.gameStart()
        // this.share1UI.hide();
        // this.share2UI.hide();
        // this.endUI.hide();
    },

    gameContinue() {
        // this.waveMng.continueWave();
        
        /** 准备箭矢 */
        this.readyShooter();

        /** 重新播放背景音乐 */
        this.audioMng.playBgm();

        console.log('gameContinue');
    },

    /**
     * 游戏结束
     */
    gameOver() {
        this.audioMng.stopAll();
        this.scheduleOnce(() => {
            this.audioMng.playLose();
        }, 0.3)
        //上报游戏数据
        this.doUserReport();

        //暂停游戏
        // this.gamePause();
        
        // if (this.gameReviveCount == 0) {
        //     //第一次复活，引导分享
        //     this.share1UI.show(this.inGameUI.score)
        //     this.gameReviveCount += 1;
        // } else if (this.gameReviveCount == 1) {
        //     //第二次复活，使用复活卡，同时引导分享
        //     this.share2UI.show(this.inGameUI.score)
        //     this.gameReviveCount += 1;
        // } else if (this.gameReviveCount == 2) {
        //     //游戏结束
        //     this.state = 'gameOver';
        //     this.waveMng.endWave();
        //     this.endUI.show(this.inGameUI.score)
        // }
        if(this.gameReviveCount == 0) {
            this.share2UI.show(this.inGameUI.score)
            this.gameReviveCount += 1;
        } else if (this.gameReviveCount == 1) {
            //游戏结束
            this.state = 'gameOver';
            this.waveMng.endWave();
            this.endUI.show(this.inGameUI.score)
        }
    },

    doUserReport() {
        if(!window.Global.user) {
            return;
        }

        let postObj = {
            "coin": this.inGameUI.gold,
            "score": this.inGameUI.score,
            "uid": window.Global.user.uid
        }
        let ecData = Base64.encode(JSON.stringify(postObj))
        wx.request({
            url: Global.userReport,
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            data: {
                token: window.Global.user.token,
                uid: window.Global.user.uid,
                channel: window.Global.channel,
                os: window.Global.os,
                ver: window.Global.ver,
                ecData: ecData
            },
            success: res => {
                console.log(res);
            }
        })
    },

    doShare() {
        let shareImg = [
            'https://pub.dwstatic.com/wxgame/dwgame01/wxshare/share1.jpg',
            'https://pub.dwstatic.com/wxgame/dwgame01/wxshare/share2.jpg',
            'https://pub.dwstatic.com/wxgame/dwgame01/wxshare/share3.jpg'
        ]
        let shareText = [
            '这游戏怎么一玩上就停不下来呢！',
            '点一下~玩一年~皮肤不用一分钱！',
            `太虐了，欢乐投壶终于${this.inGameUI.score}分了！你能超过我吗？`
        ]
        let r1 = Math.floor(cc.random0To1() * 3);
        let r2 = Math.floor(cc.random0To1() * 3);
        
        if (wx) {
            wx.shareAppMessage({
                title: shareText[r1],
                imageUrl: shareImg[r2],
                query:"uid="+Global.user.uid
            })
        }
    },

    goMainPage() {
        cc.director.loadScene("MainMenu");
    },

    goFriendRank() {
        window.Global.showFriendRank = true;
        this.goMainPage();
    },

    goTotalRank() {
        window.Global.showTotalRank = true;
        this.goMainPage();
    }
    // update (dt) {},
});