import Panel from "../views/Panel";
import {getSkinPath} from "../utils";
import {NetManager} from "../../libs/tw/manager/NetManager";
import topLayerCtrl from "../ctrls/topLayerCtrl";
import {ModuleTypes} from "../types/sceneTypes";
import Tween = egret.Tween;
import Component = eui.Component;
import TouchEvent = egret.TouchEvent;
import {getlogItem} from "../comm/getlogItem";
import { G_GetHomeDataByKey, HOME } from "../Scenes/Home";
import { showToast } from "../comm/UtilsConst";

const propData = [
    {
        key: 'speed',
        spId: 'sp_prop_1',
        name: '加速卡',
        price: 0,
        stock: 0,
        introduce: '加速作物成长，每张加速卡可减免4小时的成长时长',
        bid: 19,
    },
    {
        key: 'water',
        spId: 'sp_food_2',
        name: '水',
        price: 0,
        stock: 0,
        introduce: '用于浇灌植物成长，每使用一次消耗一壶水',
        bid: 20,
    },
    {
        key: 'food',
        spId: 'sp_food_1',
        name: '饲料',
        price: 0,
        stock: 0,
        introduce: '用于喂养动物成长，每使用一次消耗一袋饲料',
        bid: 21,
    },
];


const seedData = [
    {
        key: 'chicken',
        name: '鸡',
        spId: 'sp_seed_1',
        price: 0,
        stock: 0,
        bid: 27,
    },
    {
        key: 'wheat',
        name: '水稻种子',
        spId: 'sp_seed_2',
        price: 0,
        stock: 0,
        bid: 22,
    },
    {
        key: 'corn',
        name: '玉米种子',
        spId: 'sp_seed_3',
        price: 0,
        stock: 0,
        bid: 24,
    },
    {
        key: 'cattle',
        name: '牛',
        spId: 'sp_seed_4',
        price: 0,
        stock: 0,
        bid: 26,
    },
    {
        key: 'potato',
        name: '土豆种子',
        spId: 'sp_seed_5',
        price: 0,
        stock: 0,
        bid: 23,
    },
    {
        key: 'walnut',
        name: '核桃种子',
        spId: 'sp_seed_6',
        price: 0,
        stock: 0,
        bid: 25,
    },
    {
        key:'apple',
        name:'苹果种子',
        spId:'sp_seed_7',
        price:0,
        stock:0,
        bid:0,
    },
    {
        key:'papaya',
        name:'木瓜种子',
        spId:'sp_seed_8',
        price:0,
        stock:0,
        bid:0,
    }
];

export default class ShopPanel extends Panel {
    public closeBtn: eui.Button;
    public tableSeed: eui.Button;
    public tableProp: eui.Button;
    public seedGroup: eui.Scroller;
    public propGroup: eui.Scroller;


    public get skinKey() {
        return 'ShopPanel'
    }

    public get groupName() {
        return 'shop'
    }

    constructor(data?) {
        super(data);
    }

    onShowAnim() {
        const canvasH = 750 / window.innerWidth * window.innerHeight;
        Tween.get(this).set({y: canvasH}).to({y: canvasH - this.height}, 300, egret.Ease.quadInOut);
    }

    protected getTapEvts(): any[] {
        return super.getTapEvts().concat([
            [this.tableProp, this.onTap, this],
            [this.tableSeed, this.onTap, this],
        ]);
    }

    private onTap(e) {
        this.showSeed(e.target == this.tableSeed);
    }

    protected async start() {
        super.start();

        await this.getPropInfo();
        this.initUI();
    }

    private initUI(): void {

        // 默认种子不可点击，道具可点击
        this.showSeed(true);

        propData.forEach((v, i) => {
            v['updateCall'] = this.updateItems;
            // @ts-ignore
            const item = this.propGroup.viewport.addChild(new ShopItem({...v, type: 'prop'}));
            item.x = (i % 2) * 351;
            item.y = ~~(i / 2) * 369;
        });

        seedData.forEach((v, i) => {
            v['updateCall'] = this.updateItems;
            // @ts-ignore
            const item = this.seedGroup.viewport.addChild(new ShopItem({...v, type: 'seed'}));
            item.x = (i % 2) * 351;
            item.y = ~~(i / 2) * 409;
        });
    }

    private updateItems = async () => {
        await this.getPropInfo();

        propData.forEach((v, i) => {
            // @ts-ignore
            this.propGroup.viewport.$children[i].updateData(v);
        });

        seedData.forEach((v, i) => {
            // @ts-ignore
            this.seedGroup.viewport.$children[i].updateData(v);
        });
    }

    /**
     * 是否是种子区域
     */
    private showSeed(seed: boolean) {
        this.tableSeed.enabled = !seed;
        this.tableProp.enabled = seed;
        if (seed) {
            this.addChild(this.removeChild(this.tableProp));
            this.addChild(this.removeChild(this.tableSeed));
        } else {
            this.addChild(this.removeChild(this.tableSeed));
            this.addChild(this.removeChild(this.tableProp));
        }

        this.seedGroup.visible = seed;
        this.propGroup.visible = !seed;
    }

    destroy() {
        super.destroy();
    }

    /**
     * 获得道具库存价格信息
     */
    private getPropInfo() {
        return new Promise<void>((resolve, reject) => {
            NetManager.ins.propInfo((success, res) => {
                if (!success) {
                    reject();
                    return;
                }
                let data = {};
                res.data.forEach((v) => {
                    data[v.spId] = {
                        stock: v.stock,
                        price: v.price,
                    };
                });

                for (let i = 0; i < propData.length; i++) {
                    const d = propData[i];
                    d.price = data[d.spId].price;
                    d.stock = data[d.spId].stock;
                }

                for (let i = 0; i < seedData.length; i++) {
                    const d = seedData[i];
                    d.price = data[d.spId].price;
                    d.stock = -1;   // stock == -1 则是种子，种子无库存
                }
                resolve();
            });
        });
    }
}


/**
 * 商店item
 */
class ShopItem extends Component {
    public subBtn: eui.Button;
    public addBtn: eui.Button;
    public buyBtn: eui.Button;
    public numTxt: eui.Label;
    public nameTxt: eui.Label;
    public img: eui.Image;
    public tipTxt: eui.Label;
    public propBuyBtn: eui.Button;

    public cntBg:eui.Image;
    public imgBigBg:eui.Image;
    public imgBg:eui.Image;

    public tipImg:eui.Image;


    private num: number = 0;

    constructor(
        private data?
    ) {
        super();
        this.skinName = getSkinPath('ShopItem');

        this.initUi(data);

        this.initEvent();
    }

    private initUi(data?) {
        this.img.source = `prop_${data.key}_png`;
        // chicken wheat
        // this.tipImg.visible = (data.key == 'chicken' || data.key == 'wheat');
        this.tipImg.visible = false//(data.key == 'wheat');
        this.nameTxt.text = data.name;
        this.tipTxt.text = `购买价格：${data.price}欢趣豆`;
        this.setNum(0);

        if (this.data.type == 'prop') {
            this.addBtn.visible = false;
            this.subBtn.visible = false;
            this.buyBtn.visible = false;
            this.numTxt.visible = false;
            this.cntBg.visible = false;
            this.imgBigBg.visible = false;
            this.num = 1;
            this.nameTxt.y = 186;

            this.propBuyBtn.enabled = (this.data.stock > 0);
        } else {
            this.propBuyBtn.visible = false;
            this.imgBg.visible = false;
            this.nameTxt.y = 176;
        }

        NetManager.ins.showLog(getlogItem(this.data.bid));

    }

    private initEvent() {
        this.buyBtn.addEventListener(TouchEvent.TOUCH_TAP, this.tapSeedBuy, this);
        this.propBuyBtn.addEventListener(TouchEvent.TOUCH_TAP, this.tapPropBuy, this);
        this.subBtn.addEventListener(TouchEvent.TOUCH_TAP, this.onNumBtn, this);
        this.addBtn.addEventListener(TouchEvent.TOUCH_TAP, this.onNumBtn, this);
    }

    private onNumBtn(e) {
        this.setNum(this.num += (e.target == this.addBtn ? 1 : -1));
    }

    /**
     * 买道具
     * @private
     */
    private async tapPropBuy() {
        NetManager.ins.clickLog(getlogItem(this.data.bid));
        let spId = this.data.spId;
        let spIds = ["sp_prop_1","sp_food_2","sp_food_1"];
        if(spIds.indexOf(spId)!=-1){
            let spdata1 = G_GetHomeDataByKey(HOME.PROP);
            let count = spdata1[spId];
            if(count>=100){
                showToast("已达上限");
                return;
            }
        }

        topLayerCtrl.instance.show(ModuleTypes.SHOP_BUY_PANEL, {
            ...this.data,
            needGold: this.data.price,
            num: this.num,
            call:()=>{}
        }, 0.7);
    }

    /**
     * 买种子
     * @private
     */
    private async tapSeedBuy() {
        NetManager.ins.clickLog(getlogItem(this.data.bid));

        const num = this.num;

        if (num == 0) return;

        const needGold = this.data.price * num;
        console.log(`%c购买${num}个，一个价格${this.data.price}, 需要${needGold}`, 'color:green');

        topLayerCtrl.instance.show(ModuleTypes.SHOP_BUY_PANEL, {
            ...this.data,
            needGold,
            num,
            call: () => {
                this.setNum(0);
            }
        }, 0.7);
    }

    /**
     * 更新一下数据
     * @param data
     * @private
     */
    public updateData(data) {
        this.data = data;
        this.tipTxt.text = `购买价格：${data.price}欢趣豆`;
        this.setNum(this.num);
    }


    // stock == -1 则是种子，种子无库存
    private setNum(num) {
        const {stock} = this.data;
        // if (stock != -1 && num > stock) {
        //     num = stock;
        // }

        this.subBtn.enabled = (num > 0);
        stock != -1 && (this.propBuyBtn.enabled = (num <= stock));
        this.buyBtn.enabled = (num > 0);

        this.num = num;

        this.numTxt.text = num + '';
    }

}
