// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

var Module = require('Module');

cc.Class({
    extends: cc.Component,

    properties: {

        roomPrefab: {
            default: null,
            type: cc.Prefab
        },

        earnMoneyButton: {
            default: null,
            type: cc.Button
        },

        totalMoneyLabel: {
            default: null,
            type: cc.Label
        },

        currentEarnMoneyLabel: {
            default: null,
            type: cc.Label
        },

        starCountLabel: {
            default: null,
            type: cc.Label
        },

        starNode: {
            default: null,
            type: cc.Node
        },

        friendSystemPrefab: {
            default: null,
            type: cc.Prefab
        },

        friendSystemButton: {
            default:null,
            type: cc.Button
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        Module.game = this.node;
        this.rooms = [];
        this.totalMoney = 2000;
        this.totalMoneyLabel.string = this.totalMoney.toString();
        this.currentEarnMoney = 0;
        this.starCount = 0;
        this.currentTime = 0;
        this.buyTipNode = null;
        this.loadRes();

        // 修改赚钱按钮的渲染排序的 Z 轴深度, 这样后面显示tipLabel时就可以被盖住了
        this.earnMoneyButton.node.zIndex = 1;

        this.setEventListener();
    },

    onDestroy() {
        Global.GameEvent.off("room_update", this);
    },

    // 监听事件
    setEventListener: function() {

        Global.GameEvent.on("room_update", this, (room)=>{

            this.buyTipNode = null;

            let config = room.getComponent('room').getRoomConfig();

            if (config.lv < config.price.length) {

                let price = config.price[config.lv];
                this.totalMoney -= price;
                this.totalMoneyLabel.string = this.totalMoney.toString();
                this.starCount += 1;
                this.starCountLabel.string = this.starCount.toString();

                config.lv += 1;

                room.getComponent('room').init(config, this.totalMoney);
                if (config.lv === config.price.length-1) {
                    room.getComponent('room').full();
                }
            }
        });

        Global.GameEvent.on("earn_money", this, (price)=>{

            this.totalMoney += price;
            this.totalMoneyLabel.string = this.totalMoney.toString();
        });
    },

    // 加载本地资源
    loadRes: function () {

        cc.loader.loadRes("./Config/Layout", (error, result)=>{
            if (error) {
                console.log(error);
            } else {

                let total = result["total"];

                for (let i = 1; i <= total; i++) {

                    let roomConfig = result["room" + i];
                    let roomNode = cc.instantiate(this.roomPrefab);

                    // 将当前界面上的所有建筑保存在一个数组里, 方便后续调用
                    this.rooms.push(roomNode);

                    // 添加到界面上
                    roomNode.parent = this.node;

                    // 配置room
                    roomNode.getComponent("room").init(roomConfig, this.totalMoney);
                }
            }
        });
    },

    // 点击赚钱按钮
    clickEarnMoneyButton: function () {

        let totalSpeed = 0;
        let unlockCount = 0;
        for (let i = 0; i < this.rooms.length; i++) {

            let room = this.rooms[i];
            let config = room.getComponent('room').getRoomConfig();
            let isEarnMoney = room.getComponent('room').isEarnMoney();

            if (config !== undefined && isEarnMoney) {

                unlockCount += 1;
                // 根据当前等级取赚钱速度
                let speed = config.speed[config.lv];
                totalSpeed += speed;
            }
        }

        let totalMoney = 100 * unlockCount + totalSpeed / 5;
        if (totalMoney === 0) {
            totalMoney = 100;
        }
        this.addTipLabel(totalMoney)
    },

    getBuyTipNode: function() {
        return this.buyTipNode;
    },

    setBuyTipNode: function(buyTipNode) {
        this.buyTipNode = buyTipNode;
    },

    // 添加提示
    addTipLabel: function (totalMoney) {

        let tipNode = new cc.Node("tipNode");
        let tipLabel = tipNode.addComponent(cc.Label);
        tipLabel.fontSize = 80;
        tipLabel.lineHeight = 80;
        tipLabel.string = "$" + totalMoney.toString();
        let color = new cc.Color(252, 222, 2);
        tipNode.color = color;
        this.node.addChild(tipNode, 0);
        tipNode.position = this.earnMoneyButton.node.position;

        let moveAction = cc.moveBy(0.35, cc.p(0, 200));
        let spawn = cc.spawn([moveAction, cc.fadeOut(0.35)]);

        let callBack = cc.callFunc(function () {
            this.totalMoney += totalMoney;
            this.totalMoneyLabel.string = this.totalMoney.toString();
        }, this);

        let sequence = cc.sequence(spawn, callBack);
        tipNode.runAction(sequence);
    },

    // 显示好友系统
    showFriendSystem: function() {

        let friendSystem = cc.instantiate(this.friendSystemPrefab);
        friendSystem.getComponent('FriendSystem').init(this.friendSystemButton.node.position);
        this.node.addChild(friendSystem, 2);

        friendSystem.position = this.friendSystemButton.node.position;
        friendSystem.opacity = 0;
        friendSystem.setScale(0, 0);

        let moveAction = cc.moveTo(0.35, cc.p(0, 0));
        let scaleAction = cc.scaleTo(0.35, 1.0, 1.0);
        let spawn = cc.spawn([moveAction, scaleAction, cc.fadeIn(0.4)]);

        friendSystem.runAction(spawn);
    },

    update (dt) {
        
        if (this.rooms.length > 0) {

            this.currentTime += dt;
            var earnMoneySpeed = 0;
            for (let i = 0; i < this.rooms.length; i++) {

                let room = this.rooms[i];
                let config = room.getComponent('room').getRoomConfig();
                let price = config.price[config.lv];
                let isEarnMoney = room.getComponent('room').isEarnMoney();

                if (config !== undefined && isEarnMoney) {

                    // 根据当前等级取赚钱速度
                    let speed = config.speed[config.lv];
                    earnMoneySpeed += speed;

                    if (this.totalMoney >= price) {
                        room.getComponent('room').unlockUpdate();
                    } else {
                        room.getComponent('room').lockUpdate();
                    }

                } else {

                    // 这是0级时的情况
                    if (this.totalMoney < price) {
                        room.getComponent('room').lockUpdate();
                    } else {
                        room.getComponent('room').unlockUpdate();
                    }
                }
            }

            this.currentEarnMoney = earnMoneySpeed;
            this.currentEarnMoneyLabel.string = this.currentEarnMoney + " / 秒";
        }
    },
});
