import { Data } from './../../libs/tw/data/Data';
import { NetManager } from './../../libs/tw/manager/NetManager';
import { GDispatcher } from './../../libs/tc/util/GDispatcher';
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 PanelCtrl from "../ctrls/panelCtrl";
import Loading from "../loading/Loading";
import { Buried } from '../../libs/tw/util/Buried';
import PrizeItem from './PrizeItem';
import { GFun } from '../../libs/tc/util/GFun';
import { NetName } from '../../libs/tw/enum/NetName';
import { GetBuriedData } from '../ctrls/GetBuriedData';


export default class PrizePanel extends Panel {
    private mdata: any;
    public prizeGroup:eui.Group;

    public hintLab:eui.Label;
    public prizeList:eui.List;
    public prizeScroller:eui.Scroller;

    public prizeBackBtn:eui.Button;
    public prizeBg:eui.Image;
    private prizeBgTexture:egret.Texture;

    public prizeBoxBg:eui.Image;
    private prizeTexture:egret.Texture;

    public npcBtn:eui.Button;
    public get skinKey() { return 'PrizePanel' }
    public get groupName() { return 'prize_panel' }
 
    constructor(data: any) {
        super(data);
        this.mdata = data;
    }
    protected async preLoadRes() {
        this.prizeTexture = await RES.getResAsync('prizeBoxBg_jpg');
        this.prizeBgTexture = await RES.getResAsync('prizeBg_jpg');
        return new Promise(function (resolve, reject) {
            resolve();
        });
    }
    onSkinComplete(): void {
        super.onSkinComplete();
        this.prizeBoxBg.texture = this.prizeTexture;
        this.prizeBg.texture = this.prizeBgTexture;
        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.prizeBackBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClickBack,this);
        GDispatcher.addEvent("onClickPrize", this.onClickPrize, this);
        this.npcBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClickNpc,this);
    }

    removeEvents(): void {
        super.removeEvents();
        this.prizeBackBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClickBack,this);
        GDispatcher.removeEvent("onClickPrize", this.onClickPrize, this);
        this.npcBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClickNpc,this);
    }

    private onLoad() {
        // if(GFun.getQueryString('prize')){
        //     this.delParam('prize');
        // }
        // console.log('屏幕',screen.width,screen.height)
        // if(screen.height/screen.width >= 2.22)
        // {
        //     this.prizeGroup.y = 140;
        // }
        NetManager.ins.getRecords((success,result)=>{ 
            if(!success){
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:result.message})
                return;
            }
            if(success && result.data){
                this.getOrderStatus(result.data);
            }
        })
        NetManager.ins.showLog(GetBuriedData(10));
    }

    private delParam(paramKey) {
        var url = window.location.href;    //页面url
        var urlParam = window.location.search.substr(1);   //页面参数
        var beforeUrl = url.substr(0, url.indexOf("?"));   //页面主地址（参数之前地址）
        var nextUrl = "";

        var arr = new Array();
        if (urlParam != "") {
            var urlParamArr = urlParam.split("&"); //将参数按照&符分成数组
            for (var i = 0; i < urlParamArr.length; i++) {
                var paramArr = urlParamArr[i].split("="); //将参数键，值拆开
                //如果键与要删除的不一致，则加入到参数中
                if (paramArr[0] != paramKey) {
                    arr.push(urlParamArr[i]);
                }
            }
        }
        if (arr.length > 0) {
            nextUrl = "?" + arr.join("&");
        }
        url = beforeUrl + nextUrl;
        if(url){
            window.history.pushState({}, '', url);
        }
        console.log('url',url);
        //return url;
    }
    private getOrderStatus(prizeData){
        let prizeIdArray = new Array();
        prizeData.forEach(element => {
            if(element.extra.type != 1){
                prizeIdArray.push(element.id);
            }
        });
        if(prizeIdArray.length > 0){
            let prizeIdString = prizeIdArray.join(',');
            NetManager.ins.getOppoOrderStatus((success,result)=>{ 
                if(!success){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:result.desc})
                    return;
                }
                if(success && result.data){
                    this.handlePrizeData();
                }
            },prizeIdString)
        }else{
            this.hintLab.visible = true;
        }
    }
    private handlePrizeData(){
        let tmpPrizeData = DataManager.ins.getData(NetName.OPPO_GETRECORDS).data;
        let tmpOrderStatus = DataManager.ins.getData(NetName.OPPO_GETPRIZE).data;
        for (let index = 0; index < tmpPrizeData.length; index++) {
            let prizeDataJudge = tmpPrizeData[index];
            for (let index = 0; index < tmpOrderStatus.length; index++) {
                let orderStatus = tmpOrderStatus[index];
                if(prizeDataJudge.id == orderStatus.projectOrderNo){
                    orderStatus.name = prizeDataJudge.extra.name;
                    orderStatus.refType = prizeDataJudge.extra.refType;
                    orderStatus.icon = prizeDataJudge.extra.icon;
                } 
            }
        }
        this.setPrize(tmpOrderStatus);
    }
    private onClickPrize(prizeData){
        console.log('选择奖品',prizeData);
        NetManager.ins.clickLog(GetBuriedData(12));
        if(prizeData.refType == 'virtual'){

            if(prizeData.hasMainOrder){
                if(prizeData.status == 'success'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'红包已经发放至你的微信账户啦，\n注意查收~'})
                }else{
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'因微信账号异常，\n受到微信官方发放限制，\n请联系客服补发红包~'})
                }
            }else{
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'因微信账号异常，\n受到微信官方发放限制，\n请联系客服补发红包~'})
            }
            return;
        }
        if(prizeData.refType == 'alipay')
        {
            if(prizeData.hasMainOrder){
                if(prizeData.status == 'consume_success'){
                    NetManager.ins.canRetry((success,result)=>{ 
                        if(result.data){
                            window.location.href = window['getPrizeUrl'] + prizeData.projectOrderNo + '&orderId='+prizeData.orderId + '&retry=1';
                        }else{
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'红包将于24小时内到账，\n请稍后前来查看～'})
                        }
                    },prizeData.orderId)
                }else if(prizeData.status == 'success' ){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'红包已经发放至你的支付宝账户啦，\n注意查收~'})
                }else{
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'请至活动规则中，联系客服处理～'})
                }
            }
        }
        if(GFun.getIsWxClient() && prizeData.refType == 'alipay' && !prizeData.hasMainOrder){
            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'请到OPPO+领取支付宝红包哦~'})
            return;
        }
         //   /oppocommunity/i.test(navigator.userAgent) &&
        if( prizeData.refType == 'alipay' && !prizeData.hasMainOrder){
            window.location.href = window['getPrizeUrl'] + prizeData.projectOrderNo;
        }
    }
    private setPrize(prizeData):void{
        console.log('奖品',prizeData);
        if(prizeData.length > 0){
            this.hintLab.visible = false;
            NetManager.ins.showLog(GetBuriedData(12));
        }else{
            this.hintLab.visible = true;
        }
        let arrData = null;
        this.prizeList.itemRenderer = PrizeItem;
        arrData = new eui.ArrayCollection(prizeData);
        this.prizeList.dataProvider = arrData;
    }

    private onClickBack(e:egret.TouchEvent):void{
        PanelCtrl.instance.btnDelay(this.prizeBackBtn);
        NetManager.ins.clickLog(GetBuriedData(10));
        this.hidePanel();
        //SceneCtrl.instance.change(ModuleTypes.START_SCENE);
    }
    private onClickNpc(){
        PanelCtrl.instance.btnDelay(this.npcBtn);
        window.location.href = '/faq/index?dbnewopen';
    }
}