import Panel from "../views/Panel";
import { productData } from "./WareHousePanel";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { ProgressNum } from "../components/ProgressNum";
import { MainDispatcher } from "../Scenes/MainScene/MainScene";
import { ModuleTypes } from "../types/sceneTypes";
import TopLayerCtrl from "../ctrls/topLayerCtrl";

export default class SellPanel extends Panel {
    public closeBtn: eui.Image;
    public titleImg: eui.Image;
    public nameLabel: eui.Label;
    public infoLabel: eui.Label;
    public totalLabel: eui.Label;
    public sellBtn: eui.Button;

    private key;    // 当前要卖的东西的id
    private total = 0;  // 总个数

    private numBar: ProgressNum = null;

    public get skinKey() {
        return 'SellPanel'
    }

    public get groupName() {
        return 'sell_panel'
    }

    constructor(data?) {
        super(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.sellBtn, this.doSell, this],
        ])
    }

    protected start() {
        super.start();

        this.initUI();
        MainDispatcher.addEvent('updateSellValue', this.updateSellValue, this);
    }

    private updateSellValue() {
        let value = this.numBar.value;
        this.sellBtn.enabled = (value > 0);
    }

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

        let d = productData[this.key];
        this.infoLabel.text = `一${productData[this.key].numLabel}${productData[this.key].nameLabel}=${productData[this.key].price}个欢趣豆`;

        this.nameLabel.text = d.nameLabel;
        this.titleImg.source = `sellTitle_${d.name}_png`;

        this.totalLabel.text = `共${this.data.total}${d.numLabel}`;

        this.numBar = new ProgressNum({total: this.total});
        this.addChild(this.numBar);
        this.numBar.x = this.width / 2 - this.numBar.width / 2;
        this.numBar.y = 400;

        this.updateSellValue();
    }

    /**
     * 发起售卖
     */
    private doSell() {
        this.sellBtn.touchEnabled = false;
        let count = this.numBar.value;
        NetManager.ins.doSell((success, res) => {
            this.sellBtn.touchEnabled = true;
            if(!success) {
                return;
            }
            let total = this.numBar.value * productData[this.key].price;
            TopLayerCtrl.instance.show(ModuleTypes.SELLED_PANEL, {name: productData[this.key].nameLabel, total: total}, .4);
        }, this.key, count);
    }

    destroy() {
        this.numBar.destroy();
        super.destroy();
    }

}
