import { ExchangeResultData } from './../../libs/tw/data/pets/ExchangeResultData';
import Panel from "../views/Panel";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { GetActToysListData } from "../../libs/tw/data/pets/GetActToysListData";
import { GetActToysItemData } from "../../libs/tw/data/pets/GetActToysItemData";
import { NetManager } from "../../libs/tw/manager/NetManager";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";
import { Buried } from "../../libs/tw/util/Buried";
import GuidePanel from "../guidePanel/GuidePanel";
import Loading from '../loading/Loading';

export class PropPanel extends Panel{

    public prop0num:eui.Label;
    public buyBtn0_prop:eui.Button;
    private gd:GetActToysItemData;
    public buyPopGroup:eui.Group;
    public mask1:eui.Rect;
    public closeBtn1:eui.Button;
    public downBtn:eui.Button;
    public upBtn:eui.Button;
    public costLb:eui.Label;
    public pNum:eui.Label;
    public buyCostBtn:eui.Button;

    // public guideBack: Function;
    private guideLayer: GuidePanel;

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

    //设置加载emxl的路径名字
    public get skinKey() { return 'PropPanel' }
	public get groupName() { return 'prop_panel'}

    initEvents():void{
        super.initEvents();
        this.buyBtn0_prop.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_buyBtn0_prop, this);
        this.closeBtn1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_closeBtn1, this);
        this.downBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_downBtn, this);
        this.upBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_upBtn, this);
        this.buyCostBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_buyCostBtn, this);
    }

    removeEvents():void{
        super.removeEvents();
        this.buyBtn0_prop.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_buyBtn0_prop, this);
        this.closeBtn1.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_closeBtn1, this);
        this.downBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_downBtn, this);
        this.upBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_upBtn, this);
        this.buyCostBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_buyCostBtn, this);
        
    }

    start(data?:any){
        this.percentHeight 	= 100;
        // this.guideBack = data;
    }

    protected onSkinComplete():void{
        super.onSkinComplete();

        // if(this.guideBack){
		// 	this.showGuide(9);
        // }

        this.once(egret.Event.ADDED_TO_STAGE,this.onLoad,this);
        if(this.stage){
            this.onLoad();
        }
    }

    private onLoad():void{
        //曝光埋点，使用/购买 按钮
        const dpm = Buried.connectDpm(110, 5, 1);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.showLog(exposure);

        this.showBuyPop(false);

        var aToys = DataManager.ins.getActToysListData;
        if(aToys && aToys[3]){
            var gdList:GetActToysListData = aToys[3];
            if(gdList.toyList && gdList.toyList.length){
                this.gd = gdList.toyList[0];
                this.prop0num.text = 'x' + this.gd.purchasedCount;

                if(this.gd.purchasedCount){
                    this.buyBtn0_prop.label = '使用';
                }else{
                    this.buyBtn0_prop.label = '购买';
                }

                this.pNum.text      = '1';
                this.costLb.text    = '花费:' + this.gd.cost * 1 + DataManager.ins.petIndexData.creditsUnitName;
            }
        }
    }

    private onClick_buyBtn0_prop():void{
        PanelCtrl.instance.btnDelay(this.buyBtn0_prop);
        if(this.buyBtn0_prop.label == '使用'){//点击使用
            if(DataManager.ins.petHomeInfoData.status != 2){
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,['只有出游状态下，才可以使用道具！']);
                return;
            }
            var pid:number = DataManager.ins.petHomeInfoData.petId;
            NetManager.ins.toyUse_xiecheng((success:boolean)=>{
                if(!success){
                    return;
                }
                this.gd.purchasedCount -= 1;

                if(!this.gd.purchasedCount){
                    this.buyBtn0_prop.label = '购买';
                }
                this.prop0num.text = 'x' + this.gd.purchasedCount;

                GDispatcher.dispatchEvent('useComplete');

                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,['道具使用成功！']);
            },DataManager.ins.petIndexData.activityId, this.gd.identifier, pid);

            // if(this.guideBack){
            //     this.hideGuide();
            //     this.hidePanel();
            //     this.guideBack(10);
            // }
        }else{//点击购买
            this.showBuyPop(true);
        }

        //点击埋点，使用/购买 按钮
        const dpm = Buried.connectDpm(110, 5, 1);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.clickLog(exposure);
    }

    private onClick_closeBtn1():void{
        this.showBuyPop(false);
    }

    private onClick_downBtn():void{
        this.ctlBuyNum(false);
    }

    private onClick_upBtn():void{
        this.ctlBuyNum(true);
    }

    //购买，并发送购买接口
    private onClick_buyCostBtn():void{
        Loading.instace.show();
        PanelCtrl.instance.btnDelay(this.buyCostBtn);
        var cost:number = Number(this.pNum.text) * this.gd.cost;
        if(cost <= DataManager.ins.petIndexData.credits){
            this.showBuyPop(false);
        
            // NetManager.ins.toyExchanges(function(){
            //     DataManager.ins.petIndexData.credits -= cost;
            //     this.gd.purchasedCount += Number(this.pNum.text);

            //     this.pNum.text = '1';
            //     this.costLb.text = '花费:' + this.gd.cost * 1 + DataManager.ins.petIndexData.creditsUnitName;
            //     this.buyBtn0_prop.label = '使用';
            //     this.prop0num.text = 'x' + this.gd.purchasedCount;

            //     GDispatcher.dispatchEvent('refreshCredits');
            // }.bind(this), this.gd.id, Number(this.pNum.text));
            var activityId:number = DataManager.ins.petIndexData.activityId;
            var petId:number = DataManager.ins.petHomeInfoData.petId;

            NetManager.ins.toyExchange_xc(function(success:boolean){
                if(!success){
                    Loading.instace.hide();
                    return;
                }
                NetManager.ins.exchangeResult(function(success:boolean){
                    Loading.instace.hide();
                    if(!success){
                        return;
                    }
                    DataManager.ins.petIndexData.credits -= cost;
                    this.gd.purchasedCount += Number(this.pNum.text);
    
                    this.pNum.text = '1';
                    this.costLb.text = '花费:' + this.gd.cost * 1 + DataManager.ins.petIndexData.creditsUnitName;
                    this.buyBtn0_prop.label = '使用';
                    this.prop0num.text = 'x' + this.gd.purchasedCount;
    
                    GDispatcher.dispatchEvent('refreshCredits');

                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,['购买成功！'], false);
                }.bind(this),activityId,petId,DataManager.ins.toyExchangesDataXC.orderId,function(data:ExchangeResultData):boolean{
                    console.log('购买轮询',data.status);
                    return Number(data.status) != 1;
                })
            }.bind(this), activityId, petId, this.gd.id,Number(this.pNum.text));
            //点击埋点，确认购买
            const dpm = Buried.connectDpm(110, 6, 1);
            const dcm = Buried.connectDcm(230, window['skinID'], 0);
            const embedDomain = DataManager.ins.petIndexData.embedDomain;
            const exposure = Buried.createExposure(dpm, dcm, embedDomain);
            NetManager.ins.clickLog(exposure);
        }else{
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,['您的' + DataManager.ins.petIndexData.creditsUnitName + '不足！'], false);
        }
        
    }

    /**
     * 控制显示隐藏数量框
     * @param isshow true 显示购买数量框
     */
    private showBuyPop(isshow:boolean):void{
        //曝光埋点，确认购买
        const dpm = Buried.connectDpm(110, 6, 1);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.showLog(exposure);

        this.pMask.visible = !isshow;
        this.mask1.visible = isshow;
        this.buyPopGroup.visible = isshow;
    }

    /**
     * 
     * @param isUp true 为增加购买数量 false 为减少
     */
    private ctlBuyNum(isUp:boolean):void{
        var num:number = Number(this.pNum.text);
        if(isUp){
            if((num + 1) * this.gd.cost <= DataManager.ins.petIndexData.credits){
                num += 1;
            }else{
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,['您的' + DataManager.ins.petIndexData.creditsUnitName + '不足！'], false);
            }
        }else{
            if(num > 1){
                num -= 1;
            }
        }

        this.pNum.text = num + '';
        this.costLb.text = '花费:' + this.gd.cost * num + DataManager.ins.petIndexData.creditsUnitName;
    }

    // private showGuide(index:number):void{
    //     this.hideGuide();
	// 	if(!this.guideLayer){
	// 		this.guideLayer = new GuidePanel();
	// 		this.addChild(this.guideLayer);
    //     }
        
    //     const thisH = Math.floor(750 / document.body.clientWidth * document.body.clientHeight)
    //     let w;
    //     let h;
    //     let x;
    //     let y;
    //     if(index == 9){//指向使用按钮
    //         w = 176;
    //         h = 66;
    //         x = this.buyBtn0_prop.x;
    //         y = thisH - this.buyBtn0_prop.bottom - (h+2);
    //     }
    //     this.guideLayer.updateData(index, x, y, w, h)
    // }

	// private hideGuide():void{
	// 	if(this.guideLayer){
	// 		this.guideLayer.dispose();
	// 		this.removeChild(this.guideLayer);
	// 		this.guideLayer = null;
	// 	}
	// }
}