import Panel from "../views/Panel";
import {MainDispatcher, MainIns} from "../Scenes/MainScene/MainScene";
import Tween = egret.Tween;
import {btnDelay, showToast} from "../comm/UtilsConst";
import {G_GetHomeDataByKey, HOME} from "../Scenes/Home";
import Loading from "../loading/Loading";
import {NetManager} from "../../libs/tw/manager/NetManager";
import {Tools} from "../Tools";

export default class ShopBuyPanel extends Panel {
    public closeBtn: eui.Image;
    public buyBtn: eui.Button;
    // public buyBtn1: eui.Button;
    public nameTxt: eui.Label;
    public img: eui.Image;
    public tipTxt: eui.Label;


    public get skinKey() {
        return 'ShopBuyPanel';
    }

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

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

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

    protected start() {
        super.start();

        this.initUI();

        this.img.source = `prop_${this.data.key}_png`;
        this.nameTxt.text = this.data.name;
        this.tipTxt.text = `所需欢趣豆：${this.data.needGold}`;

        // if (this.data.type == 'prop') {
        //     this.buyBtn.visible = false;
        // } else {
        //     this.buyBtn1.visible = false;
        // }

        this.buyBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.buy, this);
        // this.buyBtn1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.buy, this);
    }

    private buy(e) {
        if (G_GetHomeDataByKey(HOME.GOLD) < this.data.needGold) {
            showToast('啊哦，欢趣豆不足，快去攒豆吧');
            return;
        }

        Loading.instace.show();

        Tools.creditsCost('join_7', 'join', this.data.needGold, 'act_name')
            .then((ticket) => {
                // 兑换商品
                NetManager.ins.propExchange((success, res) => {
                    Loading.instace.hide();

                    if (!success) {
                        showToast('消耗欢趣豆失败，请稍后再试');
                        return;
                    }

                    this.hidePanel();

                    showToast('兑换成功，可返回农场使用');

                    this.data.updateCall();

                    MainIns().mainUI.getPropInfo();

                    this.data.call();

                }, this.data.spId, ticket, this.data.num);
            })
            .catch(() => {
                this.hidePanel();

                showToast('消耗欢趣豆失败，请稍后再试');
                Loading.instace.hide();
            });
    }

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

    private initUI(): void {
        this.y = 750 / window.innerWidth * window.innerHeight * 0.2;
    }

    destroy() {
        super.destroy();
        this.buyBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchClose, this);
    }

}
