
const DWTool = require('../utils/DWTool');
const { GameNotificationKey } = require("../utils/GameEnum");
const ThemeManager = require("../utils/ThemeManger");
const HomeApi = require("../net/HomeApi");

cc.Class({
    extends: cc.Component,

    properties: {

        // Public Properties

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

        // 两边的柱子
        pillars: [cc.Sprite],

        bottomBg: cc.Sprite,

        lockBottomBg: cc.Sprite,

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

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

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

        /** 这里当做升级建筑按钮 */
        updateBtn: 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,

        artistList: cc.Node,

        artistListItem: cc.Prefab,

        openDoorSkeletion: sp.Skeleton,

        updateSkeletion: sp.Skeleton,

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

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

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

        addition: {
            get: function () {
                if (!this._addition) {
                    this._addition = 0;
                }
                return this._addition;
            },
            set: function (value) {
                this._addition = value;
                if (this._addition === 0) {
                    this.additionNode.active = false;
                } else {
                    this.additionNode.active = true;
                    this.additionLabel.string = `X${this._addition}`;
                }
            }
        },

        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;
                if (this.addition > 0) {
                    this._rate = this._rate * this.addition;
                }
                this.rateProgressLabel.string = DWTool.coinParse(this._rate);
            }
        },

    },

    // LIFE-CYCLE CALLBACKS:
    onLoad() {

        this._currentTime = 0;
        this.humanList = [];
        this.isFirstLoad = true;
        // 监听自定义事件
        this.setEventListener();
    },

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

        this.addition = 0;
        this.isFirstLoad = true;
        this.buildingInfo = null;
        for (let child of this.artistList.children) { child.destroy(); }
        for (let child of this.humanList) { child.destroy(); }
        this.countDown = 0;
        this.rate = 0;
        this._currentTime = 0;
        this.levelProgressBar.progress = 0;
        this.rateProgressBar.progress = 0;
        this.levelProgressLabel.string = "";
    },

    onDestroy() {

        GameEvent.off(GameNotificationKey.ResidentArtist, this);
        GameEvent.off(GameNotificationKey.RefreshLevelHomeArtistList, this);

    },

    setEventListener() {

        // 这个是入驻艺人成功时调用的
        GameEvent.on(GameNotificationKey.ResidentArtist, this, (uid, buildingId) => {

            if (this.node.active && this.uid === uid && this.buildingInfo.buildingId === buildingId) { 

                HomeApi.friendGetArtistsInBuilding(this.uid, this.buildingInfo.buildingId, (data) => {
                    this.artists = data.list || [];
                    this.artistListLayout();
    
                }, (code, msg) => {
                    console.log(msg);
                })
            }
        });

        // 这个是召回驱赶艺人时调用的
        GameEvent.on(GameNotificationKey.RefreshLevelHomeArtistList, this, (uid, buildingId) => {

            if (this.node.active && this.uid === uid && this.buildingInfo.buildingId === buildingId) {

                HomeApi.friendGetArtistsInBuilding(this.uid, this.buildingInfo.buildingId, (data) => {

                    this.artists = data.list || [];
                    this.artistListLayout();
    
                }, (code, msg) => {
                    console.log(msg);
                })
            }
        });
    },

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

        this.cityId = cityId;
        this.index = index;
        ThemeManager.setItemBuildSpriteFrame(this.cityId, this.buildSprite, index);
        ThemeManager.setItemPillarSpriteFrame(this.cityId, this.pillars);
        ThemeManager.setItemDownSpriteFrame(this.cityId, this.bottomBg);
        ThemeManager.setItemLockDownSpriteFrame(this.cityId, this.lockBottomBg);
    },


    /**
     * Public Method, 配置建筑的内部样式
     * @param {*} buildingInfo 建筑信息
     * @param {*} uid 当前用户的uid
     */
    config(buildingInfo, uid) {

        if (arguments.length < 2) {
            throw new Error("Config Missing parameter...");
        }

        this.buildingInfo = buildingInfo;
        this.uid = uid;

        this.artists = this.buildingInfo.artists;

        // 这里设置一些只需要设置一次的数据
        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>`

        if (this.isFirstLoad) {

            this.isFirstLoad = false;

            this.artistListLayout();
        }

        this.layout(buildingInfo);
    },

    artistListLayout() {

        for (let child of this.artistList.children) { child.destroy(); }
        for (let child of this.humanList) { child.destroy(); }

        let self = this;

        let addAddItemToList = function () {
            let addArtistItem = cc.instantiate(self.artistListItem);
            self.artistList.addChild(addArtistItem);
            let addArtistScript = addArtistItem.getComponent('LevelHomeArtistItem');
            addArtistScript.initWithBuildingInfo(self.buildingInfo, self.uid, false);
        }

        let addArtistItemToList = function (artist) {
            let artistItem = cc.instantiate(self.artistListItem);
            self.artistList.addChild(artistItem);
            let artistScript = artistItem.getComponent('LevelHomeArtistItem');
            artistScript.initWithArtistData(self.buildingInfo, self.uid, false, artist);
        }

        let addHuman = function (artist, index) {
            DWTool.loadResPrefab("./prefabs/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);
                });
        }

        // 当没有自己艺人, 也没有好友艺人入驻时, 这里还得区分主态和客态
        if (this.artists.length === 0) {
            addAddItemToList();
            // 没有艺人不显示倍数
            this.addition = 0;
        } else {

            // 有艺人入驻要显示倍数
            this.additionNode.active = true;

            if (this.artists.length === 1) {

                let artist = this.artists[0];
                this.addition += artist.stationJobLevel + 1;
                // 这里要区分主态和客态, 去别人家园时, 如果有一个是客态自己的艺人, 那么另一个就是可以入驻的按钮
                if (artist.role === 2) {

                    addArtistItemToList(artist);
                    addHuman(artist, (Math.random() - 0.5) * 2);
                    addAddItemToList();
                    
                } else {
                    
                    addArtistItemToList(artist);
                    addHuman(artist, (Math.random() - 0.5) * 2);
                }

            } else {
                for (let i = 0; i < this.artists.length; i++) {
                    let artist = this.artists[i];
                    this.addition += artist.stationJobLevel + 1;
                    addArtistItemToList(artist);
                    addHuman(artist, i);
                }
            }
        }
    },

    layout(buildingInfo) {

        if (buildingInfo.isUnlocked) {
            this.lockNode.active = false;
            this.rate = buildingInfo.rate;
            this.maxNode.active = (buildingInfo.hasNext != 1) ? true : false;
        } else {
            this.lockNode.active = true;
            this.countDown = 0;
            this.rateProgressBar.progress = 0;
            this.totalRate = 0;

            this.costLabel.string = 0;
        }

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

    update(dt) {
        if (this.buildingInfo) {

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

            // 只有已经解锁进度条才会走
            if (this.buildingInfo.isUnlocked) {

                // 进度条走完, 开始生产金币
                if (Math.floor(this.rateProgressBar.progress) === 1) {

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