import Panel from "../views/Panel";
import TopLayerCtrl from "../ctrls/topLayerCtrl";
import {ModuleTypes} from "../types/sceneTypes";
import {NetManager} from "../../libs/tw/manager/NetManager";
import {btnDelay, preLoadRes} from "../comm/UtilsConst";
import {MainDispatcher} from "../Scenes/MainScene/MainScene";
import {G_GetHomeDataByKey, G_UpdateHomeData, HOME} from "../Scenes/Home";
import SceneCtrl from "../ctrls/sceneCtrl";
import Tween = egret.Tween;
import {getSkinPath} from "../utils";
import Component = eui.Component;
import TouchEvent = egret.TouchEvent;

export const productData = {
    'sp_1': {   // 鸡蛋
        key: 'sp_1',
        name: 'egg',
        nameLabel: '鸡蛋',
        numLabel: '个',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_2': {   // 大米
        key: 'sp_2',
        name: 'wheat',
        nameLabel: '大米',
        numLabel: '袋',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_3': {   // 玉米
        key: 'sp_3',
        name: 'corn',
        nameLabel: '玉米',
        numLabel: '个',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_4': {   // 牛奶
        key: 'sp_4',
        name: 'milk',
        nameLabel: '牛奶',
        numLabel: '瓶',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_5': {   // 土豆
        key: 'sp_5',
        name: 'potato',
        nameLabel: '土豆',
        numLabel: '袋',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_6': {   // 核桃
        key: 'sp_6',
        name: 'walnut',
        nameLabel: '核桃',
        numLabel: '袋',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_7': {   // 核桃
        key: 'sp_7',
        name: 'apple',
        nameLabel: '苹果',
        numLabel: '个',
        price: 0,
        total: 0,
        item: null,
    },
    'sp_8': {   // 核桃
        key: 'sp_8',
        name: 'papaya',
        nameLabel: '木瓜',
        numLabel: '个',
        price: 0,
        total: 0,
        item: null,
    }
};


export const seedData = {
    'sp_seed_1': {   // 鸡
        key: 'sp_seed_1',
        name: 'chicken',
        nameLabel: '鸡',
        total: 0,
        item: null,
    },
    'sp_seed_2': {   // 水稻
        key: 'sp_seed_2',
        name: 'wheat',
        nameLabel: '水稻',
        total: 0,
        item: null,
    },
    'sp_seed_3': {   // 玉米
        key: 'sp_seed_3',
        name: 'corn',
        nameLabel: '玉米',
        total: 0,
        item: null,
    },
    'sp_seed_4': {   // 牛奶
        key: 'sp_seed_4',
        name: 'cattle',
        nameLabel: '牛',
        total: 0,
        item: null,
    },
    'sp_seed_5': {   // 土豆
        key: 'sp_seed_5',
        name: 'potato',
        nameLabel: '土豆',
        total: 0,
        item: null,
    },
    'sp_seed_6': {   // 核桃
        key: 'sp_seed_6',
        name: 'walnut',
        nameLabel: '核桃',
        total: 0,
        item: null,
    },
    'sp_seed_7': {   // 苹果
        key: 'sp_seed_7',
        name: 'apple',
        nameLabel: '苹果',
        total: 0,
        item: null,
    },
    'sp_seed_8': {   // 木瓜
        key: 'sp_seed_8',
        name: 'papaya',
        nameLabel: '木瓜',
        total: 0,
        item: null,
    }
};

export default class WareHousePanel extends Panel {
    public closeBtn: eui.Image;
    public cropGroup: eui.Group;
    public record_btn: eui.Image;
    public cropNoneImg: eui.Image;
    public crops: eui.Scroller;
    public seedGroup: eui.Group;
    public seedNoneImg: eui.Image;
    public seeds: eui.Scroller;
    public tableSeed: eui.Button;
    public tableCrop: eui.Button;

    public get skinKey() {
        return 'WareHouse'
    }

    public get groupName() {
        return 'warehouse'
    }

    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.record_btn, this.onTap, this],
            [this.tableSeed, this.onTap, this],
            [this.tableCrop, this.onTap, this],
        ]);
    }

    private onTap(e: egret.TouchEvent) {
        switch (e.target) {
            case this.record_btn:   // 售卖记录
                btnDelay(this.record_btn);
                TopLayerCtrl.instance.show(ModuleTypes.SELL_RECORD, {}, .3);
                break;

            case this.tableSeed:   // 种子区
                this.showSeed(true);
                break;

            case this.tableCrop:   // 作物区
                this.showSeed(false);
                break;

            default:
                break;
        }
    }

    protected async start() {
        super.start();
        NetManager.ins.priceInfo((success, res) => {
            if (!success) {
                return;
            }
            const data = res.data;
            for (let k in productData) {
                productData[k].price = data[k];
            }
        });


        this.initUI();

        await this.getWareHouseInfo();

        preLoadRes('sell_panel', 'sellRecord', 'selled_panel');
    }

    private initUI(): void {
        let i = 0;
        for (let k in productData) {
            const data = productData[k];
            const item = new WareHouseCrop(data);
            //@ts-ignore
            this.crops.viewport.addChild(item);
            item.x = i % 2 * 354;
            item.y = ~~(i / 2) * 409;
            item.visible = false;
            productData[k].item = item;
            i++;
        }

        for (let k in seedData) {
            const data = seedData[k];
            const item = new WareHouseSeed(data);
            //@ts-ignore
            this.seeds.viewport.addChild(item);
            item.x = i % 2 * 354;
            item.y = ~~(i / 2) * 359;
            item.visible = false;
            seedData[k].item = item;
            i++;
        }

        this.showSeed(false);
    }

    onTouchClose(): any {
        return super.onTouchClose();
    }

    initEvents() {
        super.initEvents();
        MainDispatcher.addEvent('updateWareHouse', this.getWareHouseInfo, this);
        MainDispatcher.addEvent('closeWareHouse', this.onTouchClose, this);
    }

    removeEvents() {
        super.removeEvents();
        MainDispatcher.removeEvent('updateWareHouse', this.getWareHouseInfo, this);
        MainDispatcher.removeEvent('closeWareHouse', this.onTouchClose, this);
    }

    destroy() {
        super.destroy();
    }

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

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

    /**
     * 仓库排列
     */
    private setUI() {

        const showProp = [];
        for (let k in productData) {
            const {total, item} = productData[k];
            if (total > 0) {
                showProp.push(item);
            } else {
                item.x = item.y = 0;
            }
            item.updateData(productData[k]);
        }

        showProp.forEach((v, i) => {
            v.x = 30+ i % 2 * 344;
            v.y = ~~(i / 2) * 409;
            v.visible = true;
        });
        console.log('aaa---->>',productData)

        this.cropNoneImg.visible = (showProp.length <= 0);


        const showSeed = [];
        for (let k in seedData) {
            const {total, item} = seedData[k];
            if (total > 0) {
                showSeed.push(item);
            } else {
                item.x = item.y = 0;
            }
            item.updateData(seedData[k]);
        }

        showSeed.forEach((v, i) => {
            v.x = i % 2 * 354;
            v.y = ~~(i / 2) * 359;
            v.visible = true;
        });

        this.seedNoneImg.visible = (showSeed.length <= 0);
    }

    private async getWareHouseInfo() {
        await G_UpdateHomeData();
        const product = G_GetHomeDataByKey(HOME.PRODUCT);
        for (let k in product) {
            productData[k].total = product[k];
        }
        console.log('testhsuju--->>',product)

        const seed = G_GetHomeDataByKey(HOME.SEED);
        for (let k in seed) {
            seedData[k].total = seed[k];
        }

        this.setUI();
    }
}


/**
 * 倉庫農作物item
 */
class WareHouseCrop extends Component {
    public bg: eui.Image;
    public sellBtn: eui.Image;
    public label: eui.Label;
    public exBtn: eui.Image;

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

        this.initUi(data);

        this.initEvent();
    }

    private initUi(data?) {
        this.updateUI();
    }

    private updateUI() {
        this.bg.source = `${this.data.name}_bg_png`;
        this.label.text = `数量：${this.data.total}`;
    }

    private initEvent() {
        this.sellBtn.addEventListener(TouchEvent.TOUCH_TAP, this.tapBtn, this);
        this.exBtn.addEventListener(TouchEvent.TOUCH_TAP, this.tapBtn, this);
    }

    private tapBtn(e) {
        switch (e.target) {
            case this.sellBtn:
                btnDelay(this.sellBtn);
                TopLayerCtrl.instance.show(ModuleTypes.SELL_PANEL, {key: this.data.key, total: this.data.total}, .4);
                break;

            case this.exBtn:
                btnDelay(this.exBtn);
                SceneCtrl.instance.change(ModuleTypes.EXCHANGE_SCENE);
                break;
        }
    }

    /**
     * 更新一下数据
     * @param data
     * @private
     */
    public updateData(data) {
        this.data = data;
        this.updateUI();
    }

}

/**
 * 仓库种子item
 */
class WareHouseSeed extends Component {
    public nameTxt: eui.Label;
    public img: eui.Image;
    public tipTxt: eui.Label;
    public tipImg: eui.Image;

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

        this.initUi(data);

        this.initEvent();
    }

    private initUi(data?) {
        console.log(data);
        this.img.source = `prop_${data.name}_png`;
        this.nameTxt.text = data.nameLabel;
        // this.tipImg.visible = (data.name == 'chicken' || data.name == 'wheat');
        this.tipImg.visible = false;//(data.name == 'wheat');
        this.updateUI();

    }

    private updateUI() {
        this.tipTxt.text = `数量：${this.data.total}`;
    }

    private initEvent() {

    }

    /**
     * 更新一下数据
     * @param data
     * @private
     */
    public updateData(data) {
        this.data = data;
        this.updateUI();
    }

}
