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


cc.Class({
    extends: cc.Component,

    properties: {

        // Public Properties

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

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

        /** 未解锁, 解锁的图片 */
        lockSpriteFrames: [cc.SpriteFrame],

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

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

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

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

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

        /** 更新按钮的背景, 用来做呼吸灯效果 */
        // updateBtnBg: cc.Sprite,

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

        /** 解锁按钮背景图 */
        lockSprite: cc.Sprite,

        lockBottomNode: cc.Node,

        /** 等级节点 */
        levelProgressNode: cc.Node,

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

        /** 等级 */
        levelProgressLabel: cc.RichText,

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

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

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

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

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

        artistList: cc.Node,

        artistListItem: cc.Prefab,

        openDoorSkeletion: sp.Skeleton,

        updateSkeletion: sp.Skeleton,

        coinArrayMax: {
            default: 3,
            type: cc.Integer,
            tooltip: "当前楼层最大存储金币数"
        },

        coinWrap: cc.Node,

        coinPrefab: cc.Prefab,

        countDown: {
            get: function() {
                if (!this._countDown) {
                    this._countDown = 0;
                }
                return this._countDown;
            },
            set: function (value) {
                this._countDown = value;
                this.countdownLabel.string = DWTool.calculateTime(this._countDown);
                this._preCountDown = this._countDown;
            }
        },

        rate: {
            get: function() {
                if (!this._rate) {
                    this._rate = 0;
                }
                return this._rate;
            },
            set: function(value) {
                this._rate = value;
                this.rateProgressLabel.string = DWTool.coinParse(this._rate);
            }
        },

        notPickupCount: {
            get: function() {
                if (!this._notPickupCount) {
                    this._notPickupCount = 0;
                }
                return this._notPickupCount;
            },
            set: function(value) {
                this._notPickupCount = value;
                this.buildingInfo.coinCount = value;
                GameModule.userInfo.updateRecordModify(this.buildingInfo);
            }
        }
    },

    // LIFE-CYCLE CALLBACKS:
    onLoad () {
        this.coinArray = [];
        this._currentTime = 0;
        this.updateSkeletion.node.active = false;

        this.artistListLayout();

        // 解锁建筑事件
        this.lockBtn.node.on(cc.Node.EventType.TOUCH_END, () => {
            
            if (!this.isSelf) { return; }

            // 如果当前不够钱, 点击不生效
            if (GameModule.userInfo.grossIncome < this.buildingInfo.unlockScore) { return; } 

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

            this.openDoorSkeletion.setAnimation(0, "changjing_kaiqi2");
            
            this.lockBottomNode.runAction(cc.fadeOut(0.1));

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

        }, this);

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

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

                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;
                    });
                }
                
            }

        }, this);

        // 呼吸灯效果
        // let fadeOut = cc.fadeOut(0.8);
        // let fadeIn = cc.fadeIn(0.8);

        // let sequence = cc.sequence(fadeOut, fadeIn, cc.delayTime(0.5));
        // this.updateBtnBg.node.runAction(sequence.repeatForever());

        // 配置界面上的金币
        this.configCoins();
    },

    // 当该节点active为false时, 重置数据
    onDisable () {

        this.buildingInfo = null;
        this.countDown = 0;
        this.rate = 0;
        this._currentTime = 0;
        this.levelProgressBar.progress = 0;
        this.rateProgressBar.progress = 0;
        this.levelProgressLabel.string = "";
    },

    configCoins() {

        for (let i = 0; i < this.coinArrayMax; i++) {
            
            // 初始化
            let coinNode = cc.instantiate(this.coinPrefab)
            this.coinWrap.addChild(coinNode);
            coinNode = coinNode.getComponent("LevelHomeCoin");
            
            this.coinHide(coinNode, i)
            this.coinArray[i] = coinNode;

            coinNode.node.on(cc.Node.EventType.TOUCH_END, (event) => { // 非主态不需要点击效果
                if (!this.isSelf) { return; }
                // console.log(event.getLocation());
                // this.showCollectAnim(event.getLocation(), coinNode.coinCount)
                this.pickupCoin(coinNode, i);
            }, this);
        }
    },

    /**
     * Public Method, 用来设置建筑背景图
     * @param {*} index 
     */
    init(index) {
        if (arguments.length < 1) {
            throw new Error("init Missing parameter...");
        }

        DWTool.loadResSpriteFrame(`./building/${index}`)
        .then((spriteFrame) => {
            this.buildSprite.spriteFrame = spriteFrame;
        }).catch((err) => {
            cc.error(err);
        });
    },

    /**
     * Public Method, 配置建筑的内部样式
     * @param {*} buildingInfo 建筑信息
     * @param {*} isSelf 是否主态
     */
    config(buildingInfo, isSelf) {
        
        if (arguments.length < 2) {
            throw new Error("Config Missing parameter...");
        }

        this.buildingInfo = buildingInfo;
        this.isSelf = isSelf;

        if (this.buildingInfo.isUnlocked) {
            this.initRunman();
        }
    
        // 这里设置一些只需要设置一次的数据
        this.countDown = buildingInfo.rateUnit;

        this.buildNameLabel.string = buildingInfo.name;
        this._notPickupCount = buildingInfo.coinCount;
       
        if (buildingInfo.coinCount === this.coinArrayMax * 10) {
            this.rateProgressBar.progress = 1;
            this.countdownLabel.string = DWTool.calculateTime(0);
        }
        this.levelProgressBar.progress = buildingInfo.level / Global.BuildingManager.getLevelCount(buildingInfo.buildingId);

        this.levelProgressLabel.string = `<outline color=#ffffff width=2><b><color= #0e689c>LV.${buildingInfo.level}</c></b></outline>`

        this.initializeCoinPosition();

        this.layout(buildingInfo);
    },


    /** 初始化金币的位置 */
    initializeCoinPosition() {

        if (!this.buildingInfo.coinCount) { 
            for (let i = 0; i < this.coinArrayMax; i++) {
                let coin = this.coinArray[i];
                this.coinHide(coin, i);
             }
             return;
        }

        for (let i = 0; i < this.coinArrayMax; i++) {
            let coin = this.coinArray[i];
            while (this.buildingInfo.coinCount != 0 && coin.coinCount != 10) {
                coin.coinCount += 1;
                this.buildingInfo.coinCount -= 1;
            }

            if (coin.coinCount != 0) {

                let x = -140 + (85 * i);

                coin.isPlay = true;
                coin.node.position = cc.v2(x, -28);
                coin.node.active = true;
                coin.totalRate = this.buildingInfo.rate * coin.coinCount;
                coin.initStatic(i);
            }
        }
    },

    artistListLayout() {

        let item = cc.instantiate(this.artistListItem);
        this.artistList.addChild(item);
        item.getComponent('LevelHomeArtistItem').init(LevelHomeArtistItemStyle.Add);
        
        
    },

    layout(buildingInfo) {
        
        if (this.isSelf) { // 这里是主态

            this.updateBtn.node.active = true;

            // 判断是否有下一级, 没有的话就是满级
            if (buildingInfo.hasNext === 1) {

                // 判断是否已经解锁
                if (buildingInfo.isUnlocked) {

                    this.lockNode.active = false;
                    this.costLabel.string = DWTool.coinParse(buildingInfo.nextUpScore);
                    this.rate = buildingInfo.rate;
                    // 判断是否有足够的金额解锁
                    if (GameModule.userInfo.grossIncome >= buildingInfo.nextUpScore) {
                        this.setState(RoomState.Update);
                    } else {
                        this.setState(RoomState.Lock);
                    }

                } else {
                    
                    this.countDown = 0;
                    this.rateProgressBar.progress = 0;
                    this.totalRate = 0;
                    this.lockNode.active = true;
                    this.costLabel.string = 0;
                    this.unlockLabel.string = DWTool.coinParse(buildingInfo.unlockScore);

                    // 判断是否有足够的金额解锁
                    if (GameModule.userInfo.grossIncome >= buildingInfo.unlockScore) {
                        this.lockSprite.spriteFrame = this.lockSpriteFrames[1];
                        this.lockBtn.spriteFrame = this.updateBtnFrames[1];
                        this.lockBtn.node.getComponent(cc.Button).interactable = true;
                    } else {
                        this.lockSprite.spriteFrame = this.lockSpriteFrames[0];
                        this.lockBtn.spriteFrame = this.updateBtnFrames[0];
                        this.lockBtn.node.getComponent(cc.Button).interactable = false;
                    }
                    this.setState(RoomState.Lock);
                }
        
            } else {
                this.rate = buildingInfo.rate;
                this.setState(RoomState.Full);
            }

        } else { // 这是访问别人家园时的状态

            
            if (buildingInfo.isUnlocked) {
                this.lockNode.active = false; 
                this.rate = buildingInfo.rate;
            } else {
                this.lockNode.active = true;
                this.lockBtn.node.active = false;
                this.countDown = 0;
                this.rateProgressBar.progress = 0;
                this.totalRate = 0;
                
                this.costLabel.string = 0;
                this.unlockLabel.string = DWTool.coinParse(buildingInfo.unlockScore);

                this.lockSprite.spriteFrame = this.lockSpriteFrames[0];
                this.lockBtn.spriteFrame = this.updateBtnFrames[0];
            }

            this.updateBtn.node.active = false;
            // this.updateBtnBg.node.active = false;
        }
    },

    getBuildingInfo() {
        return this.buildingInfo;
    },

    setState(state) {

        if (this.state === state && !this.isSelf) {
            return;
        }

        switch (state) {
            case RoomState.Lock:
                // this.updateBtnBg.node.active = false;
                this.updateBtn.spriteFrame = this.updateBtnFrames[0];
                this.updateBtn.node.getComponent(cc.Button).interactable = false;
                break;
            case RoomState.Update:
                this.lockNode.active = false;
                // this.updateBtnBg.node.active = true;
                this.updateBtn.spriteFrame = this.updateBtnFrames[1];    
                this.updateBtn.node.getComponent(cc.Button).interactable = true;
                break;
            case RoomState.Full:
                this.lockNode.active = false;
                // this.updateBtnBg.node.active = false;
                this.updateBtn.node.active = false;
            default:
                break;
        }
        this.state = state;
    },

    // 升级建筑
    updateBuilding() {
        // 从配置文件里获取
        let buildModel = Global.BuildingManager.getBuildingInfo(1, this.buildingInfo.buildingId, this.buildingInfo.level + 1);

        if (this.buildingInfo.isUnlocked) {
            GameModule.userInfo.grossIncome -= this.buildingInfo.nextUpScore;
            GameModule.userInfo.updateRecordModify(buildModel);
        } else {
            GameModule.userInfo.grossIncome -= this.buildingInfo.unlockScore;
            GameModule.userInfo.recordUnlockModify.push(buildModel);
        }

        GameModule.userInfo.stars += 1;
        this.config(buildModel, this.isSelf);
    },

    // 收取金币
    pickupCoin(coin, i) {
        
        if (this.currentCoin === coin) {
            this.currentCoin = null;
        }

        let pos = coin.node.convertToWorldSpace(cc.v2(coin.node.width/2, coin.node.height/2));
        this.showCollectAnim(pos, coin.coinCount)

        // 点击一次金币, 就将notPickupCount减去coinNode.coinCount
        this.notPickupCount -= coin.coinCount;

        // 收取收益
        let buildingInfo = this.getBuildingInfo();
        
        // console.log(`收入: ${buildingInfo.rate * coin.coinCount}`);
        GameModule.userInfo.grossIncome += (buildingInfo.rate * coin.coinCount);
        
        this.coinHide(coin, i);
    },

    showCollectAnim(pos, colNums) {
        let canvasNode = cc.find("Canvas");
        let grossCoin = GameModule.userInfo.grossCoin;
        let grossCoinPos = grossCoin.node.convertToWorldSpace(cc.v2(grossCoin.node.width/2, grossCoin.node.height/2));
        
        // let colNums = 5
        let vSize = cc.view.getVisibleSize();
        let target = cc.v2(grossCoinPos.x - vSize.width / 2, grossCoinPos.y - vSize.height / 2)
        
        let i = 0;
        let runSt = setInterval(() => {
            if(i == colNums) {
                clearInterval(runSt)
            } else {
                let ran = (Math.random() - 0.5) * 2 * 3;

                let newCoin = cc.instantiate(this.coinPrefab);
                let posX = pos.x - vSize.width / 2;
                let posY = pos.y - vSize.height / 2;
                
                canvasNode.addChild(newCoin)

                newCoin.x = posX + ran * 15;
                newCoin.y = posY + 30 + ran * 15;
                newCoin.active = true;

                newCoin = newCoin.getComponent("LevelHomeCoin")
                newCoin.initAnim()

                let cbNotiStart = cc.callFunc(() => {
                    Global.GameEvent.fire(GameNotificationKey.UserCollectCoin, true);
                })

                let cbDestroy = cc.callFunc(() => {
                    newCoin.node.destroy();
                })

                let act = cc.sequence(cc.moveTo(1, target), cbDestroy, cbNotiStart)
                
                newCoin.node.runAction(act.easing(cc.easeIn(2.1)));

                i++
            }
        }, 100)

        // for(let i = 0; i < colNums; i++) {
        //     let ran = (Math.random() - 0.5) * 2 * 3;

        //     let newCoin = cc.instantiate(this.coinPrefab);
        //     let posX = pos.x - vSize.width / 2;
        //     let posY = pos.y - vSize.height / 2;
            
        //     let canvasNode = cc.find("Canvas");
        //     canvasNode.addChild(newCoin)

        //     newCoin.x = posX + ran * 15;
        //     newCoin.y = posY + 30 + ran * 15;
        //     newCoin.active = true;

        //     newCoin = newCoin.getComponent("LevelHomeCoin")
        //     newCoin.initAnim()

        //     let fire = cc.callFunc(() => {
        //         newCoin.node.destroy();
        //         if(i == 0) {
        //             Global.GameEvent.fire(GameNotificationKey.UserCollectCoin, true);
        //         } else if(i == colNums - 1) {
        //             setTimeout(() => {
        //                 Global.GameEvent.fire(GameNotificationKey.UserCollectCoin, false);
        //             }, 400)
        //         } 
        //     }, this, null)

        //     let act = cc.sequence(cc.moveTo(1, target), fire)
        //     newCoin.node.runAction(act.easing(cc.easeIn(2.1)));
        // }
    },

    coinHide(coin, i) {
        // 算出金币的x值, 70是金币宽度, -130是第一个金币的x值
        let x = -140 + (85 * i);

        // 重置金币状态
        coin.node.position = cc.v2(x, -108);
        coin.node.active = false;
        coin.isPlay = false;
        coin.isPlaying = false;
        coin.coinCount = 0;
        coin.totalRate = 0;
    },

    getFreeCoin() {
        for (let i = 0; i < this.coinArrayMax; i++) {
            let coinNode = this.coinArray[i];
            if (coinNode.coinCount != 10) {
                return coinNode;
            }
        }
        return null;
    },

    generateCoin() {

        if (this.currentCoin && this.currentCoin.coinCount < 10) {

            this.currentCoin.totalRate += this.getBuildingInfo().rate;
            this.currentCoin.coinCount += 1;
            this.currentCoin.updateAnimation();
            
        } else {

            this.currentCoin = this.getFreeCoin();

            if (this.currentCoin) {
                this.currentCoin.totalRate += this.getBuildingInfo().rate;
                this.currentCoin.coinCount += 1;
    
                if (!this.currentCoin.isPlay) {       
                    this.currentCoin.showAnimation();
                } else {
                    this.currentCoin.updateAnimation();
                }
            }
        }  
    },

    /**
     * 初始化可移动的人物骨骼 (位置随机)
     * @param {Number} size 人物数量
     */
    initRunman (size = 1) {
        try {
            this.destroyRunman()
        } catch (e) {
            console.log(e);
        }
        if(this.isInitRunman) {
            return
        } else {
            this.isInitRunman = true;
        }
        this.runmanList = [];
        cc.loader.loadRes('./prefabs/runman', (err, prefab) => {
            for (let i = 0; i < size; i++) {
                let runman = cc.instantiate(prefab);
                this.runmanList.push(runman)
                this.node.addChild(runman);

                let direction = (Math.random() - 0.5) * 2 > 0 ? 1 : -1   //初始方向{1: 向左; -1: 向右}
                runman.x = Math.random() * 350 * direction

                let moveLeftToRight = cc.moveTo(5, cc.v2(330, runman.y))
                let moveRightToLeft = cc.moveTo(5, cc.v2(-330, runman.y))
                let directionRightToLeft = cc.scaleTo(0, -1, 1)
                let directionLeftToRight = cc.scaleTo(0, 1, 1)

                if(direction < 0) {
                    runman.scaleX = -1
                    let ac = cc.repeatForever(
                        cc.sequence([
                            moveLeftToRight,
                            directionLeftToRight,
                            moveRightToLeft,
                            directionRightToLeft
                        ])
                    )
                    runman.runAction(ac)
                } else {
                    let ac = cc.repeatForever(
                        cc.sequence([
                            moveRightToLeft,
                            directionRightToLeft,
                            moveLeftToRight,
                            directionLeftToRight
                        ])
                    )
                    runman.runAction(ac)
                }
            }              
        })
    },

    /**
     * 销毁人物对象
     */
    destroyRunman () {

    },

    update (dt) {
        let buildingInfo = this.getBuildingInfo();
        if (buildingInfo) {

            // 不断刷新界面
            this.layout(buildingInfo);

            // 只有已经解锁进度条才会走
            if (buildingInfo.isUnlocked) {
                
                // 进度条走完, 开始生产金币
                if (Math.floor(this.rateProgressBar.progress) === 1) {

                    if (this.isSelf) { // 主态时样式
                        if (this.notPickupCount >= this.coinArrayMax * 10) {
                        
                            // 避免重复赋值
                            if (!this.coinFullTip.active) {
                                this.coinFullTip.active = true;    
                            }
                            
                        } else {
    
                            // 避免重复赋值
                            if (this.coinFullTip.active) {
                                this.coinFullTip.active = false;  
                            }
                            
                            this.notPickupCount += 1; 
                            this.generateCoin();
                            this.rateProgressBar.progress = 0;
                            this._currentTime = 0;
                        }  
                        
                    } else { // 客态时样式
                        this.rateProgressBar.progress = 0;
                        this._currentTime = 0;
                    }
                    
                } else {

                    this._currentTime += dt;
                    this.rateProgressBar.progress = this._currentTime / this.countDown; 

                    let resultCountDown = this.countDown - Math.floor(this._currentTime);
                    if (this._preCountDown !== resultCountDown) {

                        this.countdownLabel.string = DWTool.calculateTime(resultCountDown);
                        this._preCountDown = resultCountDown;
                    }
                } 
            }   
        }
    },
});
