import { DataManager } from './../../libs/tw/manager/DataManager';
import { ModuleTypes } from './../types/sceneTypes';

import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import { NetManager } from '../../libs/tw/manager/NetManager';
import Loading from '../loading/Loading';
import { Buried } from '../../libs/tw/util/Buried';
import { VideoEntity } from '../../libs/SVGA';
import SceneCtrl from '../ctrls/sceneCtrl';
import { NetName } from '../../libs/tw/enum/NetName';
import { playSound } from '../ctrls/soundCtrl';
import TopLayerCtrl from '../ctrls/topLayerCtrl';
export default class StartScene1 extends Scene {
    public ruleBtn:eui.Button;
    public soundBtn:eui.Group;
    public headImg:eui.Image;

    public myFoodLb:eui.Label;
    public actGroup:eui.Group;

    private uInfoData:any;

    public startBtn:eui.Button;
    public shareBtn:eui.Button;
    public prizeBtn:eui.Button;
    public rankBtn:eui.Button;
    public gameTime:eui.Label;
    private rankBtn1:SVGA.EgretMovieClip;
    private startBg:SVGA.EgretMovieClip;

    // 用于控制全局音乐是否播放和音乐按钮状态
    public static isPlayMusic: boolean = true;

    public get skinKey() { return 'StartScene' }
    public get groupName() { return 'start_scene' }

    constructor(data?) {
        super(data);

    }
    showAct():void{
        // this.alpha = 0;
        // egret.Tween.get(this).to({alpha:1}, 800);
    }

    initEvents() {
        super.initEvents();

        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        this.soundBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
        this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
    }

    removeEvents() {
        super.removeEvents();

        this.soundBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
        this.prizeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        if(this.rankBtn){
            this.rankBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_rankBtn, this);
        }

    }

    start(data?) {
        super.start(data);
        this.percentHeight = 100;
    }

    private bgtexture: egret.Texture;
    protected async preLoadRes() {
        //加载背景并设置背景图片
        // this.bgtexture = await RES.getResAsync('startBg_jpg');
        await RES.loadGroup('common');
        // this.startBg = await PanelCtrl.instance.getSvga('resource/assets/svga/start/startBgSvg.svga') as SVGA.EgretMovieClip;
        // this.rankBtn1 = await PanelCtrl.instance.getSvga('resource/assets/svga/start/rankBtnSvg.svga') as SVGA.EgretMovieClip;

        return new Promise(function (resolve, reject) {
            resolve();
        });
    }

    protected onSkinComplete(): void {
        super.onSkinComplete();
        
        // this.mainbg.texture = this.bgtexture;

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

    private onLoad(): void {
        let startDpmOut = Buried.connectDpm(110, 2, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);
    
        NetManager.ins.showLog(exposure);

        this.initUI();
    }

    private initUI(): void {
        let startDpmOut = Buried.connectDpm(110, 1, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);
    
        NetManager.ins.showLog(exposure);

        window['isOpenMusic'] = true;
        this['mImg0'].visible = true;
        this['mImg1'].visible = false;

        this.uInfoData = DataManager.ins.getData(NetName.GET_PROJECT_USER_INFO);
        if(this.uInfoData && this.uInfoData.data){
            this.uInfoData = this.uInfoData.data;
        }

        let data = DataManager.ins.getData(NetName.BASE_INFO);
        if(data && data.data){
            let freeNum = data.data.freeTimes;
            if(freeNum > 0){
                this.gameTime.text = '免费次数:' + freeNum + '次';
            }else{
                this.gameTime.text = '今日可参与次数:'+data.data.participationTimes+'次'
            }
            let data2 = DataManager.ins.getData(NetName.BASE_INFO);
            if(data2 && data2.data){
                let creditNum = data2.data.gameCredits;
                    
                this.startBtn['priceLb'].text = creditNum + this.uInfoData.unitName + '/次';
            }

            if(data.data.rankingStatus == 0){
                TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动已结束，无法继续参与游戏哦~'});
            }
        }

        this.myFoodLb.text = '我的' + this.uInfoData.unitName + ':' + this.uInfoData.credits;
        this.initData();
        this.initSvga();

    }

    private onTap_prizeBtn():void{
        PanelCtrl.instance.btnDelay(this.prizeBtn)
        window.location.href = window['prizeUel'] ? window['prizeUel'] : 'http://activity.m.duibatest.com.cn/projectx/p1c121900/f67a6eae9.html';
    }

    private initData(isPlay:boolean = false):void{
        this.actGroup.visible = true;
    }

    private initSvga():void{
        egret.Tween.get(this.startBtn, {loop:true}).to({scaleX:0.82, scaleY:1.12}, 200)
        .to({scaleX:1.02, scaleY:0.96}, 100)
        .to({scaleX:0.9, scaleY:1.04}, 200)
        .to({scaleX:1.02, scaleY:0.96}, 100)
        .to({scaleX:1, scaleY:1}, 200).wait(1200)

        // this.addChild(this.rankBtn1);
        // this.rankBtn1.y = 332;
        // this.startBg.x = 100;
        // this.startBg.y = 225;
        // this.actGroup.addChild(this.startBg);

        this.rankBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_rankBtn, this);

        // this.rankBtn1.touchEnabled = true;

    }

    private onTap_rankBtn():void{
        PanelCtrl.instance.btnDelay(this.rankBtn);
        console.log('点击了排行榜！')
        NetManager.ins.RankingTypeInfo((success)=>{
            let rtData = DataManager.ins.getData(NetName.RANKING_TYPE_INFO);
            let type;
            if(rtData && rtData.data){
                type = rtData.data.curType;
            }
            if(success){
                NetManager.ins.getRanking((success1)=>{
                    if(success1){
                        NetManager.ins.prizelist((success2)=>{
                            if(success2){
                                PanelCtrl.instance.show(ModuleTypes.RANK_PANEL);
                            }else{//获取本期奖品列表失败

                            }
                        })
                    }else{//获取排行榜信息失败

                    }
                }, type, 100, '1');
            }else{

            }
        });
    }
    private onTap_startBtn():void{
        PanelCtrl.instance.btnDelay(this.rankBtn);
        let startDpmOut = Buried.connectDpm(110, 1, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);
    
        NetManager.ins.clickLog(exposure);

        let data = DataManager.ins.getData(NetName.BASE_INFO);
        if(data && data.data){
            if(data.data.rankingStatus == 0){
                TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动已结束，无法继续参与游戏哦~'});
                return;
            }
        }
        this.touchEnabled = false;
        this.touchChildren = false;
        NetManager.ins.freeStart((success)=>{
            if(success){
                //每局所需积分数
                let data1 = DataManager.ins.getData(NetName.BASE_INFO);
                let gameCredits;
                if(data1 && data1.data){
                    gameCredits = data1.data.gameCredits;
                }

                let data = DataManager.ins.getData(NetName.FREE_START);
                if(data && data.data){
                    let free = data.data.free;
                    if(free){//有次数
                        SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                    }else{//无次数
                        NetManager.ins.creditsCost((success2)=>{
                            if(success2){
                                let cdata = DataManager.ins.getData(NetName.CREDITS_COST);
                                if(cdata){
                                    this.times = 5;
                                    this.loopNet(cdata.data);
                                }else{
                                    //为什么会没数据！！！！！！
                                    this.touchEnabled = true;
                                    this.touchChildren = true;
                                }
                            }else{
                                //扣积分接口失败
                                this.touchEnabled = true;
                                this.touchChildren = true;
                                TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'网络异常，请稍后再试~'});
                            }
                        }, gameCredits);
                    }
                }
            }else{

                this.touchEnabled = true;
                this.touchChildren = true;
                //免费次数参与游戏失败
                let data = DataManager.ins.getData(NetName.FREE_START);
                if(data){
                    if(data.code == '100000'){
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'今日参与次数已达上限,请明日再来~'});
                    }else if(data.code == '100010'){
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:this.uInfoData.unitName + '不足~'});
                    }else if(data.code == "100021"){
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'喵喵累了，先休息一会儿吧~'});
                    }else if(data.code == "100020"){
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'喵喵出去玩耍了，等下再来哦~'});
                    }else{
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'网络异常，请稍后再试~'});
                    }
                }
            }
        });

    }

    private times:number;
    private loopNet(ticketNum:string):void{
        if(this.times < 1){
            //轮询失败
            
            TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'网络异常，请稍后再试~'});
            return;
        }
        //获取券码券详情
        NetManager.ins.queryStatus((success)=>{
            this.times --;
            if(success){
                let data = DataManager.ins.getData(NetName.QUERY_STATUS).data;
                if(data != 1){
                    setTimeout(() => {
                        this.loopNet(ticketNum);
                    }, 500);
                }else{
                    let cdata = DataManager.ins.getData(NetName.CREDITS_COST);
                    //扣积分成功,消耗积分开始游戏
                    NetManager.ins.creditsStart((successStart)=>{
                        if(successStart){
                            SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                        }else{
                            //creditsStart开始游戏失败
                            TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'网络异常，请稍后再试~'});
                        }
                    }, ticketNum);
                }
            }else{
                setTimeout(() => {
                    this.loopNet(ticketNum);
                }, 500);
            }
        }, ticketNum);
    }

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

        let startDpmOut = Buried.connectDpm(110, 2, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);
    
        NetManager.ins.clickLog(exposure);
        if(window['SNNativeClient']){
            window['SNNativeClient'].callNativeShareUrl({
                shareTypeList:["WXChat","WXFriends"],
                shareTitle:window['shareTitle'] ? window['shareTitle'] : "数钱赢壕礼！越数约happy~",
                shareContent:window['shareCont'] ? window['shareCont'] : "上苏宁金融和我一起猫咪数钱，缤纷好礼免费送！",
                shareUrl:window['shareUrl'] ? window['shareUrl'] : 'http://activity.m.duiba.com.cn/customShare/share?id=3802',
                imageUrl:'https://duiba.oss-cn-hangzhou.aliyuncs.com/db_games/activity/shareImg/20200228/shareImg.png',
                // cbFunc:this.onCallBack.bind(this)
            })
            setTimeout(() => {
                this.onCallBack();
            }, 2000);
        }

    }

    private onCallBack():void{

        NetManager.ins.share((success)=>{
            if(success){
                console.log('分享加次数成功！');
                NetManager.ins.baseInfo(()=>{
                    let data = DataManager.ins.getData(NetName.BASE_INFO);
                    if(data && data.data){
                        let freeNum = data.data.freeTimes;
                        console.log(DataManager.ins.getData(NetName.BASE_INFO))
                        if(freeNum > 0){
                            this.startBtn['priceLb'].text = '免费次数:' + freeNum;
                        }
                    }else{
                        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'次数刷新失败，请刷新界面~'});
                    }
                })
            }else{
                let sdata = DataManager.ins.getData(NetName.SHARE);
                if(sdata.code == '100033'){

                }else{
                    TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'分享加次数失败！'});
                }
            }
        })
    }

    private onTap_ruleBtn(): void {

        console.log('点击rule');
        PanelCtrl.instance.btnDelay(this.ruleBtn);
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    private onTap_soundBtn(){
        if(window['isOpenMusic'] == undefined || window['isOpenMusic'] == null || window['isOpenMusic'] == false){
            window['isOpenMusic'] = true;
            this['mImg0'].visible = true;
            this['mImg1'].visible = false;
        }else{
            window['isOpenMusic'] = false;
            this['mImg0'].visible = false;
            this['mImg1'].visible = true;
        }

    }

    private getIsWxClient ():boolean {
        var ua:string = window['navigator'].userAgent.toLowerCase();
        console.log(ua);
        if (ua.indexOf("micromessenger") != -1) {
            return true;
        }
        return false;
    };

}
