import Panel from "../../Module/Panel";
import {_decorator, Button, Node, Sprite, Label} from "cc";
import {observer} from "../store/decorators";
import { showPanel, showToast } from "db://assets/Module/UIFast";
import ExchangeSuccess from "db://assets/Scripts/Panels/ExchangeSuccess";
import { creditsCost, sendWebNetWithToken, WebNetName } from "db://assets/Scripts/Utils/WebNet/WebNet";
import { _asyncThrottle } from "../Utils/Utils";

const {ccclass, property} = _decorator;

@observer
@ccclass('ProPop')
export default class ProPop extends Panel {

    static bundle = "PropPop";
    static skin = "PropPop";

    @property(Label) prizeName: Label = null;
    @property(Node) closeBtn: Node = null;
    @property(Node) btn: Node = null;
    @property(Sprite) prize: Sprite = null;
    @property(Label) explanation: Label = null;
    @property(Label) num: Label = null;

    exchangeInfo = {}

    onLoad() {
        this.closeBtn.on(Button.EventType.CLICK, this.clickClose)
        this.btn.on(Button.EventType.CLICK, this.clickExchange)
    }

    start() {
        const {consumeSp, item, conditionsItem} = this.data

        this.explanation.string = item.spDetail;

        const num = this.btn.getChildByName("num")
        num.getComponent(Label).string = consumeSp.quantity;

        this.prize.spriteFrame = item.optionImg;

        this.prizeName.string = item.optionName;
    }

    clickClose = () => {
        this.hidePanel();
    }

    clickExchange = _asyncThrottle(async () => {
        const { consumeSp, item, conditionsItem } = this.data;

        const {
            success: costSuc,
            ticket
        } = await creditsCost("exchange_1", "doExchange", `sp_deduct_desc`, consumeSp.quantity);

        if (!costSuc) {
            showToast("预扣积分失败");
            return;
        }

        //兑换接口
        const { success, data } = await sendWebNetWithToken(WebNetName.propExchange, {
            ticketNum: ticket,
            ruleId: item.ruleId,
            gear: conditionsItem.gear,
        });

        if (!success) return;

        this.exchangeInfo = data;

        // if (conditionsItem.credits >= consumeSp.quantity) {

            showPanel(ExchangeSuccess, {consumeSp, item, conditionsItem})

        // }
    })
}
