import { NetManager } from "../../libs/tw/manager/NetManager";
import { deepClone } from "../comm/UtilsConst";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { MainIns } from "./MainScene/MainScene";

let HomeData = {
    gold: 0,    // 欢趣豆
    prop: {
        sp_food_1: 0,    // 饲料
        sp_food_2: 0,    // 水壶
        sp_prop_1: 0,    // 加速卡
    },
    product: {
        sp_1: 0,    // 鸡蛋
        sp_2: 0,    // 小麦粉
        sp_3: 0,    // 玉米
        sp_4: 0,    // 牛奶
    },
    medals: {
        sp_achv_1: {
            name: '进击的农夫',
            count: 0
        },   // 进击的农夫
        sp_achv_2: {
            name: '丰收的季节',
            count: 0
        },   // 丰收的季节
    },
};

export enum HOME {
    GOLD = 'gold',
    PROP = 'prop',
    PRODUCT = 'product',
    MEDALS = 'medals',
}

/**
 * 刷新拥有的产物，使用数据之前要刷新，如打开仓库、打开商店
 */
export const G_UpdateHomeData = function() {
    let updateGold = new Promise((resolve, reject) => {
        NetManager.ins.getProjectUserInfo((success, res) => {
            if(!success) {
                return;
            }
            G_SetHomeDataByKey(HOME.GOLD, res.data.consumerCredits);
            resolve();
        });
    });

    let updateSp = new Promise((resolve, reject) => {
        NetManager.ins.queryUserSpList((success, res) => {
            if(!success) {
                return;
            }
            for(let k in HomeData.prop) {
                HomeData.prop[k] = res.data[k];
            }
            for(let k in HomeData.product) {
                HomeData.product[k] = res.data[k];
            }
            for(let k in HomeData.medals) {
                HomeData.medals[k].count = res.data[k];
            }
            MainIns().mainUI.setPropInfo();
            resolve();
        });
    });
    return Promise.all([updateGold, updateSp]);
};

export const G_GetHomeData = function() {
    return deepClone(HomeData);
};

export const G_GetHomeDataByKey = function(key: HOME) {
    return deepClone(HomeData[key]) || null;
};

export const G_SetHomeDataByKey = function(key: HOME, val) {
    HomeData[key] = val;
};

/**
 * 检查是否可以弹出勋章弹窗
 */
export const G_JudgeMedalPanel = function() {
    const oldData = G_GetHomeDataByKey(HOME.MEDALS);
    G_UpdateHomeData().then(() => {
        const newData = G_GetHomeDataByKey(HOME.MEDALS);
        for(const k in newData) {
            if(newData[k].count > oldData[k].count) {
                setTimeout(() => {
                    PanelCtrl.instance.show(ModuleTypes.MEDAL_PANEL, k);
                }, 500);
                return;
            }
        }
    })
};




