import { LotteryType } from './../../libs/tw/enum/LotteryType';
import Panel from "../views/Panel";
import SceneCtrl from "../ctrls/sceneCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { NetManager } from "../../libs/tw/manager/NetManager";
import PanelCtrl from "../ctrls/panelCtrl";
import Loading from "../loading/Loading";
import { Buried } from '../../libs/tw/util/Buried';
export default class PrizePanel extends Panel {
    private mdata: any;
    public shareTips:eui.Label;
    public resultLb:eui.Label;
    public closeBtn:eui.Button;
    public shareBtn:eui.Button;
    public iknowBtn: eui.Button;
    public copyBtn:eui.Button;
    public rmbNumLb:eui.Label;
    public prizeNameLb: eui.Label;

    private isplug:boolean;
    private lottery:any;
    public get skinKey() { return 'PrizePanel' }
    public get groupName() { return 'prize_panel' }

    constructor(data: any) {
        super(data);
        this.mdata = data;

        if(this.mdata){
            this.isplug = this.mdata.isplug;
            if(this.isplug){
                this.lottery = DataManager.ins.getPlugOrderStatusData.lottery;
            }else{
                this.lottery = DataManager.ins.getCustomOrderStatusData.lottery;
                console.log('this.lottery=', this.lottery);
            }
        }
    }
    onSkinComplete(): void {
        super.onSkinComplete();

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

        this.showAct(function(){
            
        }.bind(this));
    }

    start(): void {
        this.percentHeight = 100;
    }

    initEvents(): void {
        super.initEvents();
        this.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_closeBtn, this);
        this.iknowBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ok, this);
        this.copyBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_copyBtn, this);
        this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
        
    }

    removeEvents(): void {
        super.removeEvents();
        if(this.iknowBtn){
            this.iknowBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ok, this);
        }
        if(this.shareBtn){
            this.shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
        }

        if(this.copyBtn){
            this.copyBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_copyBtn, this);
        }

        if(this.closeBtn){
            this.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_closeBtn, this);
        }
    }

    private onLoad() {
        const startDpmOut = Buried.connectDpm(110, 6, 1); // 点击埋点   
        const startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        const exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.showLog(exposure);


        if(this.lottery){
            this.prizeNameLb.text = '领取串码：' + this.lottery.couponCode;
            this.rmbNumLb.text = this.lottery.title;
            console.log('this.prizeNameLb.text=',this.prizeNameLb.text);
        }

        if(this.mdata && this.mdata.score){
            let idata = DataManager.ins.getInformationZhaohangData.data;
            if(idata.ifCanAddJoinTimesByShare){
                this.iknowBtn.visible = false;
                this.shareBtn.visible = true;
                this.shareTips.visible = true;

                const startDpmOut2 = Buried.connectDpm(110, 7, 1); // 点击埋点   
                const startDcmOut2 = Buried.connectDcm(202, 0, 0); // 曝光埋点
                const exposure2 = Buried.createExposure(startDpmOut2, startDcmOut2);
        
                NetManager.ins.showLog(exposure2);

                this.setPrizeResult(1);
            }else{
                this.iknowBtn.visible = true;
                this.shareBtn.visible = false;
                this.shareTips.visible = false;

                const startDpmOut3 = Buried.connectDpm(110, 12, 1); // 点击埋点   
                const startDcmOut3 = Buried.connectDcm(202, 0, 0); // 曝光埋点
                const exposure3 = Buried.createExposure(startDpmOut3, startDcmOut3);

                NetManager.ins.showLog(exposure3);
            }
        }


        // if(this.mdata && this.lottery){
        //     var url: string;

        //     url = this.lottery.img;
        //     this.prizeImg.name = 'img'

        //     this.prizeNameLb.text = this.lottery.name;//511 239
        //     this.prizeImg.source = url;
            
        //     switch(this.lottery.type){
        //         case LotteryType.VIRTUAL:
        //         case LotteryType.OBJECT:
        //         case LotteryType.ALIPAY:
        //         case LotteryType.PHONEBILL:
        //         case LotteryType.QB:
        //             this.prizeImg.x = 255;
        //             this.prizeImg.y = 479;

        //             this.prizeImg.width = 239;
        //             this.prizeImg.height = 239;
        //         break;

        //         case LotteryType.THANKS:
                    
        //         break;

        //         default:

        //             this.prizeImg.x = 117;
        //             this.prizeImg.y = 479;

        //             this.prizeImg.width = 515;
        //             this.prizeImg.height = 239;
        //         break;
        //     }
        // }
    }

    // private onTap(): void {
    //     this.hidePanel();
    // }


    onUse() {
        // if(this.mdata){
        //     const lottery = this.lottery;
        //     // if (lottery.type == LotteryType.COUPON || lottery.type == LotteryType.LUCKY) {
        //     if (lottery.type == LotteryType.LUCKY) {

        //         window["downloadAppConfig"] =
        //             {
        //                 openUrl: lottery.openUrl,
        //                 iosDownloadUrl: lottery.iosDownloadUrl,
        //                 androidDownloadUrl: lottery.androidDownloadUrl,
        //                 confirm: lottery.confirm ? lottery.confirm : false
        //             };
        //         window["downloadApp"]();
        //         if (lottery.type == "lucky") {
        //             if(this.isplug){
        //                 NetManager.ins.spmclick(DataManager.ins.getPlugOrderStatusData.exposure);
        //             }else{
        //                 NetManager.ins.spmclick(DataManager.ins.getCustomOrderStatusData.exposure);
        //             }
        //         }
        //     }
        //     else {
        //         console.log(`领奖链接：${lottery.link}`)
        //         window.location.href = lottery.link;
        //     }
        // }else{
        //     // this.onTouchTap();
        // }
    }

    onTouchTap(): any {
        super.onTouchTap();
        if (this['closeBtn']) {
            PanelCtrl.instance.btnDelay(this['closeBtn']);
        }

        // if(this.mdata && this.mdata.callBack){
        //     this.mdata.callBack();
        // }

        // const times = DataManager.ins.ajaxElementDataNew.element.freeLimit - 1;
        // DataManager.ins.ajaxElementDataNew.element.freeLimit = times;

        // SceneCtrl.instance.change(ModuleTypes.START_SCENE);
    }

    private onTap_ok(e:egret.TouchEvent):void{//立即领取

        PanelCtrl.instance.btnDelay(this.iknowBtn);
        // this.onUse();
        const startDpmOut = Buried.connectDpm(110, 12, 1); // 点击埋点   
        const startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        const exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);

        // window.location.href = window['prizeUrl'] ? window['prizeUrl'] : 'http://www.baidu.com';
        // this.onTouchTap();
        window.location.href = this.gotoRecord();

        this.goStart();
    }

    //获取我的奖品
    private gotoRecord():string{
        let recordUrl: string;
        let oaId: number;
        if (DataManager.ins.customCfgData) {
            oaId = DataManager.ins.customCfgData.oaId;
            recordUrl = DataManager.ins.customCfgData.recordUrl;
        } else {
            oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
            recordUrl = window['recordUrl'];
        }

        if(recordUrl.indexOf('?') != -1){
            recordUrl += '&origins=' + oaId + '00';
        }else{
            recordUrl += '?origins=' + oaId + '00';
        } 
        // recordUrl += ',' + (window['plugId'] ? window['plugId'] : 4500) + '01';

        // for(let i = 0; i < window['plugIdArr'].length; i++){
        //     recordUrl += ',' + window['plugIdArr'][i] + '01';
        // }

        return recordUrl;
    }

    private onTap_closeBtn():void{
        this.goStart();
    }

    private onTap_copyBtn():void{
        PanelCtrl.instance.btnDelay(this.copyBtn);

        if(this.lottery){
            this.copyUrl(this.lottery.couponCode);
        }


        const startDpmOut = Buried.connectDpm(110, 6, 1); // 点击埋点   
        const startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        const exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);
    }

    private onTap_shareBtn():void{
        PanelCtrl.instance.btnDelay(this.shareBtn);

        const startDpmOut = Buried.connectDpm(110, 7, 1); // 点击埋点   
        const startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        const exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);

        var param = {
			"shareTitle" : window['shareTitle'] ? window['shareTitle'] : '下载苏州银行APP 百万豪礼免费拿',// 标题
			"shareTextUrl" : window['shareTextUrl'] ? window['shareTextUrl'] : 'https://www.baidu.com',//window.basePath + '/page/conductBuy/cBuyMain.html',// 链接
			"shareText" : window['shareText'] ? window['shareText'] : '下载苏州银行APP 百万豪礼免费拿'// 分享文本内容
        };
        if(window['ThirdApp']){
            window['ThirdApp'].webviewShare(param);
        }

        this.hidePanel();

        Loading.instace.show();
        NetManager.ins.shareZhaohang((success) => {
            if(success && DataManager.ins.getShareZhaohangData.code == '0000000000'){
                setTimeout(() => {    
                    PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, {type: 0});

                    Loading.instace.hide();
                }, 5000);
            }else{
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'分享失败了！'});
                Loading.instace.hide();
            }
        }, DataManager.ins.getInformationZhaohangData.data.scenes[0].scene, DataManager.ins.customCfgData.actId, 1);
    }

    private goStart():void{
        this.onTouchTap();
        
        NetManager.ins.ajaxElementNew(function(success){
            console.log(DataManager.ins.ajaxElementDataNew);
            if(success && DataManager.ins.ajaxElementDataNew.code == '0000000000'){
                NetManager.ins.informationZhaohang((success) => {
                    if(success){    
                        SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                    }else{
                        if(DataManager.ins.getInformationZhaohangData.code == 'E1002060003'){
                            SceneCtrl.instance.change(ModuleTypes.START_SCENE, true);
                        }else{
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'获取场次信息失败，请刷新重试'});
                        }
                    }
                }, DataManager.ins.customCfgData.actId);
            }else{

                if(DataManager.ins.ajaxElementDataNew.code == 'E100201001' || DataManager.ins.ajaxElementDataNew.code == 'E100201002'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'您还未登录，请登录重试'});
                }else{
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'请刷新重试'});
                }
                Loading.instace.hide();

                // console.log('errorCode:' + DataManager.ins.doJoinData.code);
                // PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'请刷新重试', line: 1});
                // PanelCtrl.instance.show(ModuleTypes.WARNING_PANEL, {idx:1});
                // Loading.instace.hide();
            }
        }.bind(this));

    }


    private copyUrl(str:string):void {
        var oInput = document.createElement('input');
        oInput.value = str;
        document.body.appendChild(oInput);
        oInput.select();
        document.execCommand("Copy");
        oInput.style.display = 'none';
        PanelCtrl.instance.showTips(ModuleTypes.TOAST_PANEL, {msg:'已复制'});
    }

    //记录中奖结果
    //出奖结果：1：已中奖 0：未中奖
    private setPrizeResult(type:number):void{
        NetManager.ins.updateRecentJoinResult((success) => {
            if(success && DataManager.ins.getUpdateRecentJoinResultData.code == '0000000000'){
                console.log('中奖结果记录成功');
            }else{
                console.log('中奖结果记录失败');
            }
        }, DataManager.ins.getInformationZhaohangData.data.scenes[0].scene, DataManager.ins.customCfgData.actId, type);
    }

}