
const GameModule = require("../utils/GameModule");
const DWTool = require("../utils/DWTool");
const Api = require('../net/Api');
const GameNotificationKey = require('../utils/GameEnum').GameNotificationKey;
// var cityList = require('../data/city');
// const BuildingModel = require('./utils/BuildingModel');
// const AlertManager = require('./utils/AlertManager');
// const ReportType = require("./utils/GameEnum").ReportType;

cc.Class({

    extends: cc.Component,

    properties: {

        _reportFailDuration: 0,
        grossIncomeLabel: cc.Label,
        grossCoin: sp.Skeleton,

        grossIncomeRichText: cc.RichText,
        rateRichText: cc.RichText,

        // rateLabel: cc.Label,

        headSprite: cc.Sprite,

        starsLabel: cc.Label,

        starsProgress: cc.ProgressBar,

        diamondLabel: cc.Label,

        // ticketLabel: cc.Label,

        //每秒点击产生的金币
        coinTap: {
            default: 1,
            visible: false,
            type: cc.Float
        },

        recordModify: [],

        recordUnlockModify: [],

        _stars: 0,
        stars: {
            get: function () {
                return this._stars;
            },
            set: function (value) {
                console.log('星星增加数 ' + value);
                this._stars = value;
                // 每5级跳动一次
                // if (value % 5 == 0) {
                //     this.updateStarAnimation();
                // }
                // let cStar = Math.floor(this._stars / 5)
                // this.starsLabel.string = cStar;
                //
                // // 把用户的星星数上报给微信
                // DWTool.submitWechatStars(cStar);

                // 更新星星数的进度条
                // this.starsProgress.progress = value % 5 == 0 ? 1 : value % 5 / 5
            }
        },

        _gold: 0,
        gold: {
            get: function () {
                return this._gold;
            },
            set: function (value) {
                this._gold = value < 0 ? 0 : parseInt(value);
                // this.grossIncomeLabel.string = DWTool.coinParse(this._gold);
                this.grossIncomeRichText.string = `<outline color=#ffffff width=3><color=#009100>${DWTool.coinParse(this._gold)}</c></outline>`;
            }
        },

        //建筑每秒自动生成的金币数
        _rateGold: 0,
        rateGold: {
            get: function () {
                return this._rateGold;
            },
            set: function (value) {
                this._rateGold = value < 0 ? 0 : parseFloat(value);
                if (this._rateGold > 0) {
                    this.rateRichText.node.active = true;
                    let text = this._rateGold * GameModule.skill.multiple * this.perpetualMt * this.starMt;
                    this.rateRichText.string = `<outline color=#ffffff width=3><color=#009100>+${DWTool.coinParse(text)}</c></outline>`;
                } else {
                    this.rateRichText.node.active = false;
                }
            }
        },

        //自动每次点击需要的秒数
        _secondClick: 0,
        secondClick: {
            get: function () {
                return this._secondClick;
            },
            set: function (value) {
                this._secondClick = value < 0 ? 0 : parseFloat(value);
                this.unschedule(this.autoClickGetGold, this);
                if (this._secondClick > 0) {
                    this.schedule(this.autoClickGetGold, this._secondClick);
                }
            }
        },

        _diamond: 0,
        diamond: {
            get: function () {
                return this._diamond;
            },
            set: function (value) {
                this._diamond = value;
                this.diamondLabel.string = this._diamond;
            }
        },

        _clickCount: 0,
        clickCount: {
            get: function () {
                return this._clickCount;
            },
            set: function (value) {
                this._clickCount = value;
            }
        },

        _buyStarCount: 0,
        buyStarCount: {
            get: function () {
                return this._buyStarCount;
            },
            set: function (value) {
                this._buyStarCount = value;
            }
        },

        //获得奖励的永久产出倍数
        perpetualMt: {
            default: 1,
            visible: false,
            type: cc.Float
        },

        //获得奖励的永久点击倍数
        perpetualClickMt: {
            default: 1,
            visible: false,
            type: cc.Float
        },

        //入驻在建筑的明星加成倍数
        starMt: {
            default: 1,
            visible: false,
            type: cc.Float
        },

        levelHomeItemFullCount: 0
    },

    onLoad() {
        GameModule.userInfo = this;
        this._rate = 0;
        this._isPlayAnimation = false;
        this.seq = 1;

        // 初始化用户信息
        this.initUserInfo();

        // 监听用户头像点击事件
        this.headSprite.node.on(cc.Node.EventType.TOUCH_END, _.debounce(() => {
            GameEvent.fire(GameNotificationKey.ShowUserInfomation, this.userInfo.uid);
        }, 1000, true), this);

        // 监听满级事件
        // GameEvent.on(NotiKey.LevelHomeItemBuildingFull, this, () => {
        //     this.levelHomeItemFullCount += 1;
        //     if (this.levelHomeItemFullCount === 5 && Global.devCityId <cityList.length) {
        //         GameEvent.fire(NotiKey.LevelHomeItemBuildingAllFull);
        //         GameEvent.fire(NotiKey.CurrentCompanyMax);
        //         // 满级立刻上报
        //         this.reportFunc();
        //     }
        // });

        // 轮询上报游戏数据
        this.reportFunc = () => {

            if (this._reportFailDuration > 0) {
                this._reportFailDuration -= 3;
                return;
            }

            this.doReport();
        };

        this.schedule(this.reportFunc, 3.0);

        //建筑每秒自动赚的钱
        this.addMoneyFunc = () => {
            this.buildingAddMoney();
        };
        this.schedule(this.addMoneyFunc, 1.0);
    },

    /**
     * 每秒增加金币
     */
    buildingAddMoney() {
        if (this.rateGold > 0) {
            this.gold += (this.rateGold * GameModule.skill.multiple * this.perpetualMt * this.starMt);
            this.secondRateTextAnimation();
        }
    },

    secondRateTextAnimation() {
        let fadeIn = cc.fadeIn(0.2);
        let delay = cc.delayTime(0.3);
        let fadeOut = cc.fadeOut(0.3);
        let action = cc.sequence(fadeIn, delay, fadeOut);
        this.rateRichText.node.runAction(action);
    },

    refreshSecondText() {
        if (this._rateGold > 0) {
            this.rateRichText.node.active = true;
            let text = this._rateGold * GameModule.skill.multiple * this.perpetualMt * this.starMt;
            this.rateRichText.string = `<outline color=#ffffff width=3><color=#009100>+${DWTool.coinParse(text)}</c></outline>`;
        } else {
            this.rateRichText.node.active = false;
        }
    },

    /**
     * 每秒自动点击次数
     */
    autoClickGetGold() {
        GameEvent.fire(GameNotificationKey.AutoClickGold);
    },

    /**
     * 上报用户数据
     */
    doReport() {
        DWTool.reportInfo(this.seq, this.gold, this.stars, this.clickCount, this.recordModify, this.recordUnlockModify)
            .then(() => {
                this._reportFailDuration = 0;
                this.recordModify = [];
                this.recordUnlockModify = [];
                this.seq += 1;
            }).catch(err => {
                if (err.code === -4) {
                    this._reportFailDuration = 60;
                }
                console.log('上报失败 ' + err.msg);
            })
    },

    /**
     * 初始化用户数据
     */
    initUserInfo() {
        let userInfo = this.userInfo = Global.userData;

        // Api.createImageFromUrl(userInfo.head, (spriteFrame) => {
        //     this.headSprite.spriteFrame = spriteFrame;
        // }, null);

        if (userInfo != undefined) {
            this.updateUserRes({
                gold: userInfo.gold,
                stars: userInfo.ogStars,
                diamond: userInfo.diamond,
                ticket: userInfo.ticket,
                clickCount: userInfo.clickCount
            });
            this.perpetualMt = parseFloat(userInfo.mt);
            this.perpetualClickMt = parseFloat(userInfo.clickMt);
            this.buyStarCount = userInfo.buyStarCount;
        }
    },

    /**
     * 更新用户资源数据
     * @param {object} data 更新资源对象
     * @param {number} data.grossIncome 增加的金币
     * @param {number} data.stars 星星
     * @param {number} data.diamond 钻石
     * @param {number} data.ticket 艺人券
     */
    updateUserRes(data) {
        console.log("Update userData: ", JSON.stringify(data));
        if (data.gold) {
            this.gold += parseInt(data.gold);
        }

        if (data.stars) {
            this.stars += parseInt(data.stars);
        }

        if (data.diamond) {
            this.diamond += parseInt(data.diamond);
        }

        if (data.ticket) {
            this.ticket += parseInt(data.ticket);
        }

        if (data.clickCount) {
            this.clickCount += parseInt(data.clickCount);
        }
    },

    /**
     * 增加星星的动画
     */
    updateStarAnimation() {

        if (this._isPlayAnimation) { return; }

        this._isPlayAnimation = true;
        let jumpHeight = 30;
        let duration = 0.2;

        let animationArray = [];
        while (jumpHeight > 0.1) {
            jumpHeight = jumpHeight - (jumpHeight / 3);
            duration = duration - (duration / 3);
            let upAction = cc.moveBy(duration, 0, jumpHeight).easing(cc.easeCubicActionOut());
            let downAction = cc.moveBy(duration, 0, -jumpHeight).easing(cc.easeCubicActionIn());
            animationArray.push(upAction);
            animationArray.push(downAction);
        }

        let callback = cc.callFunc(() => {
            this._isPlayAnimation = false;
        });

        animationArray.push(callback);
        this.starsLabel.node.runAction(cc.sequence(animationArray));
    },

    updateRecordModify(buildingInfo) {

        for (let i = 0; i < this.recordModify.length; i++) {
            let temp = this.recordModify[i];
            if (buildingInfo.roomId == temp.roomId) {
                this.recordModify.splice(i, 1, buildingInfo);
                return;
            }
        }

        this.recordModify.push(buildingInfo);
    }

});