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";

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 title:eui.Label;
    public introduce:eui.Label;
    public stock:eui.Label;
    public titleImg:eui.Image;
    public titleMask:eui.Image;

    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.btn, this.onTap, this],
        ])
    }

    private onTap() {
        btnDelay(this.btn);
        if(this.data.stock <= 0) {
            showToast('商品无库存，耐心等待商品补货后再来吧');
            return;
        }
        if(!this.canGet()) {
            showToast('啊哦，合成所需食材不足，快去赚食材吧');
            return;
        }
        NetManager.ins.prizeExchange((success, res) => {
            if(!success && res.code == "300061"){
                showToast(res.message);
                return;
            }
            if(!success) {
                showToast('啊哦...目前无法兑换哦');
                return;
            }
            PanelCtrl.instance.show(ModuleTypes.EXCHANGED_PANEL, res.data);
        }, this.data.strategyId);

    }

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

    }

    private initUI(): void {
        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();
    }

    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'
    }

}
