const HomeApi = require("../net/HomeApi");
const Api = require('../net/Api');
// const BuildingManager = require('../utils/BuildingManager');
const Notikey = require('../utils/GameEnum').GameNotificationKey;
const DWTool = require('../utils/DWTool');
const GameModule = require("../utils/GameModule");

cc.Class({
    extends: cc.Component,

    properties: {

        scrollView: cc.ScrollView,

        levelHomeItem: cc.Prefab,

        levelHomeTop: cc.Prefab,

        levelHomeBottom: cc.Prefab,
        
        minContentPosition: -150,
    },

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

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

        if (isSelf) {
            // this.setEventListener();
        }

        this.buildingInfos = [];

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

        this.getNetworkData();
    },

    initFriend(uid, cityId, callback) {
        this.uid = uid;
        this.cityId = cityId;
        this.isSelf = false;

        this.buildingInfos = [];

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

        this.scrollView.scrollToTop(0); 

        // 获取目标用户的建筑
        HomeApi.getUserBuildings(uid, cityId, (responseData) => {
            
            let reverseArray = responseData.buildings.reverse();
            reverseArray.map((value, index, array) => {
                let model = Global.BuildingManager.getBuildingInfo(this.cityId, value.buildingId, value.level)
                model.coinCount = value.coinCount;

                this.buildingInfos.push(model);
            });
            
            GameModule.friendInfo.userNick.string = responseData.user.nick; 
            GameModule.friendInfo.userStars.string = responseData.stars; 
            Api.createImageFromUrl(responseData.user.head, (spriteFrame) => {
                GameModule.friendInfo.userHead.spriteFrame = spriteFrame;
            }, null);

            callback && callback(responseData)

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

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

    },

    // LIFE-CYCLE CALLBACKS:
    onLoad () {
        
        this.buildings = [];

        this.matchScreenSize();

        let topNode = cc.instantiate(this.levelHomeTop);
        this.scrollView.content.addChild(topNode);

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

        let bottomNode = cc.instantiate(this.levelHomeBottom);
        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);  
    },

    /**
     * 适配不同高度的屏幕尺寸
     */
    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;

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

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

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

    getNetworkData() {
        // 获取目标用户的建筑
        HomeApi.getUserBuildings(this.uid, this.cityId, (responseData) => {
            
            let reverseArray = responseData.buildings.reverse();
            reverseArray.map((value, index, array) => {
                let model = Global.BuildingManager.getBuildingInfo(this.cityId, value.buildingId, value.level)
                model.coinCount = value.coinCount;
                
                this.buildingInfos.push(model);
            });

            if(this.isSelf) {
                console.log("responseData:" + JSON.stringify(responseData));
                GameModule.userInfo.setUserInfo(responseData.user);
                GameModule.userInfo.setGrossIncomeAndStars(responseData.grossIncome, responseData.stars);
            }
            // if (!this.isSelf) {
            //     this.configUserInfo(responseData.user);
            // }

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

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

    configBuildings() {

        for (let i = 0; i < this.buildings.length; i++) {
            let building = this.buildings[i];
            building.getComponent('LevelHomeItem').config(this.buildingInfos[i], this.isSelf);
        }
    },

    update (dt) {

        if (this.buildings.length > 0 && this.isSelf) {

            let totalRate = 0;

            for (let i = 0; i < this.buildings.length; i++) {
            
                let building = this.buildings[i];
                let buildingInfo = building.getComponent('LevelHomeItem').getBuildingInfo();

                if (buildingInfo && buildingInfo.isUnlocked) {
                    totalRate += buildingInfo.rate
                }
            }

            GameModule.userInfo.rate = totalRate;
        }
    },
});
