const HomeApi = require("../net/HomeApi");
const GameModule = require("../utils/GameModule");
const { GameNotificationKey } = require("../utils/GameEnum")
const AlertManager = require('../utils/AlertManager')
cc.Class({
    extends: cc.Component,

    properties: {

        scrollView: cc.ScrollView,

        levelHomeItem: cc.Prefab,

        levelHomeTop: cc.Prefab,

        levelHomeBottom: cc.Prefab,

        minContentPosition: -150,

        _unlockBuilding: [],

        firstLoad: true,

    },

    /**
     * home 初始化方法, 所有的初始化操作在这里操作, 必须在加入父节点之前调用
     * */
    init(uid, cityId) {

        this.uid = uid;
        this.cityId = cityId;

        this.buildingInfos = [];

        this.node.parent = cc.find("Canvas/game");

        this.refreshTheme();
        this.getNetworkData();
    },

    refreshTheme() {

        if (this.topScript) {
            this.topScript.init(this.cityId);
        }

        if (this.buildings) {
            for (let i = 0; i < this.buildings.length; i++) {
                let itemScript = this.buildings[i];
                itemScript.init(this.cityId, i + 1);
            }
        }

        if (this.bottomScript) {
            this.bottomScript.init(this.cityId);
        }
    },

    // LIFE-CYCLE CALLBACKS:
    onLoad() {

        this.buildings = [];

        this.unlockBuilding = [];

        this.matchScreenSize();

        let topNode = cc.instantiate(this.levelHomeTop);
        this.topScript = topNode.getComponent('LevelHomeTop');
        this.topScript.init(this.cityId);
        this.scrollView.content.addChild(topNode);

        for (let i = 0; i < 5; i++) {
            let item = cc.instantiate(this.levelHomeItem);
            let itemScript = item.getComponent('LevelHomeItem');
            itemScript.init(this.cityId, i + 1);
            this.scrollView.content.addChild(item);
            this.buildings.push(itemScript);
        }

        let bottomNode = cc.instantiate(this.levelHomeBottom);
        this.bottomScript = bottomNode.getComponent('LevelHomeBottom'); this.bottomScript.init(this.cityId);
        this.scrollView.content.addChild(bottomNode);

        this.scrollView.node.on("scrolling", (event) => {

            if (this.scrollView._isOutOfBoundary()) {

                if (this.scrollView._outOfBoundaryAmount.y > 0) { // 超出上面的界限

                    this.scrollView._outOfBoundaryAmount.y = 0;
                    this.scrollView._adjustContentOutOfBoundary();

                } else {  // 超出下面的界限

                    if (this.scrollView._outOfBoundaryAmount.y < this.minContentPosition) {

                        if (this.recordScrollViewPosition) {
                            this.scrollView.content.setPosition(this.recordScrollViewPosition);
                            return;
                        } else {
                            this.recordScrollViewPosition = this.scrollView.getContentPosition();
                        }

                    } else {
                        this.recordScrollViewPosition = null;
                    }
                }
            }

        }, this);

        GameEvent.on(GameNotificationKey.showCatFlyAnimation, this, () => {
            this.scrollView.scrollToTop(0.2);
        });

        GameEvent.on(GameNotificationKey.ReloadLevelHomeData, this, () => {
            this.refreshTheme();
            this.getNetworkData();   
        });

        GameEvent.on(GameNotificationKey.ResetLevelHomePaddingBottom, this, () => {
            this.resetPaddingBottom();
        })
    },

    /**
     * 适配不同高度的屏幕尺寸
     */
    matchScreenSize() {
        let initHeight = 1624;
        let vsize = cc.view.getVisibleSize()
        let paddingY = (initHeight - vsize.height) / 2;

        if (paddingY < 0) {
            paddingY = 0;
        }
        this.scrollView.content.getComponent(cc.Layout).paddingTop = paddingY;

        this.scrollView.elastic = false;
        // 底部加多一块100px的内边距, 让底楼不要完全显示出来
        this.scrollView.content.getComponent(cc.Layout).paddingBottom = paddingY - 100;
        
    },

    resetPaddingBottom() {
        let initHeight = 1624;
        let vsize = cc.view.getVisibleSize()
        let paddingY = (initHeight - vsize.height) / 2;
        if (GameModule.userInfo.stars >= 20) {
            this.scrollView.elastic = true;
            // 底部加多一块100px的内边距, 让底楼不要完全显示出来
            this.scrollView.content.getComponent(cc.Layout).paddingBottom = paddingY - 100;
        } else {
            this.scrollView.elastic = false;
            // 底部加多一块100px的内边距, 让底楼不要完全显示出来
            this.scrollView.content.getComponent(cc.Layout).paddingBottom = paddingY - 275;
        }
        this.scrollView.scrollToBottom(0);
    },

    // 用来访问自己家园时, 重置scrollView位置
    start() {
        this.scrollView.scrollToBottom(0.0);
    },

    // 用来访问好友家园时, 重置scrollView位置
    onEnable() {

    },

    getNetworkData(callback) {

        // 获取目标用户的建筑
        HomeApi.getUserBuildings(this.uid, this.cityId, (responseData) => {
            
            // 清空数据
            this.buildingInfos = [];

            // 满级后去别的城市就置零
            GameModule.userInfo.levelHomeItemFullCount = 0;

            let sortArray = responseData.buildings.sort((a, b) => {
                return a.buildingId < b.buildingId;
            });

            let offlineGrossIncome = 0;
            sortArray.map((value, index, array) => {
                let model = Global.BuildingManager.getBuildingInfo(this.cityId, value.buildingId, value.level)
                this._unlockBuilding[index] = model.isUnlocked ? 1 : 0;
                if (model.isFull() && this.cityId === Global.devCityId) {
                    try {
                        GameEvent.fire(GameNotificationKey.LevelHomeItemBuildingFull);
                    } catch (error) {
                        console.log(error);
                    }
                }
                model.coinCount = value.coinCount;
                model.artists = value.artists || [];
                if (model.artists.length > 0) { // 有艺人入驻的情况
                    
                    let addition = 0;
                    for (let i = 0; i < model.artists.length; i++) {
                        let artist = model.artists[i];
                        addition += artist.stationJobLevel + 1;
                    }
                    offlineGrossIncome += (model.coinCount * (model.rate * addition));

                } else { // 无艺人入驻时
                    offlineGrossIncome += (model.coinCount * model.rate);
                }
                this.buildingInfos.push(model);
            });

            this._unlockBuilding = this._unlockBuilding.reverse();

            GameModule.userInfo.setUserInfo(responseData.user);
            GameModule.userInfo.setGrossIncomeAndStars(responseData.grossIncome, responseData.user.stars);

            // this.resetPaddingBottom();

            callback && callback();

            // 开始设置建筑
            this.configBuildings();

            // 计算离线收益
            let lastTime = cc.sys.localStorage.getItem('offlineLastTime');
            if(!lastTime) {
                lastTime = new Date().getTime()
                cc.sys.localStorage.setItem('offlineLastTime', lastTime);
            } else {
                let curTime = new Date().getTime()
                cc.sys.localStorage.setItem('offlineLastTime', curTime);

                // 离开超过5分钟才显示离线收益
                if (this.firstLoad && curTime - lastTime > 300 * 1000) {
                    this.firstLoad = false;
                    AlertManager.showOfflineGrossIncome(offlineGrossIncome);
                }
            }
            

        }, (error) => {
            console.log("error: " + error);
        });
    },

    configBuildings() {

        for (let i = 0; i < this.buildings.length; i++) {
            let itemScript = this.buildings[i];
            itemScript.config(this.buildingInfos[i], this.uid, this._unlockBuilding, (newBuildingInfo) => {
                this.buildingInfos[i] = newBuildingInfo;
            });
        }
    },

    onDestroy() {
        GameEvent.off(GameNotificationKey.showCatFlyAnimation, this);
    },

});
