import Panel from "../views/Panel";
import { G_GetHomeDataByKey, 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 } from "./WareHousePanel";

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;
                }
                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);
                break;
            default:
                break;
        }
    }

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

    }

    private async initUI() {
        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;
        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}跟你换实物哦， 或者直接卖给我，每袋可以得「20」欢趣豆。 考虑看看呢？`;
            });
        } else {
            this.newextxt.text = `今天我需要「${changespnum}」${danwei}跟你换实物哦， 或者直接卖给我，每袋可以得「20」欢趣豆。 考虑看看呢？`;
        }
    }

    private setBtn() {
        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(): Promise<boolean> {
        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');
                    return;
                }
            }
            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'
    }

}
