const HomeApi = require("../net/HomeApi");
const GameModule = require("../utils/GameModule");
const GameNotificationKey = require('../utils/GameEnum').GameNotificationKey;
const AlertManager = require('../utils/AlertManager');

cc.Class({
    extends: cc.Component,

    properties: {
        scrollView: cc.ScrollView,

        clickAddMoneyPrefab: cc.Prefab,

        _unlockBuilding: [],

        showOffLineUI: true,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        this.minContentPosition = 0;

        this.buildings = [];

        this.unlockBuilding = [];

        this.setEventListener();

        this.addMoneyPool = new cc.NodePool();

        this.scrollViewMng = this.scrollView.getComponent('LevelHomeListAdapter');
    },

    setEventListener() {
        GameEvent.on(GameNotificationKey.ClickAddMoney, this, (position) => {
            this.clickAddMoney(position);
        });

        GameEvent.on(GameNotificationKey.RefreshBuildingData, this, () => {
            this.refreshAllbuildingGoldRate();
        });

        GameEvent.on(GameNotificationKey.UnlockLevelHome, this, (buildingModel) => {
            this.unlockLevelHome(buildingModel);
        });

    },

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

        this.uid = uid;
        this.node.setContentSize(cc.view.getVisibleSize());

        this.buildingInfos = [];

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

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

    //
    clickAddMoney (position) {
        let item = null;
        if (this.addMoneyPool.size() > 0) {
            item = this.addMoneyPool.get();
        } else {
            item = cc.instantiate(this.clickAddMoneyPrefab);
        }
        this.node.addChild(item);

        item.x = position.x;
        item.y = position.y;
        item.active = true;

        let itemManager = item.getComponent('ClickAddMoney');
        itemManager.showAddMoney( () => {
            this.addMoneyPool.put(item);
        });
    },

    start () {

    },

    sortNumber(a,b) {
        return a - b
    },

    //数据排序，roomId小的在前
    compareFunction (a, b) {
        if (a.roomId < b.roomId) {
            return 1; // a排在b的前面
        } else if (a.roomId > b.roomId) {
            return -1; // a排在b的后面
        } else {
            return 0; // a和b的位置保持不变
        }
    },

    getNetworkData(callback) {

        this.getUserBuildings()
            .then((userRooms) => {

            // 清空数据
            this.buildingInfos = [];

            let sortArray = userRooms.sort(this.compareFunction);

            // 离线收益金币数量
            // let offlineGrossIncome = 0;
            sortArray.map((value, index, array) => {
                let model = Global.BuildingManager.getBuildingInfo(value.roomId, value.roomLevel);
                this._unlockBuilding[index] = model.isUnlocked ? 1 : 0;

                model.roomStars = value.roomStars || [];

                this.buildingInfos.push(model);
         });

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

        // GameModule.userInfo.setUserInfo(responseData.user);

        // this.resetPaddingBottom();

            callback && callback();

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

            // 离线收益处理
            this.configOffIncome();

            // return this.getBuildingItems();
        })
        .then((buildingItems) => {

            for (const roomId in buildingItems) {

                let itemScript;
                let filterList = this.buildings.filter( item => item.buildingInfo.roomId === parseInt(roomId) ) || [];
                if (filterList.length > 0) { itemScript = filterList[0]; }

                if (buildingItems.hasOwnProperty(roomId)) {
                    let prop = buildingItems[roomId];
                    itemScript.configProp(prop);
                }
            }
        })
        .catch((err) => {
            console.log(err);
        });
    },

    getUserBuildings() {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            // HomeApi.getUserBuildings((responseData) => {
            //     resolve(responseData);
            // }, (error) => {
            //     reject(error);
            // });
            if (Global.BuildingManager.networkRooms && Global.BuildingManager.networkRooms.length > 0) {
                resolve(Global.BuildingManager.networkRooms);
            } else {
                reject('error');
            }
        })
    },

    configBuildings() {
        this.refreshAllbuildingGoldRate();

        let sortLockRoom = 0;
        this.buildingInfos.forEach(n => {
            if (n.isUnlocked == 0) {
                sortLockRoom += 1;
            }
        });

        if (sortLockRoom == 0) {
            this.scrollViewMng.configBuildings(this.buildingInfos);
        } else {
            let sortArray = this.buildingInfos.slice((sortLockRoom - 1),this.buildingInfos.length);
            this.scrollViewMng.configBuildings(sortArray);
        }

        GameModule.roomInfo = this.buildingInfos;
    },

    unlockLevelHome(buildingModel) {
        this.buildingInfos.forEach((item, index) => {
            if (item.roomId == buildingModel.roomId) {
                this.buildingInfos[index] = buildingModel;
            }
        });

        let sortLockRoom = 0;
        this.buildingInfos.forEach(n => {
            if (n.isUnlocked == 0) {
                sortLockRoom += 1;
            }
        });

        // 等于0为所有建筑已开锁
        if (sortLockRoom != 0) {
            let sortArray = this.buildingInfos.slice((sortLockRoom - 1),this.buildingInfos.length);
            this.scrollViewMng.configBuildings(sortArray, true);
        }
        GameModule.roomInfo = this.buildingInfos;
    },

    /**
     * 离线收益处理
     * @param {Array} sortArray 用户当前城市buildingInfos数组
     * @param {Number} offlineGrossIncome 离线收益金币数量
     */
    configOffIncome() {
        let offlineGold = Global.offlineGold;

        let lastTime = cc.sys.localStorage.getItem('offlineLastTime');
        if (!lastTime) {
            lastTime = new Date().getTime();
            cc.sys.localStorage.setItem('offlineLastTime', lastTime);
        } else {

            if (offlineGold <= 0 ) {
                return;
            }

            let curTime = new Date().getTime();
            cc.sys.localStorage.setItem('offlineLastTime', curTime);

        //     // 显示离线收益的条件：
        //     // 1. 离上一次显示超过5分钟
            let unLockStatus1 = curTime - lastTime > 300 * 1000;

            // showOffLineUI: 用户每次进入游戏离线收益只会显示1次
            if (this.showOffLineUI && unLockStatus1) {
                this.showOffLineUI = false;
                AlertManager.showOfflineGrossIncome(offlineGold);
            }
        }
    },

    //刷新建筑每秒生产金币
    refreshAllbuildingGoldRate() {
        var totalStar = 0;
        var totalRate = 0;
        this.buildingInfos.forEach(n => {
            if (n.isUnlocked && n.gold > 0) {
                totalRate += Math.ceil(n.gold / n.goldUnit);
                if (n.roomStars && n.roomStars.length > 0) {
                    totalStar += n.roomStars.length;
                }
            }
        });

        GameModule.userInfo.starMt = totalStar > 0 ? Math.pow(2,totalStar) : 1;
        GameModule.userInfo.rateGold = totalRate;
        GameEvent.fire(GameNotificationKey.UpBuildingLevel);
    },


    // update (dt) {},
});
