import Panel from "../views/Panel";
import { G_GetHomeDataByKey, G_UpdateHomeData, HOME } from "../Scenes/Home";
import { btnDelay, showToast } from "../comm/UtilsConst";
import { NetManager } from "../../libs/tw/manager/NetManager";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import SceneCtrl from "../ctrls/sceneCtrl";
import { getlogItem } from "../comm/getlogItem";
import WareHousePanel, { productData, seedData } from "./WareHousePanel";
import TopLayerCtrl from "../ctrls/topLayerCtrl";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";

export default class ExchangePanel extends Panel {
    public closeBtn: eui.Button;
    public propGroup: eui.Group;
    public sp_1_group: eui.Group;
    public sp_1_label: eui.Label;
    public add1: eui.Label;
    public sp_2_group: eui.Group;
    public sp_2_label: eui.Label;
    public add2: eui.Label;
    public sp_3_group: eui.Group;
    public sp_3_label: eui.Label;
    public add3: eui.Label;
    public sp_4_group: eui.Group;
    public sp_4_label: eui.Label;
    public btn: eui.Image;
    public btn_1: eui.Image;

    public title: eui.Label;
    public introduce: eui.Label;
    public stock: eui.Label;
    public titleImg: eui.Image;
    public titleMask: eui.Image;

    newextxt: eui.Label;
    constructor(data?) {
        super(data);
        console.error("兑换点击==》", this.data);
    }

    onShowAnim() {
        // const canvasH = 750 / window.innerWidth * window.innerHeight;
        egret.Tween.get(this).set({ alpha: 0 }).to({ alpha: 1 }, 233, egret.Ease.quadInOut);
    }

    protected getTapEvts(): any[] {
        return super.getTapEvts().concat([
            [this.btn, this.onTap, this],
            [this.btn_1, this.onTap, this],
        ])
    }

    private onTap(e: egret.TouchEvent) {
        btnDelay(e.target);
        switch (e.target) {
            case this.btn:
                if (this.data.stock <= 0) {
                    showToast('商品无库存，耐心等待商品补货后再来吧');
                    return;
                }
                console.log('库存是否充足--->>',this.canGet())
                if (!this.canGet()) {
                    // showToast('啊哦，合成所需食材不足，快去赚食材吧');
                    PanelCtrl.instance.show(ModuleTypes.EXCHANGED_PANEL, {
                        type: "fail"
                    });
                    return;
                }
                NetManager.ins.prizeExchange((success, res) => {
                    if (!success && res.code == "300061") {
                        showToast(res.message);
                        return;
                    }
                    if (!success) {
                        showToast('啊哦...目前无法兑换哦');
                        return;
                    }
                    let paneldata = res.data;
                    paneldata["type"] = "success";
                    PanelCtrl.instance.show(ModuleTypes.EXCHANGED_PANEL, paneldata);
                }, this.data.strategyId);
                break;
            case this.btn_1:
                console.error("卖掉点击===》");
                // this.hidePanel();
                // SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
                NetManager.ins.clickLog(getlogItem(5));
                // PanelCtrl.instance.show(WareHousePanel);
                let key = Object.keys(this.data.spMap)[0];
                let total = productData[key].total
                if(total<=0){
                    showToast('暂无农作物可出售')
                }else{
                    TopLayerCtrl.instance.show(ModuleTypes.SELL_PANEL, {key: key, total: total}, .4);
                }
                
                break;
            default:
                break;
        }
    }

    protected start() {
        this.titleMask.visible = false;
        this.titleImg.visible = false;
        this.y = 750 / window.innerWidth * window.innerHeight * 0.2;
        super.start();
        this.getHouseInfo();
        GDispatcher.addEvent('updateExchangePanel',this.getHouseInfo,this)

    }

    private async initUI() {
        this.titleMask.visible = true;
        this.titleImg.visible = true;
        
        this.y = 750 / window.innerWidth * window.innerHeight * 0.2;
        this.titleImg.mask = this.titleMask;
        this.titleImg.source = this.data.icon;
        // console.log(this.data);
        let title = this.data.name.split('_@_');
        // title[1].length >= 18 ? title[1] = title[1].slice(0, 17) + '\n' + title[1].slice(17) : 0;
        this.title.text = title[0];
        this.introduce.text = `商品介绍：${title[1] || '无'}`;
        this.stock.text = `剩余数量：${this.data.stock}`;
        // this.setNeed();
        // this.setBtn();

        let key0 = Object.keys(this.data.spMap)[0];
        let changespnum = this.data.spMap[key0];
        console.error("兑换id", changespnum);
        let danwei = productData[key0].numLabel;
        let iprice = productData[key0].price;
        let name = productData[key0].nameLabel;
        console.log('兑换所需-->',key0,productData[key0])
        if (iprice == 0) {
            NetManager.ins.priceInfo((success, res) => {
                if (!success) {
                    return;
                }
                const data = res.data;
                for (let k in productData) {
                    productData[k].price = data[k];
                }
                iprice = productData[key0].price;
                this.newextxt.text = `今天我需要「${changespnum}」${danwei}${name}跟你换${this.data.name}哦， 或者直接卖给我，每${danwei}可以得「${iprice}」欢趣豆。 考虑看看呢？`;
            });
        } else {
            this.newextxt.text = `今天我需要「${changespnum}」${danwei}${name}跟你换${this.data.name}哦， 或者直接卖给我，每袋可以得「${iprice}」欢趣豆。 考虑看看呢？`;
        }
    }

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

    private setBtn() {
        //TODO 不需要设置btn了！ 2021-05-10
        // this.canGet().then(
        //     (res) => {
        //         this.btn.source = 'ex_btn_png';
        //         this.btn.touchEnabled = true;
        //     },
        //     (err) => {
        //         this.btn.source = err;
        //         this.btn.touchEnabled = false;
        //     }
        // );
    }

    private canGet() {
        //TODO 不需要异步！直接判断！ 2021—05-10
        // return new Promise<boolean>((resolve, reject) => {
            const showList = [];
            for (let spk in this.data['spMap']) {
                showList.push(spk);
            }
            const products: {} = G_GetHomeDataByKey(HOME.PRODUCT);
            for (let v of showList) {
                if (this.data['spMap'][v] > products[v]) {   // 有一项不足，不能合成
                    // reject('ex_btn_dis_png');
                    // reject(false)
                    return false;
                }
            }
            return true
            // resolve(true);  // 以上都没有，可以合成
        // });
    }

    // 显示需要的道具
    private setNeed() {
        let showList = [];
        for (let spk in this.data['spMap']) {
            showList.push(spk);
        }
        // 设置道具下的label
        this.propGroup.width = 38 + 80 * (showList.length - 1);
        const products: {} = G_GetHomeDataByKey(HOME.PRODUCT);


        const spMap = this.data.spMap;

        showList.forEach((v, i) => {
            const group = this[`${v}_group`];
            const label = this[`${v}_label`];

            group.scaleX = 1.5;
            group.scaleY = 1.5;
            group.visible = true;
            group.x = 90 * i;
            label.textFlow = <Array<egret.ITextElement>>[
                {
                    text: products[v].toString(),
                    style: { "textColor": (products[v] < spMap[v]) ? 0xed3330 : 0xffffff }
                },
                { text: '/' + spMap[v], style: { "textColor": 0xffffff } }
            ];
        });

        // 显示+号
        for (let i = 1; i < showList.length; i++) {
            this[`add${i}`].visible = true;
            this[`add${i}`].x += i * 10;
        }
    }

    destroy() {
        super.destroy();
    }

    public get skinKey() {
        return 'ExchangePanel'
    }

    public get groupName() {
        return 'exchange_panel'
    }

}
