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

import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import SceneCtrl from '../ctrls/sceneCtrl';
import { NetManager } from '../../libs/tw/manager/NetManager';
import { NetName } from '../../libs/tw/enum/NetName';
import TopLayerCtrl from '../ctrls/topLayerCtrl';
import StartScene1 from '../startScene/StartScene';
import { stopAllSound } from '../ctrls/soundCtrl';
import { Buried } from '../../libs/tw/util/Buried';
export default class Scene6 extends Scene {
    public textBg:eui.Image;
    public mainGroup:eui.Group;
    public soundBtn:eui.Button;

    private s6btn:SVGA.EgretMovieClip;

    private tTxtTimes:any[];

    public get skinKey() { return 'Scene6' }
    public get groupName() { return 'scene6' }

    constructor(data?) {
        super(data);

    }

    initEvents() {
        super.initEvents();
        this.s6btn.touchEnabled = true;
        this.s6btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ontap_s6btn, this);
        this.addEventListener(egret.TouchEvent.TOUCH_END, this.onTap_this, this);
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_this, this);
        this.soundBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
    }

    removeEvents() {
        super.removeEvents();
        this.s6btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.ontap_s6btn, this);

        this.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTap_this, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_this, this);
        this.soundBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
    }

    private bLocalX:number = 0;
    private onTap_this(e:egret.TouchEvent):void{
        console.log('e.localX',e.localX);
        console.log('value', e.localX - this.bLocalX);
        let val = e.localX - this.bLocalX;
        if(Math.abs(val) > window['space']){
            if(val < 0){//向左
                // SceneCtrl.instance.change(ModuleTypes.SCENE5);

            }else{//向右
                // SceneCtrl.instance.change(ModuleTypes.SCENE5);
            }
        }
    }

    private onBegin_this(e:egret.TouchEvent):void{
        console.log('e.localX',e.localX);
        this.bLocalX = e.localX;

    }

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

    private bgtexture: egret.Texture;
    protected async preLoadRes() {
        //加载背景并设置背景图片
        // this.bgtexture = await RES.getResAsync('startBg_jpg');
        //螃蟹端内
        this.s6btn = await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn00.svga') as SVGA.EgretMovieClip;

        let data = DataManager.ins.getData(NetName.GET_INFO).data;
        if(data.actPayload == 1){//显示红包按钮
            if(window['isapp']){//分享获取小食
                this.s6btn = await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn01.svga') as SVGA.EgretMovieClip;
                
                let startDpmOut = Buried.connectDpm(110, 9, 1); // 点击埋点   
                let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let exposure = Buried.createExposure(startDpmOut, startDcmOut);
        
                NetManager.ins.showLog(exposure);
            }else{//点击抽取
                this.s6btn = await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn11.svga') as SVGA.EgretMovieClip;

                let startDpmOut = Buried.connectDpm(110, 18, 1); // 点击埋点   
                let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let exposure = Buried.createExposure(startDpmOut, startDcmOut);
        
                NetManager.ins.showLog(exposure);
            }
        }else{//显示螃蟹
            if(window['isapp']){//分享获取小食
                let startDpmOut = Buried.connectDpm(110, 9, 1); // 点击埋点   
                let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let exposure = Buried.createExposure(startDpmOut, startDcmOut);
        
                NetManager.ins.showLog(exposure);
                this.s6btn = await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn00.svga') as SVGA.EgretMovieClip;
            }else{//点击抽取
                let startDpmOut = Buried.connectDpm(110, 18, 1); // 点击埋点   
                let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let exposure = Buried.createExposure(startDpmOut, startDcmOut);
        
                NetManager.ins.showLog(exposure);
                this.s6btn = await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6btn10.svga') as SVGA.EgretMovieClip;
            }
        }

        for(let i = 0; i < 3; i++){
            this['s6mv' + i] = await PanelCtrl.instance.getSvga('resource/assets/svga/scene6/s6mv' + i + '.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 {
        this.initSoundBtn();

        this.initData();
        this.initUI();
    }

    private initData():void{
        this.tTxtTimes = [
            {s:3, e:4.5, h:201},
            {s:5, e:6.5, h:203},
            {s:7, e:8.5, h:204},
            {s:9, e:10.5, h:203}
        ]
    }

    private initUI(): void {
        this.initAct();
        this.initSvga();

    }

    private initAct():void{
        this.textBg.alpha = 0;
        //文字背景动效
        egret.Tween.get(this.textBg).wait(2000).to({alpha:1}, 500);

        for(let i = 0; i < 4; i++){
            this.setTxtAct(this.tTxtTimes[i].s, this.tTxtTimes[i].e, this.tTxtTimes[i].h, this['text' + i]);
        }
        
        let len = this.tTxtTimes.length;
        // setTimeout(() => {
            console.log('显示分享按钮');
            this.mainGroup.addChild(this.s6btn);
            this.s6btn.startAniRange(1, 27, 1, ()=>{
                this.s6btn.startAniRange(28, this.s6btn.totalFrames, -1);
            });
        // }, this.tTxtTimes[len - 1].e * 1000 + 1000);
    }

    private setTxtAct(stime:number, etime:number, h:number, target:eui.Component):void{
        let shap = new egret.Shape();
        shap.graphics.beginFill(0);
        shap.graphics.drawRect(0, 0, 37, h);
        shap.x = target.x;
        shap.y = target.y - h;
        this.mainGroup.addChild(shap);

        target.mask  = shap;

        setTimeout(() => {
            egret.Tween.get(shap).to({y:target.y}, (etime - stime) * 1000);
        }, stime * 1000);
    }

    private initSvga():void{

        for(let i = 0; i < 3; i++){
            this.mainGroup.addChild(this['s6mv' + i]);
        }

        this.mainGroup.addChild(this.soundBtn);

    }

    private ontap_s6btn():void{

        PanelCtrl.instance.btnDelay(this.s6btn);

        if(window['isapp']){//端内
            let startDpmOut = Buried.connectDpm(110, 9, 1); // 点击埋点   
            let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
            let exposure = Buried.createExposure(startDpmOut, startDcmOut);
    
            NetManager.ins.clickLog(exposure);
        }else{
            let startDpmOut = Buried.connectDpm(110, 18, 1); // 点击埋点   
            let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
            let exposure = Buried.createExposure(startDpmOut, startDcmOut);
    
            NetManager.ins.clickLog(exposure);
        }

        if(!window['isapp']){//分享获取小食
            window.location.href = window['dplink'] ? window['dplink'] :'https://www.baidu.com';
            return;
        }
        //测试代码
        // NetManager.ins.shareData((success)=>{
        //     if(success){//加次数成功
        //         PanelCtrl.instance.show(ModuleTypes.SHARE_SUC_PANEL);
        //     }else{
        //         //加次数失败
        //         TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动太火爆了，请稍后重试~'});
        //     }
        // });
        // return;
        this.share();
    }
    private share():void{
        //进入分享流程
        var param = {
			"shareTitle" : window['shareTitle'] ? window['shareTitle'] : '听吴侬软语，寻姑苏美食',// 标题
			"shareTextUrl" : window['shareTextUrl'] ? window['shareTextUrl'] : 'https://activity-1.m.duiba.com.cn/hdtool/index?id=3721052&appKey=U9smCw8qARxWTzoSvL41McNWiRu&openBs=openbs',// 链接
			"shareText" : window['shareText'] ? window['shareText'] : '开启美味追忆之旅，还有大闸蟹、现金红包等小食礼品你来拿哦！',// 分享文本内容
			"sequence":'110',//分享三个按钮的显示与隐藏
			"showDialog":'true', //是否需要底部弹出层
			"shareAlertTitle":'分享', //分享弹出层标题
			"callback":"shareCallBack" //分享回调方法
        };
        
        window['shareCallBack'] = (data)=>{
            let data1 = DataManager.ins.getData(NetName.GET_INFO).data;
            let endtime = new Date(window['endtime'] ? window['endtime'] : '2019-11-16 00:00:00').getTime();
            console.log('分享返回参数data:', data);
            PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, 3);//写死的活动结束
            // if(data1.timestamp > endtime){
            //     //提示活动已结束
            //     PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, 3);
            // }else{
            //     let issuccess:boolean;

            //     var u = navigator.userAgent;//, app = navigator.appVersion;
            //     var android = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            //     var iphone = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

            //     if(android){
            //         if(data == '0'){
            //             issuccess = true;
            //         }else{
            //             issuccess = false;
            //         }
            //     }

            //     if(iphone){

            //         if(data == '1'){
            //             issuccess = true;
            //         }else{
            //             issuccess = false;
            //         }
            //     }

            //     if(issuccess){
            //         //alert("分享成功");
            //         console.log("分享成功");
            //         NetManager.ins.shareData((success)=>{
            //             if(success){//加次数成功
            //                 PanelCtrl.instance.show(ModuleTypes.SHARE_SUC_PANEL);
            //             }else{
            //                 //加次数失败
            //                 TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动太火爆了，请稍后重试~'});
            //             }
            //         });
            //     }else{
            //         //alert("分享失败");
            //         console.log("分享失败");
    
            //         PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, 0);
    
            //         // TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'分享失败！'});
            //     }
            // }
            
        }
        window['ThirdApp'].webviewShare(param);
    }

    private initSoundBtn(){
        if(!StartScene1.isPlayMusic){
            this.soundBtn.currentState = 'disabled';
            window['musicPlay'](false);
            stopAllSound();
        }else{
            this.soundBtn.currentState = 'up';
            window['musicPlay'](true);
        }
        // toggleSound()
    }
    
    private onTap_soundBtn(){
        PanelCtrl.instance.btnDelay(this.soundBtn);

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

        NetManager.ins.clickLog(exposure);

        if(StartScene1.isPlayMusic){
            StartScene1.isPlayMusic = false;
            this.soundBtn.currentState = 'disabled';
            window['musicPlay'](false);
            stopAllSound();
        }else{
            StartScene1.isPlayMusic = true;
            this.soundBtn.currentState = 'up';
            window['musicPlay'](true);
        }
        // toggleSound()
    }

}
