const DWTool = require('../utils/DWTool');
const ThemeManager = require("../utils/ThemeManger");
const { RoomState, GameNotificationKey } = require("../utils/GameEnum");
const GameModule = require("../utils/GameModule");

cc.Class({
    extends: cc.Component,

    properties: {
        // Public Properties

        bgNode: cc.Node,

        /** 当前显示的图片 */
        buildSprite: cc.Sprite,

        /** 柱子 */
        pillarTop: cc.Sprite,
        pillarBottom: cc.Sprite,
        pillarRight: cc.Sprite,
        pillarLeft: cc.Sprite,

        bottomBg: cc.Sprite,

        lockBtnFrames: [cc.SpriteFrame],

        /** 升级按钮的两种状态图 */
        updateBtnFrames: [cc.SpriteFrame],

        /** 未解锁状态的节点 */
        lockNode: cc.Node,

        /** 需要花费所有金币 */
        costLabel: cc.Label,

        /** 未解锁的建筑名称 */
        unLockBuildName: cc.RichText,

        /** 未解锁需要花费多少金币 */
        unlockRichText: cc.RichText,

        /** 建筑昵称 */
        buildNameLabel: cc.Label,

        /** 这里当做升级建筑按钮 */
        updateBtn: cc.Sprite,

        /** 解锁按钮 */
        lockBtn: cc.Sprite,

        /** 将要解锁建筑的类型图 */
        unlockBuildingType: cc.Sprite,

        lockBottomNode: cc.Node,

        /** 等级进度条 */
        levelProgressBar: cc.ProgressBar,

        /** 生产金币节点 */
        rateProgressNode: cc.Node,

        /** 生产金币进度条 */
        rateProgressBar: cc.ProgressBar,

        /** 生产了多少金币 */
        rateProgressLabel: cc.Label,

        /** 下一级生产多少金币 */
        nextRateLabel: cc.Label,

        /** 倒计时 */
        countdownLabel: cc.Label,

        /** 金币满了提示 */
        coinFullTip: cc.Node,

        artistListItem: cc.Prefab,

        openDoorSkeletion: sp.Skeleton,

        updateSkeletion: sp.Skeleton,

        // 显示加成的节点
        additionNode: cc.Node,

        // 显示加成倍数
        additionLabel: cc.Label,

        // 加成的骨骼
        additionSkeleton: sp.Skeleton,

        // 满级提示
        maxNode: cc.Node,

        //
        artistMan: cc.Prefab,

        // 加成倍数，默认倍率为x1，即无加成
        addition: {
            get: function () {
                if (!this._addition) {
                    this._addition = 1;
                }
                return this._addition;
            },
            set: function (value) {
                this._addition = value;
                if (this._addition === 1) {
                    this.additionNode.active = false;
                    // this.additionSkeleton.setAnimation(0, 'jiasutiao_2', true);
                    // this.rateProgressBar.barSprite.node.active = true;
                } else {
                    this.additionNode.active = true;
                    this.additionLabel.string = `X${this._addition}`;
                    // this.rateProgressBar.barSprite.node.active = false;
                }
            }
        },

        coinWrap: cc.Node,

        coinPrefab: cc.Prefab,

        _itemId: 0,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        this.setupUI();

        this.openDoorSkeletion.setCompleteListener(() => {
            // 升级建筑
            this.updateBuilding();
            GameEvent.fire(GameNotificationKey.PlaySuccessAnimation);
        });

        // 升级建筑事件
        this.updateBtn.node.on(cc.Node.EventType.TOUCH_END, () => {
            this.updateBuildingEvent();
        }, this);

        //点击解锁建筑
        let self = this;
        this.unlockBuildingEvent = _.debounce(() => {
            // 如果当前不够钱, 点击不生效
            if (GameModule.userInfo.gold < self.data.unlockScore) { return; }

            // 点完立刻隐藏
            self.lockBtn.node.active = false;

            let position = self.lockBtn.node.convertToWorldSpace(cc.v2(self.lockBtn.node.width / 2, self.lockBtn.node.height / 2));
            GameEvent.fire(GameNotificationKey.PlayUpdateCoinAnimation, position);

            self.openDoorSkeletion.setAnimation(1, "changjing_kaiqi2");

            self.lockBottomNode.runAction(cc.fadeOut(0.7));
            // this.lockBottomNode.active = false;

        }, 1000, true);

        // GameEvent.on(GameNotificationKey.StarEnterRoom, this, (starId, roomId) = > {
        //     this.refreshStarEnterRoom(starId, roomId);
        // });
    },

    refreshStarEnterRoom(starId, roomId) {
        if (this.data.roomId) {

        }
    },

    setupUI() {
        this.humanList = [];
        this.humanPool = new cc.NodePool();
        for (let i = 0; i < 5; i++) {
            let artist = cc.instantiate(this.artistMan);
            this.humanPool.put(artist);
            this.humanList.push(artist);
        }

    //     DWTool.loadResPrefab("./prefabs/levelHome/artist_man")
    //         .then((prefab) => {
    //         let human = cc.instantiate(prefab);
    //     human.getComponent('ArtistMan').init(artist);
    //     human.getComponent('ArtistMan').direction = (index > 0) ? 1 : -1;
    //     self.node.addChild(human);
    //     self.humanList.push(human);
    // });
    },

    start () {

    },

    //每帧更新数据
    update (dt) {
        if (this.data) {

            // 不断刷新界面
            this.layout(this.data);
        }
    },

    updateItem(data, itemId, resetCallback) {
        if (!isNaN(itemId)) {
            // if (this._itemId == itemId && itemId != 0) {
            //     return;
            // }
            this._itemId = itemId;
        }

        if (typeof data != 'object') {
            return;
        }

        if (resetCallback) {
            this.resetCallback = resetCallback;
        }

        this.data = data;

        this.buildNameLabel.string = `等级${data.level} ${data.name}` ;

        // ThemeManager.setBuildItemColor(this.roomId, this.bgNode);
        // this.levelProgressLabel.string = `LV.${data.level}`;

        this.refreshTheme();

        this.layout(data);

        //升级房间时不用刷新人物
        if (!isNaN(itemId)) {
            this.artistListLayout();
        }
    },

    layout(data) {
        // 判断是否有下一级, 没有的话就是满级
        if (data.hasNext === 1 && data.level <= Global.BuildingManager.getLevelCount(data.roomId)) {

            // 判断是否已经解锁
            if (data.isUnlocked) {
                let ratio = data.level % 25;
                this.levelProgressBar.progress = ratio / 25;
                //
                // this.artistList.active = true;
                let secondGold = DWTool.coinParse(data.gold * GameModule.userInfo.starMt);
                this.rateProgressLabel.string = `${secondGold}/秒`;

                let nextGold = DWTool.coinParse(data.nextGold * GameModule.userInfo.starMt);
                this.nextRateLabel.string = `${nextGold}/秒`;

                this.lockNode.active = false;
                this.costLabel.string = DWTool.coinParse(data.nextUpGold);
                // this.rate = data.rate;
                // 判断是否有足够的金额解锁
                if (GameModule.userInfo.gold >= data.nextUpGold) {
                    this.setState(RoomState.Update);
                } else {
                    this.setState(RoomState.UnLock);
                }
            } else {
                this.lockNode.active = true;
                this.costLabel.string = 0;

                this.unLockBuildName.string = `<b><color=#ffffff>${data.name}</c></b>`;
                this.unlockRichText.string = `<img src='coin_small'/><b><color=#ffffff> ${DWTool.coinParse(data.unlockScore)}</c><b/>`;

                // 判断是否有足够的金额解锁
                if (GameModule.userInfo.gold >= data.unlockScore && Global.userData.buildingLevel >= data.buildingLevel) {
                    this.unlockBuildingType.node.active = true;
                    this.lockBtn.spriteFrame = this.lockBtnFrames[1];
                    this.lockBtn.node.getComponent(cc.Button).interactable = true;
                } else {
                    this.unlockBuildingType.node.active = false;
                    this.lockBtn.spriteFrame = this.lockBtnFrames[0];
                    this.lockBtn.node.getComponent(cc.Button).interactable = false;
                }
                this.setState(RoomState.Lock);
            }

        } else {
            this.rate = data.rate;
            this.levelProgressBar.progress = 1.0;
            this.setState(RoomState.Full);

            let secondGold = DWTool.coinParse(data.gold * GameModule.userInfo.starMt);
            this.rateProgressLabel.string = `${secondGold}/秒`;
        }
    },

    //根据房间不同状态显示不同界面
    setState(state) {

        if (this.state === state) { return; }

        switch (state) {
            case RoomState.Lock:
                this.openDoorSkeletion.node.active = true;
                this.openDoorSkeletion.clearTracks();
                this.openDoorSkeletion.setToSetupPose();
                this.lockBtn.node.active = true;
                this.lockBottomNode.stopAllActions();
                this.lockBottomNode.opacity = 255;
                this.lockBottomNode.active = true;
                this.lockNode.active = true;
                this.updateBtn.node.active = false;
                this.updateBtn.spriteFrame = this.updateBtnFrames[0];
                this.updateBtn.node.getComponent(cc.Button).interactable = false;
                this.maxNode.active = false;
                break;
            case RoomState.UnLock:
                this.openDoorSkeletion.node.active = false;
                this.lockBtn.node.active = false;

                this.lockBottomNode.active = false;
                this.updateBtn.node.active = true;
                this.lockNode.active = false;
                this.updateBtn.spriteFrame = this.updateBtnFrames[0];
                this.updateBtn.node.getComponent(cc.Button).interactable = false;
                this.maxNode.active = false;
                break;
            case RoomState.Update:
                this.openDoorSkeletion.node.active = false;
                this.lockBtn.node.active = false;
                this.lockBottomNode.active = false;
                this.updateBtn.node.active = true;
                this.lockNode.active = false;
                this.updateBtn.spriteFrame = this.updateBtnFrames[1];
                this.updateBtn.node.getComponent(cc.Button).interactable = true;
                this.maxNode.active = false;
                break;
            case RoomState.Full:
                this.openDoorSkeletion.node.active = false;
                this.lockBtn.node.active = false;
                this.lockBottomNode.active = false;
                this.lockNode.active = false;
                this.maxNode.active = true;
                this.updateBtn.node.active = false;
            default:
                break;
        }
        this.state = state;
    },

    refreshTheme() {
        ThemeManager.setItemBuildSpriteFrame(this.data.roomId, this.buildSprite);
        // ThemeManager.setItemLockDownSpriteFrame(this.pillarBottom);
        let lockBottomSprite = this.lockBottomNode.getComponent(cc.Sprite);
        ThemeManager.setItemLockDownSpriteFrame(lockBottomSprite);
    },

    setListViewAdapter(listViewAdapter) {
        this._listViewAdapter = listViewAdapter;
    },

    deleteItem() {
        this._listViewAdapter.removeItem(this);
    },

    // 解锁建筑事件
    unlockBuilding() {
        this.unlockBuildingEvent();
    },

    updateBuildingEvent() {
        if (this.state === RoomState.Update) {
        //
        //     // 清空当前用来存储金币节点
        //     this.currentCoin = null;
        //     for (let i = 0; i < this.coinArrayMax; i++) {
        //         this.pickupCoin(this.coinArray[i]);
        //     }

            let position = this.updateBtn.node.convertToWorldSpace(cc.v2(this.updateBtn.node.width / 2, this.updateBtn.node.height / 2));
            GameEvent.fire(GameNotificationKey.PlayUpdateCoinAnimation, position);

            this.updateBuilding();

            // if (!this.updateSkeletion.node.active) {
            this.updateSkeletion.node.active = true;
            this.updateSkeletion.setAnimation(0, "changjing_sj");

            this.updateSkeletion.setCompleteListener(() => {
                this.updateSkeletion.node.active = false;
            });
        }
    },

    // 升级建筑
    updateBuilding() {
        // 从配置文件里获取
        let maxLevel = Global.BuildingManager.getLevelCount(this.data.roomId);
        let nextLevel = this.data.level + 1;
        let level = nextLevel > maxLevel ? maxLevel : nextLevel;
        let buildModel = Global.BuildingManager.getBuildingInfo(this.data.roomId, level);

        // this.isLevelSpeedUp(buildModel);

        // 将已有入驻的艺人赋值给新的model, 保持一个引用
        // buildModel.artists = this.buildingInfo.artists;

        if (this.resetCallback) {
            this.resetCallback(buildModel);
        }

        if (this.data.isUnlocked) {
            // 当前楼层已解锁
            GameModule.userInfo.gold -= this.data.nextUpGold;
            GameModule.userInfo.updateRecordModify(buildModel);
        } else {
            // 当前楼层未解锁
            // this.unlockBuildingRecord[this.data.roomId - 1] = 1;
            GameModule.userInfo.gold -= this.data.unlockScore;
            GameModule.userInfo.recordUnlockModify.push(buildModel);
            // 成功解锁后立刻调用上报，提交ub
            // GameModule.userInfo.doReport();

            GameEvent.fire(GameNotificationKey.UnlockLevelHome,buildModel);
        }

        // GameModule.userInfo.stars += 1;

        // this.config(buildModel, this.uid);
        this.updateItem(buildModel);

        GameEvent.fire(GameNotificationKey.RefreshBuildingData);

        // 如果满级了, 就发通知告诉userinfo
        // if (buildModel.hasNext != 1) {
            // GameEvent.fire(GameNotificationKey.LevelHomeItemBuildingFull);
        // }

        // if (buildModel.level === 1) {
            // GameEvent.fire(GameNotificationKey.LevelHomeItemUnlock);
        // }
    },

    artistListLayout() {
        for (let child of this.humanList) {
            this.humanPool.put(child);
        }

        let self = this;
        let addHuman = function (artist, index) {
            let human = null;
            if (self.humanPool.size() > 0) {
                human = self.humanPool.get();
            } else {
                human = cc.instantiate(self.artistMan);
                self.humanList.push(human);
            }
            self.node.addChild(human);
            human.getComponent('ArtistMan').init(artist);
            human.getComponent('ArtistMan').direction = (index > 0) ? 1 : -1;
        };

        if (this.data.isUnlocked && this.data.roomStars.length > 0) {

            for(let i = 0; i < this.data.roomStars.length; ++i) {
                let starId = this.data.roomStars[i];
                let artist = new Object();
                artist.nick = `周杰伦${starId}${this.data.name}`;
                artist.starId = starId;
                addHuman(artist, (Math.random() - 0.5) * 2);
            }
        }
    },

        /**
     * 升级到某个特定等级，根据配置表的金币生产速度和时间，判断是否需要弹出金币x2或者时间-50%的通知。
     */
    isLevelSpeedUp(data) {
        // if (buildingInfo.level <= 2) {
        //     return;
        // }
        //
        // if (buildingInfo.rate >= this.buildingInfo.rate * 2) {
        //     GameEvent.fire(GameNotificationKey.LevelHomeSpeedUp, buildingInfo.name, 1);
        // } else if (buildingInfo.rateUnit === this.buildingInfo.rateUnit / 2) {
        //     GameEvent.fire(GameNotificationKey.LevelHomeSpeedUp, buildingInfo.name, 2);
        // }
    },
});
