import ComponentBase from "../../components/ComponentBase";
import { M_HideOption } from "./Objs/OptionPanel";
import PanelCtrl from "../../ctrls/panelCtrl";
import { ModuleTypes } from "../../types/sceneTypes";
import { btnDelay, showToast } from "../../comm/UtilsConst";
import { MainIns } from "./MainScene";
import { NetManager } from "../../../libs/tw/manager/NetManager";
import { DataManager } from "../../../libs/tw/manager/DataManager";
import { loadSvga } from "../../comm/loadSvga";
import { getSvga } from "../../utils";
import SceneCtrl from "../../ctrls/sceneCtrl";
import { G_GetHomeDataByKey, G_SetHomeDataByKey, G_UpdateHomeData, HOME } from "../Home";
import RulePanel from "../../Panels/RulePanel";
import WareHousePanel from "../../Panels/WareHousePanel";
import NewUserPanel from "../../Panels/NewUserPanel";
import OldUserPanel from "../../Panels/OldUserPanel";
import GameGroupPanel from "../../Panels/GameGroupPanel";
import Guide from "../../Panels/Guide";
import ShopPanel from "../../Panels/ShopPanel";
import TopLayerCtrl from "../../ctrls/topLayerCtrl";
import { Tools } from "../../Tools";
import { getlogItem } from "../../comm/getlogItem";
import { NetName } from "../../../libs/tw/enum/NetName";
import { getToken } from "./Const";
import { wait } from "../../comm/GameConst";
import Event = egret.Event;

export let propData = {
    sp_food_1: {
        name: 'food',
        key:'饲料',
    },
    sp_food_2: {
        name: 'water',
        key:'水'
    },
    sp_prop_1: {
        name: 'speed',
        key:'加速卡'
    },
};

export default class MainUI extends ComponentBase {

    public uiLayer: eui.Group;
    public propPanel: eui.Group;
    public speedGroup: eui.Group;
    public speedNum: eui.Label;
    public foodGroup: eui.Group;
    public foodNum: eui.Label;
    public waterGroup: eui.Group;
    public waterNum: eui.Label;
    public avatarPanel: eui.Group;
    public avatarImg: eui.Image;
    public avatarMask: eui.Image;
    public userName: eui.Label;
    public userGold: eui.Label;
    public medal: eui.Image;
    public warehouseBtn: eui.Button;
    public taskBtn: eui.Button;
    public recordBtn: eui.Button;
    public ruleBtn: eui.Button;
    public exchangeBtn: eui.Button;
    public gameGroupBtn: eui.Button;
    public shopBtn: eui.Button;
    public tipGroup: eui.Group;
    public tipLabelGroup: eui.Group;
    public tipLabel1: eui.Label;
    public tipLabel2: eui.Label;
    public tipLabelMask: eui.Rect;

    private tip1;
    private tip2;

    /**需要根据满仓值改变图片的道具 */
    public propImgByState = ['sp_food_1', 'sp_food_2']

    constructor() {
        super();
    }

    protected getTapEvts(): any[] {
        return super.getTapEvts().concat([
            [this, M_HideOption, this],
            [this.taskBtn, this.onTap, this],
            [this.warehouseBtn, this.onTap, this],
            [this.recordBtn, this.onTap, this],
            [this.shopBtn, this.onTap, this],
            [this.exchangeBtn, this.onTap, this],
            [this.avatarImg, this.onTap, this],
            [this.ruleBtn, this.onTap, this],
            [this.gameGroupBtn, this.onTap, this],
        ]).concat([ // OptionPanel
            [this.foodGroup, this.onTapOption, this],
            [this.waterGroup, this.onTapOption, this],
            [this.speedGroup, this.onTapOption, this],
        ])
    }

    private onTapOption(e: egret.TouchEvent) {
        btnDelay(e.target);
        switch (e.target) {
            case this.foodGroup:    // 食物数量区域
                showToast('点击饿了的动物才能进行喂食哦');
                break;
            case this.waterGroup:   // 水壶数量区域
                showToast('点击渴了的植物才能浇水哦');
                break;
            case this.speedGroup:
                showToast('点击植物/动物去加速成长时间');
                break;
            default:
                break;
        }
    }

    private async onTap(e: egret.TouchEvent) {
        btnDelay(e.target);
        switch (e.target) {
            case this.taskBtn:  // 任务按钮
                NetManager.ins.clickLog(getlogItem(4));
                PanelCtrl.instance.show(ModuleTypes.TASK_PANEL);
                break;

            case this.warehouseBtn: // 仓库按钮
                NetManager.ins.clickLog(getlogItem(5));
                PanelCtrl.instance.show(WareHousePanel);
                break;

            case this.avatarImg:    // 头像
                // window['share']();
                break;

            case this.recordBtn:    // 兑换记录
                window.location.href = window['record'];
                break;

            case this.shopBtn:  // 商店
                NetManager.ins.clickLog(getlogItem(6));
                PanelCtrl.instance.show(ShopPanel);

                break;

            case this.gameGroupBtn:  // 游戏合集
                NetManager.ins.clickLog(getlogItem(3));
                PanelCtrl.instance.show(GameGroupPanel);
                break;

            case this.exchangeBtn:  // 兑换
                NetManager.ins.clickLog(getlogItem(2));
                SceneCtrl.instance.change(ModuleTypes.EXCHANGE_SCENE);
                break;

            case this.ruleBtn:
                NetManager.ins.clickLog(getlogItem(1));
                PanelCtrl.instance.show(RulePanel);
                break;
            default:
                break;
        }
    }

    protected start() {
        super.start();
        this.initUI();
    }

    private async initUI() {
        this.uiLayer.height = 750 / window.innerWidth * window.innerHeight;
        this.touchEnabled = true;

        this.warehouseBtn.anchorOffsetX = 53.5;
        this.warehouseBtn.anchorOffsetY = 60.5;

        // this.ruleBtn.y = (this.ruleBtn.y - (MainIns().gameLayer.height - MainIns().group.height) / 2);

        this.avatarImg.mask = this.avatarMask;

        this.tipLabelGroup.mask = this.tipLabelMask;

        this.tip1 = this.tipLabel1;
        this.tip2 = this.tipLabel2;
        // this.tipLabel(18375);

        this.getUserInfo();
        await this.getPropInfoByBI();

        // console.log(G_GetHomeDataByKey(HOME.GOLD));
        // const unitName = DataManager.ins.getData(NetName.GET_PROJECTUSERINFO).data.unitName;
        // this.userGold.text = `${unitName}：${G_GetHomeDataByKey(HOME.GOLD)}`;

        // 埋点
        NetManager.ins.showLog(getlogItem(1));
        NetManager.ins.showLog(getlogItem(2));
        NetManager.ins.showLog(getlogItem(3));
        NetManager.ins.showLog(getlogItem(4));
        NetManager.ins.showLog(getlogItem(5));
        NetManager.ins.showLog(getlogItem(6));

        this.tipGroup.scaleX = 1.2;
        this.tipGroup.scaleY = 1.2;
        // this.tipGroup.x -= 80;

        this.addEventListener(Event.ENTER_FRAME, this.onUpdate, this);
    }

    private onUpdate() {
        if (this.tip1 && this.tip2) {
            this.tip1.x--;
            this.tip2.x = this.tip1.x + this.tip1.width

            if (this.tip1.x <= -860) {
                let temp = this.tip2;
                this.tip2 = this.tip1;
                this.tip1 = temp;
            }
        }
    }

    public async addGold() {
        const mv: egret.MovieClip = await loadSvga(getSvga('欢趣豆收取'))
        mv.x = this.avatarPanel.x + 100;
        mv.y = this.avatarPanel.y;
        this.addChild(mv);
        mv.addEventListener(egret.Event.COMPLETE, () => {
            mv.stop();
            this.removeChild(mv);
            this.getGoldNum();
        }, this);
    }

    public warehouseEffect() {
        // 0s(100%,100%)-0.1s(120%,80%)-0.2s(100%,100%)
        egret.Tween.removeTweens(this.warehouseBtn);
        egret.Tween.get(this.warehouseBtn)
            .to({ scaleX: 1.2, scaleY: 0.8 }, 100, egret.Ease.quadInOut)
            .to({ scaleX: 1, scaleY: 1 }, 100, egret.Ease.quadInOut);
    }

    public async getPropInfo() {
        await G_UpdateHomeData();
        this[`${propData['sp_food_1'].name}Group`].visible = true;
        this[`${propData['sp_food_2'].name}Group`].visible = true;
        this.setPropInfo();
    }

    public async getPropInfoByBI() {
        await G_UpdateHomeData();
        this[`${propData['sp_food_1'].name}Group`].visible = true;
        this[`${propData['sp_food_2'].name}Group`].visible = true;
        this.setPropInfoByBI();
    }
    //新道具数量显示
    public setPropInfoByBI() {
        const data = G_GetHomeDataByKey(HOME.PROP);
        for (let k in propData) {
            let maxcount = Tools.frontInfo.data.spLimit || 100;
            let textflow = [];
            let textLabel = this[`${propData[k].name}Num`];
            let textBg = this[`${propData[k].name}NumBg`];
            let propIcon = this[`${propData[k].name}Icon`] as eui.Image;
            if (data[k] > maxcount) {
                textflow = [
                    { text:  data[k]+ "/", style: { textColor: 0xff0000 } },
                    { text: maxcount, style: { textColor:  0xFFFFFF} },
                ];
            } else {
                textflow = [
                    { text: data[k] + "/" + maxcount, style: { textColor: 0xFFFFFF } },
                ];
            }
            if (this.propImgByState.indexOf(k) >= 0) {
                let typeStr = this.getIconState(data[k], maxcount);
                propIcon.source = `${propData[k].key}_${typeStr}_png`
            }
            textLabel.textFlow = textflow;
            if ((textLabel.textWidth + 20) > textBg.width)
                textBg.width = textLabel.textWidth + 20;
            // textLabel.text = '× ' + data[k];
            console.log('每一种的文本宽度--->>', textLabel.textWidth)
            DataManager.ins.updateData(propData[k].name, data[k]);
        }
        this[`${propData['sp_prop_1'].name}Group`].visible = data['sp_prop_1'] > 0;

        const unitName = DataManager.ins.getData(NetName.GET_PROJECTUSERINFO).data.unitName;
        this.userGold.text = `${unitName}：${G_GetHomeDataByKey(HOME.GOLD)}`;
    }

    /** 根据道具的当前值与满仓值来计算当前道具的展示 */
    getIconState(curCnt, maxCnt) {
        let step1 = Math.floor(maxCnt*0.2);
        let step2 = Math.floor(maxCnt*0.8);
        if(curCnt<=step1) return '空';
        if(curCnt>step1&&curCnt<=step2) return '半'
        if(curCnt>step2) return '满'
        return '空'
    }

    public setPropInfo() {
        this.setPropInfoByBI();

        // const data = G_GetHomeDataByKey(HOME.PROP);
        // for (let k in propData) {
        //     this[`${propData[k].name}Num`].text = '× ' + data[k];
        //     DataManager.ins.updateData(propData[k].name, data[k]);
        // }
        // this[`${propData['sp_prop_1'].name}Group`].visible = (data['sp_prop_1'] > 0);

        // const unitName = DataManager.ins.getData(NetName.GET_PROJECTUSERINFO).data.unitName;
        // this.userGold.text = `${unitName}：${G_GetHomeDataByKey(HOME.GOLD)}`;
    }

    public async getGoldNum() {
        NetManager.ins.getProjectUserInfo((success, res) => {
            if (!success) {
                return;
            }
            const data = res.data;
            this.userGold.text = `${data.unitName}：${data.consumerCredits}`;
            G_SetHomeDataByKey(HOME.GOLD, data.consumerCredits);
        });
    }

    private async getUserInfo() {

        const consumerInfo = Tools.consumerInfo;
        if (!consumerInfo) {
            this.userName.text = '欢趣使者';
            return;
        }

        const { newUser, nickname, ifLogin, popup, loginPresent } = consumerInfo;
        this.userName.text = (!consumerInfo || !nickname || (nickname == 'null'))
            ? '小e' : ((nickname.length > 7) ? nickname.slice(0, 7) + '...' : nickname);

        // 登陆奖励
        const loginPrize = async () => {
            if (ifLogin) {
                Tools.consumerInfo.ifLogin = false;
                // NetManager.ins.doTask((success, res) => {
                //     if (!success) {
                //         return;
                //     }
                //     TopLayerCtrl.instance.show(ModuleTypes.TASK_TOAST, {
                //         title: '登陆奖励',
                //         food: loginPresent.spFood1RewardNum,
                //         water: loginPresent.spFood2RewardNum,
                //     });
                //     MainIns().mainUI.getPropInfo();
                // }, 1);

                if (loginPresent['sp_food_1'] || loginPresent['sp_food_2']) {
                    await wait(800);
                    TopLayerCtrl.instance.show(ModuleTypes.TASK_TOAST, {
                        title: '登陆奖励',
                        food: loginPresent['sp_food_1'] || 0,
                        water: loginPresent['sp_food_2'] || 0,
                    });
                }
            }
        };

        if (newUser) {  // 新用户出引导，TODO 因为换了活动，则不存在老用户
            Tools.consumerInfo.newUser = false;

            // TODO 是新用户直接发奖吧
            getToken().then((token) => {
                if (!token) {
                    showToast('网络异常，请刷新页面重试');
                    return;
                }
                NetManager.ins.newUserPrize(async (res, success) => {
                    if (!success) {
                        showToast('网络异常，请稍后再试');
                        return;
                    }

                    G_UpdateHomeData().then(() => {
                        MainIns().mainUI.setPropInfo();
                    });
                }, token);
            });

            PanelCtrl.instance.show(Guide, {
                call: () => {
                    if (popup) {
                        Tools.consumerInfo.popup = false;
                        PanelCtrl.instance.show(NewUserPanel, { f: loginPrize });
                    }
                    return popup;
                },
                f: loginPrize
            }, false);
        } else if (popup) { // 不是新用户，但是要弹弹窗
            Tools.consumerInfo.popup = false;
            PanelCtrl.instance.show(OldUserPanel, { f: loginPrize });
        } else if (ifLogin) {
            loginPrize();   // 首次登陆
        }
    }

    destroy() {
        super.destroy();
    }

    get skinKey() {
        return 'MainUI';
    }

    public get groupName() {
        return 'main_ui';
    }
}
