import { GameUtils } from "../utils/GameUtils";
import {ServerHttps} from "../WXSDK/ServerHttps";
import {WECHATEVENT} from "../WXSDK/WECHATEVENT";
import { Global } from "../Global";
import {DateControl} from "../Control/DateControl";
import {LocalDataControl} from "../Control/LocalDataControl";
import {UserDataInfo} from "../Data/UserDataInfo";
import { GlobalTip } from "../utils/GlobalTip";
import { DispatcherManager } from "../utils/DispatcherManager";
import {AudioControl} from "../Control/AudioControl";
import { LayoutControl } from "../Control/LayoutControl";
import {pingtaiutils} from "../WXSDK/pingtaiutils";

/*
* name;
*/
export  class WXGamePlatform
{
    private static ins:WXGamePlatform;

    static code:string;
    static nickName:string;
    static QuDaoID:string = "";//微信广告ID

    static isShowing:boolean=true;
    /**
     * 授权状态 0:未判断，1：已授权
     */
    static accreditstate:number = 0;

    /**
     * 当天分享次数
     */
    static dayShareNum:number = 0;
    /**
     * 当天看视频次数
     */
    static dayVideoNum:number = 0;
    /**
     * 判断分享是否成功时间间隔
     */
    static ShareTime:number = 0;
    /**
     * 每日最大看视频次数（成功累加一次）
     */
    static VideoNum:number = 0;
    /**
     * 看视频冷却时间
     */
    static VideoTime:number = 0;

    /**
     * 8好位cpa可弹出时间间隔(秒)
     */
    static jiliweitime:number = 100;
    /**
     * 分享几次切换到视频
     */
    static SharetoVideo:number = 1;

    /**
     * 视频几次切换到分享
     */
    static VideotoShare:number = 1;

    /**
     * 分享数据容器
     */
    static ShareDict:any = {};

    /**
     * 用户来源id
     */
    static fromscene:number = 0;

    constructor(){
        WXGamePlatform.ins = this;

    }

    public static get Instance():WXGamePlatform
    {
        if( WXGamePlatform.ins == null )
        {
            return new WXGamePlatform();
        }
        return WXGamePlatform.ins;
    }

    public init():void
    {
        this.showShareMenu({withShareTicket:true});
        this.onAudioInterruptionBegin();
        this.onAudioInterruptionEnd();
    }

    public initShareDian( data:Array<any> ):void
    {
        if( data && data.length > 0 )
        {
            var itemd:any;
            for( var s in data )
            {
                itemd = data[s];
                WXGamePlatform.ShareDict[itemd.key] = itemd;
            }
            var firstd:any = data[0];
            this.onShareAppMessage(firstd.tile,Global.cdnurl + firstd.img);
        }
    }

    public initData():void
    {
        if( DateControl.Fresh )
        {
            WXGamePlatform.dayShareNum=0;
            WXGamePlatform.dayVideoNum=0;
            this.updateDayShareInfo();
            this.updateDayVideoInfo();
        }
        else
        {
            WXGamePlatform.dayShareNum=LocalDataControl.Instance.getnum(UserDataInfo.nowdayShare);
            WXGamePlatform.dayVideoNum=LocalDataControl.Instance.getnum(UserDataInfo.nowdayVideo);
        }

    }

    /**
     * 存储当天分享的信息
     */
    public updateDayShareInfo():void
    {
        LocalDataControl.Instance.addstr( UserDataInfo.nowdayShare,WXGamePlatform.dayShareNum.toString() );

    }

    public updateDayVideoInfo():void
    {
        LocalDataControl.Instance.addstr( UserDataInfo.nowdayVideo,WXGamePlatform.dayVideoNum.toString() );

    }

    public userinfobutton;
    static loginCallobj:any;
    static loginsucceedcallback:Function;
    static loginprogressCallback:Function;
    public createUserAndLogin( callobj:any,succeedcallback:Function,progressCallback:Function =null, failcallback:Function=null ):void
    {
        WXGamePlatform.loginCallobj = callobj;
        WXGamePlatform.loginsucceedcallback = succeedcallback;
        WXGamePlatform.loginprogressCallback = progressCallback;
        var wx:any = Laya.Browser.window.wx;
        if( wx )
        {
            let login_info:any = WXGamePlatform.Instance.getLaunchOptionsSync();
            if(login_info)
            {

                let query =login_info.query;
                if(query && query.ChanID){
                    WXGamePlatform.QuDaoID = query.ChanID;

                }
                let referrerInfo = login_info.referrerInfo;
                if( WXGamePlatform.QuDaoID == "" && referrerInfo && referrerInfo.appId )
                {
                    WXGamePlatform.QuDaoID = referrerInfo.appId;

                }
                if( login_info.scene )
                {
                    WXGamePlatform.fromscene = Number( login_info.scene );
                }
            }
            let systemres = wx.getSystemInfoSync();
            var version = systemres.SDKVersion;
            if (wx.getUpdateManager) 
            {
                var updateManager = wx.getUpdateManager();
                updateManager.onCheckForUpdate(function (res) {
                    // 请求完新版本信息的回调

                    if( res.hasUpdate==true )
                    {
                        updateManager.onUpdateReady(function () {
                            Laya.Browser.window.wx.showModal({
                                title: '更新提示',
                                content: '新版本已经准备好，是否重启应用？',
                                success: function (res) {
                                    if (res.confirm) {
                                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                        updateManager.applyUpdate()
                                    }else{
                                        WXGamePlatform.Instance.exitGame();
                                    }
                                }
                            })
                        });
                        updateManager.onUpdateFailed(function () {
                            // 新版本下载失败
                            WXGamePlatform.Instance.exitGame();
                        });
                    }
                    else
                    {
                        // if( WXGamePlatform.loginCallobj && WXGamePlatform.loginprogressCallback )
                        // {
                        //     WXGamePlatform.loginprogressCallback.call( WXGamePlatform.loginCallobj,10 );
                        // }
                        var wxplatform:WXGamePlatform = WXGamePlatform.Instance;
                        wxplatform.login(callobj,succeedcallback,failcallback);
                    }
                })
            }
            else
            {
                // if( WXGamePlatform.loginCallobj && WXGamePlatform.loginprogressCallback )
                // {
                //     WXGamePlatform.loginprogressCallback.call( WXGamePlatform.loginCallobj,10 );
                // }
                var wxplatform:WXGamePlatform = WXGamePlatform.Instance;
                wxplatform.login(callobj,succeedcallback,failcallback);
            }
        }
    }

    userinfocallobj:any;
    userinfosuccallback:Function;
    userinfofailcallback:Function;
    public createUserInfoButton(  callobj:any,callback:Function,failcallback:Function):void
    {
        this.userinfocallobj = callobj;
        this.userinfosuccallback = callback;
        this.userinfofailcallback = failcallback;
        var wx = Laya.Browser.window.wx;
        let res = wx.getSystemInfoSync();
        if( res )
        {

            var posx:number = (res.windowWidth-151)/2;
            var posy:number = res.windowHeight-172 - 40;
            WXGamePlatform.Instance.userinfobutton = wx.createUserInfoButton(
            {
                type: 'image',
                image:'wxlocal/login.png',
                style:
                {
                    left: posx,
                    top: posy,
                    width: 151,
                    height: 72
                }
            });
            WXGamePlatform.Instance.userinfobutton.onTap( WXGamePlatform.Instance.userinfoButtonClick );
        }
    }

    /**
     * 判断是否已经授权
     */
    public getaccredit( callobj:any,accreditCallback:Function ):void
    {
        if( WXGamePlatform.accreditstate == 0 )
        {
            var wx = Laya.Browser.window.wx;
            if( wx )
            {   
                wx.getSetting(
                {
                    success (res) 
                    {
                        var itemd = res.authSetting;
                        if( itemd.hasOwnProperty( "scope.userInfo" ) && itemd["scope.userInfo"] == true ) //已经授权过
                        {
                            if(accreditCallback&&callobj)
                            {
                                accreditCallback.call( callobj,true );
                            }
                        }
                        else
                        {
                            if(accreditCallback&&callobj)
                            {
                                accreditCallback.call( callobj,false );
                            }
                        }
                    }
                });
            }
            else
            {
                if(accreditCallback&&callobj)
                {
                    accreditCallback.call( callobj,true );
                }
            }
        }
        else
        {
            if(accreditCallback&&callobj)
            {
                accreditCallback.call( callobj,true );
            }
        }
    }

    public userinfoButtonClick( res:any ):void
    {
        var wxplatform:WXGamePlatform = WXGamePlatform.Instance;

        if( res )
        {
            var errMsg:string = res.errMsg;
            if( errMsg == "getUserInfo:ok" )
            {

                WXGamePlatform.accreditstate = 1;
                wxplatform.closeuserinfobUtton();
                wxplatform.getUserInfo( false,wxplatform.userinfocallobj,wxplatform.userinfosuccallback,wxplatform.userinfofailcallback );
            }
            else
            {

                if( wxplatform.userinfocallobj && wxplatform.userinfofailcallback )
                {
                    wxplatform.userinfofailcallback.call( wxplatform.userinfocallobj );
                }
            }
        }
    }

    public closeuserinfobUtton():void
    {
        var wxplatform:WXGamePlatform = WXGamePlatform.Instance;
        if(wxplatform.userinfobutton)
        {
            wxplatform.userinfobutton.offTap(wxplatform.userinfoButtonClick);
            wxplatform.userinfobutton.destroy();
            wxplatform.userinfobutton=null;
        }
    }

    public getUserInfo( islogin:boolean,callobj:any,callback:Function,failcallback:Function ):void
    {
        fairygui.GRoot.inst.showModalWait();
        var wxplatform:WXGamePlatform = WXGamePlatform.Instance;
        var wx = Laya.Browser.window.wx;
        if( wx )
        {
            wx.getUserInfo(
            {
                success: function(res) 
                {
                    var userInfo = res.userInfo;
                    WXGamePlatform.nickName = userInfo.nickName;
                    if( islogin )
                    {
                        wxplatform.login(callobj,callback,failcallback);
                    }
                    else
                    {
                        if( callobj && callback )
                        {
                            callback.call( callobj,WXGamePlatform.nickName );
                        }
                    }
                }
            })
        }
    }

    /**
     * 登录
     * @param callobj 
     * @param succeedcallback 
     * @param failCallback 
     */
    public login( callobj:any,callback:Function,failcallback:Function ):void
    {
        var wxplatform:WXGamePlatform = WXGamePlatform.Instance;
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.login({
                success: function ( res ) 
                {

                    WXGamePlatform.code = res.code;
                    var itemd:any = {};
                    if( WXGamePlatform.QuDaoID != "" )
                    {
                        itemd.ChanID = WXGamePlatform.QuDaoID;
                    }
                    itemd.Code = WXGamePlatform.code;
                    itemd.AppID = Global.appid;
                    itemd.Version = Global.gameVersion;
                },
                fail:function(res){

                    wxplatform.login( callobj,callback,failcallback );
                }
            })
        }
    }

    private loginSucceedCallback( data:any ):void
    {
        if( WXGamePlatform.loginCallobj && WXGamePlatform.loginsucceedcallback )
        {
            WXGamePlatform.loginsucceedcallback.call( WXGamePlatform.loginCallobj,data );
        }
    }


    public _subcallobj:any;
    public _subcallback:Function;
    public _updatecallback:Function;
    public _subfailcallback:Function;
    public loadSubpackage( name:string,subcallobj:any,subcallback:Function,updatecallback:Function,subfailcallback:Function ):void
    {
        if( Laya.Browser.window.wx )
        {
            this._subcallobj = subcallobj;
            this._subcallback = subcallback;
            this._updatecallback = updatecallback;
            this._subfailcallback = subfailcallback;
            var wx:any = Laya.Browser.window.wx;
            if( wx.loadSubpackage )
            {
                const loadTask = wx.loadSubpackage({
                    name:name,
                    success: function(res) {
                        // 分包加载成功后通过 success 回调

                        var wxgamePlatform:WXGamePlatform = WXGamePlatform.Instance;
                        if( wxgamePlatform._subcallback && wxgamePlatform._subcallobj )
                        {
                            wxgamePlatform._subcallback.call( wxgamePlatform._subcallobj );
                        }
                    },
                    fail: function(res) {
                        // 分包加载失败通过 fail 回调
                        var wxgamePlatform:WXGamePlatform = WXGamePlatform.Instance;
                        if( wxgamePlatform._subfailcallback && wxgamePlatform._subcallobj )
                        {
                            wxgamePlatform._subfailcallback.call( wxgamePlatform._subcallobj );
                        }
                    }
                });  
                if(loadTask.onProgressUpdate){
                    loadTask.onProgressUpdate(res => {
                        var wxgamePlatform:WXGamePlatform = WXGamePlatform.Instance;
                        if( wxgamePlatform._updatecallback && wxgamePlatform._subcallobj )
                        {
                            wxgamePlatform._updatecallback.call( wxgamePlatform._subcallobj,res.progress );
                        }
                    })
                }
            }
            else
            {
                if( subcallobj && subcallback )
                {
                    subcallback.call( subcallobj );
                }
            }
        }
        else
        {
            if( subcallobj && subcallback )
            {
                subcallback.call( subcallobj );
            }
        }
    }

    /**
     * 获取转发详细信息
     * @param obj 
     * @param callobj 
     * @param succeedcallback 
     * @param failCallback 
     */
    public getShareInfo( obj:any,callobj:any, succeedcallback:Function,failCallback:Function = null )
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.getShareInfo({
                shareTicket:obj.shareTicket,
                success: function (res)
                {
                    succeedcallback.call( callobj,res );
                }
            })
        }
    }

    /**
     * 监听用户点击右上角菜单的“转发”按钮时触发的事件
     * @param title 
     * @param imageUrl 
     */
    public onShareAppMessage( title:string,imageUrl:string ):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.onShareAppMessage(function () {
                return {
                    title:title,
                    imageUrl:imageUrl
                }
            })
        }
    }

    /**
     * 主动拉起转发，进入选择通讯录界面。
     * @param title 
     * @param imageUrl 
     */
    public shareAppMessage( d:any ):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.shareAppMessage(d);
        }
    }

    /**
     * 显示当前页面的转发按钮
     * @param obj 
     */
    public showShareMenu( obj:any = null ):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.showShareMenu(obj);
        }
    }

    /**
     * 更新转发属性
     * @param obj 
     */
    public updateShareMenu( obj:any = null ):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.updateShareMenu(obj);
        }
    }

    /**
     * 显示当前页面的转发按钮
     */
    public showMenu() 
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.showShareMenu();
        }
    }

    /**
     * 本地存储
     * @param key 
     * @param data 
     */
    public setStorageSync(key:string, data:any) 
    {
        var wx = Laya.Browser.window.wx;
        if( wx )
        {
            wx.setStorageSync(key, data);
        }
    }
    
    /**
     * 获取本地存储
     * @param key 
     */
    public getStorageSync(key:string):any 
    {
        var wx = Laya.Browser.window.wx;
        if( wx )
        {
            return wx.getStorageSync(key);
        }
        return null;
    }

    public setUserCloudStorage(obj,callobj:any=null, succeedcallback:Function=null,failCallback:Function = null) 
    {
        var wx = Laya.Browser.window.wx;
        if( wx && wx.setUserCloudStorage )
        {
            wx.setUserCloudStorage({
                KVDataList: obj,
                success: function (res) {
                    if(succeedcallback)
                    {
                        succeedcallback.call( callobj,res );
                    }
                },
                fail: function (res) {
                    if(failCallback)
                    {
                        failCallback.call( callobj );
                    }
                }
            });
        }
    }

    /**
     * 显示消息提示框
     * @param word 
     */
    public toast(word:string):void 
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.showToast({ title: word });
        }
    }

    /**
     * 向开放数据域发送消息
     * @param obj 
     */
    public postMessage(str:string,data:any=null):void
    {
        var wx = Laya.Browser.window.wx;
        if( wx )
        {
            var context = wx.getOpenDataContext();
            context.postMessage({ action: str,data:data });
        }
    }

    /**
     * 创建一个 InnerAudioContext 实例
     */
    public createInnerAudioContext():any
    {
        if( Laya.Browser.window.wx )
        {
            return Laya.Browser.window.wx.createInnerAudioContext();
        }
        return null;
    }

    /**
     * 获取系统信息
     */
    public getSystemInfoSync():any
    {
        if( Laya.Browser.window.wx )
        {
            return Laya.Browser.window.wx.getSystemInfoSync();
        }
        return null;
    }

    /**
     * 预览图片，调用之后会在新打开的页面中全屏预览传入的图片，预览的过程中用户可以进行保存图片、发送给朋友等操作
     * @param obj 
     */
    public previewImage(obj) 
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.previewImage(obj);
        }
    }

    /**
     * 监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。
     * @param callobj 
     * @param succeedcallback 
     */
    public onHide(callobj:any, succeedcallback:Function):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.onHide(function (res) {
                WXGamePlatform.isShowing=false;
                if(succeedcallback&&callobj)
                {
                    succeedcallback.call(callobj, res);
                }
            })
        }
    }

    /**
     * 返回小程序启动参数
     * @param callobj 
     * @param succeedcallback 
     */
    public getLaunchOptionsSync():any
    {
        if( Laya.Browser.window.wx )
        {
            return Laya.Browser.window.wx.getLaunchOptionsSync();
        }
        return null;
    }
    /**
     * 隐藏消息提示框
     * @param obj 
     */
    public hideToast(obj):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.hideToast(obj);
        }
    }

    /**
     * 显示模态对话框
     * @param obj 
     */
    public showModal(obj):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.showModal(obj);
        }
    }

    

    /**
     * 清理存储数据
     */
    public clearStorage():void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.clearStorageSync();
        }
    }

    /**
     * 使手机发生较短时间的振动（15 ms）
     * @param obj 
     */
    public vibrateShort() 
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.vibrateShort();
        }
    }

    /**
     * 从本地缓存中移除指定 key
     * @param key 
     */
    public removeStorage(key:string):void
    {
        if( Laya.Browser.window.wx )
        {
            Laya.Browser.window.wx.removeStorage(key);
        }
    }

    public onAudioInterruptionBegin():void{
        if( Laya.Browser.window.wx ){
            Laya.Browser.window.wx.onAudioInterruptionBegin(function(){
                // SoundssManager.Instance.playbgSound("bgm");
                AudioControl.Instance.ClearAllSOUND();
            });
        }
    }

    public onAudioInterruptionEnd():void{
        if( Laya.Browser.window.wx ){
            Laya.Browser.window.wx.onAudioInterruptionEnd(function(){
                var wxgameplatform:WXGamePlatform = WXGamePlatform.Instance;
                Laya.timer.clear( wxgameplatform,wxgameplatform.onAudioEndCallback );
                Laya.timer.once( 500,wxgameplatform,wxgameplatform.onAudioEndCallback );
            });
        }
    }

    public onAudioEndCallback():void
    {
        DispatcherManager.dispatchEvent( WECHATEVENT.WECHATEVENT_onAudioInterruptionEnd );
    }

    /**
     * 退出游戏
     */
    public exitGame():void
    {
        var wx = Laya.Browser.window.wx;
        if( wx )
        {
            wx.exitMiniProgram();
        }
    }

    /**
     * 打开客服对话框
     */
    public openCustomerService():void
    {
        var wx = Laya.Browser.window.wx;
        if (wx)
        {
            var version = wx.getSystemInfoSync().SDKVersion;
            if( GameUtils.compareVersion(version, '2.0.3') >= 0 && wx.openCustomerServiceConversation )
            {
                wx.openCustomerServiceConversation({
                    showMessageCard:true,
                    sendMessageImg:"https://resource.51yoyoyo.com/res/wxsendmessageimg/smi.jpg"
                });
            }
            else
            {
                // AlertUtils.showWordTips("当前微信版本不支持");
            }
        }
    }

    /**
     * 监听内存不足告警
     */
    public onMemoryWarning():void
    {
        var wx = Laya.Browser.window.wx;
        if( wx && wx.onMemoryWarning )
        {
            wx.onMemoryWarning(function () {
              });
        }
    }

    public onError():void
    {
        var wx = Laya.Browser.window.wx;
        if( wx && wx.onError )
        {
            wx.onError(function( res ){
                console.log("*****onError",res);
            })
        }
    }

    static nowShareindex:number = 0;
    public nowshareObj:any;
    public nowsharesucceedfun:Function;
    public nowsharefailfun:Function;
    public nowshareinfo:any;
    public startShareTime:number;
    public isShareing:boolean = false;
    static callbackfailstate:number = 0;
    /**
     * 开始分享
     */
    public startShareApp(key:string,callobj:any=null,succeedCallback:Function=null,failCallback:Function = null):void
    {
        WXGamePlatform.nowShareindex=0;
        if( WXGamePlatform.ShareDict[key] )
        {
            this.shareApp( WXGamePlatform.ShareDict[key],callobj,succeedCallback,failCallback );
        }
    }

    private shareApp(info:any,callobj:any, success: Function,failCallback:Function) 
    {
        this.nowshareObj = callobj;
        this.nowshareinfo = info;
        this.nowsharesucceedfun = success;
        this.nowsharefailfun = failCallback;
        this.startShareTime = Laya.Browser.now();
        this.isShareing = true;
        WXGamePlatform.callbackfailstate = 0;
        this.shareAppMessage({
            title:info.tile,imageUrl:Global.cdnurl + info.img,query:"",
            success:function (res)
            {

            }, 
            fail: function (res){
                GlobalTip.Instance.showWordTips("您取消了分享");
                if (failCallback && callobj ) 
                {
                    failCallback.call(callobj);
                }
            }, 
            cancel: function (res) {
                WXGamePlatform.callbackfailstate = 1;
            }
        })
    }
        

    public showobj:any;
    public showCallback:Function;
    /**
     * 监听小游戏回到前台的事件
     * @param callobj 
     * @param succeedcallback 
     * @param failCallback 
     */
    public onShow(callobj:any=null, succeedcallback:Function=null,failCallback:Function = null) 
    {
        this.showobj = callobj;
        this.showCallback = succeedcallback;
        var wx = Laya.Browser.window.wx;
        if( wx )
        {
            wx.onShow(function (res) 
            {
                WXGamePlatform.isShowing=true;

                if( res && res.scene )
                {
                    WXGamePlatform.fromscene = Number( res.scene );
                }
                Laya.timer.frameOnce( 1,WXGamePlatform.Instance,WXGamePlatform.Instance.onShowSucceed );
            });
        }
    }

    public onShowSucceed():void
    {
        var wxgameplatform:WXGamePlatform = WXGamePlatform.Instance;
        if( wxgameplatform.showobj && wxgameplatform.showCallback )
        {
            wxgameplatform.showCallback.call( wxgameplatform.showobj );
        }
        if( wxgameplatform.isShareing ) //如果是分享状态
        {
            wxgameplatform.isShareing = false;
            var isShareSucceed:boolean=false;
            if( WXGamePlatform.callbackfailstate==0 ) 
            {
                var nowTime:number =Laya.Browser.now();
                var disTime:number =(nowTime - wxgameplatform.startShareTime)/1000;
                if( disTime>=WXGamePlatform.ShareTime || WXGamePlatform.nowShareindex >= 3 )
                {
                    isShareSucceed = true;
                }
            }
            WXGamePlatform.callbackfailstate=0;
            if( isShareSucceed )
            {
                WXGamePlatform.dayShareNum++;
                wxgameplatform.updateDayShareInfo();
                if( wxgameplatform.nowshareObj && wxgameplatform.nowsharesucceedfun )
                {
                    wxgameplatform.nowsharesucceedfun.call( wxgameplatform.nowshareObj );
                }
            }
            else
            {
                WXGamePlatform.nowShareindex++;
                wxgameplatform.showModal(
                {
                    title: "提示", content: "请每次分享到不同群,是否重新分享？", showCancel: true, cancelText: '取消', confirmText: '确定',
                    success: function (res)
                    {
                        var wxplatform:WXGamePlatform = WXGamePlatform.Instance;
                        if (res.confirm) 
                        {
                            WXGamePlatform.Instance.shareApp( wxplatform.nowshareinfo,wxplatform.nowshareObj,wxplatform.nowsharesucceedfun,
                                wxplatform.nowsharefailfun );
                        } 
                        else 
                        {
                            if( wxplatform.nowsharefailfun && wxplatform.nowshareObj )
                            {
                                wxplatform.nowsharefailfun.call( wxplatform.nowshareObj );
                            }
                        }
                    }, 
                    fail: function () 
                    {
                        
                    },
                    complete:function()
                    {

                    }
                });
            }
        }
    }

    static lastVideoTime:number = 0;
    private videoAd;
    public videocallobj:any;
    public videosucceedCallback:Function;
    private videofailCallback:Function;
    public nowvideokey:string;
     /**
     * 视频是否在播放中
     */
    static videoplaying:boolean = false;

    static istongjiVideoNum:boolean = true;

    /**
     * 看视频领奖励
     * @param callobj 
     * @param succeedcallback 
     */
    public playVideo( key:string, callobj:any=null, succeedcallback:Function=null,failCallback:Function=null,istongjiNum:boolean = true )
    {
        var wx = Laya.Browser.window.wx;
        if( wx && wx.createRewardedVideoAd )
        {
            if( !WXGamePlatform.videoplaying )
            {
                var time:number = this.lockVideoLeftTime();
                if( time > 0 )
                {
                    GlobalTip.Instance.showWordTips( "广告尚未准备好，请"+ time +"秒后再试" );
                    return;
                }
                DispatcherManager.dispatchEvent( WECHATEVENT.WECHATEVENT_losefocus );
                WXGamePlatform.istongjiVideoNum = istongjiNum;
                this.nowvideokey = key;
                WXGamePlatform.videoplaying=true;
                this.videocallobj = callobj;
                this.videosucceedCallback = succeedcallback;
                this.videofailCallback = failCallback;
                this.videoAd = wx.createRewardedVideoAd(
                {
                    adUnitId:'adunit-0c687084c908ee89'
                });
                this.videoAd.onClose(this.closeAD);
                this.videoAd.onError( this.onerro );
                this.videoAd.load().then(() => this.videoAd.show()).catch(err => { console.log(err.errMsg),WXGamePlatform.Instance.failVideo() })
            }
        }
    }

    public lockVideoLeftTime():number
    {
        var time:number = (Laya.Browser.now()-WXGamePlatform.lastVideoTime)/1000; 
        time = WXGamePlatform.VideoTime - time;
        return Math.ceil(time);
    }
    public onerro(res):void
    {
        var wxgamePlatform:WXGamePlatform = WXGamePlatform.Instance;
        WXGamePlatform.videoplaying=false;
        wxgamePlatform.videoAd.offError(wxgamePlatform.onerro); //移除 不然被多次调用
        wxgamePlatform.videoAd.offClose(wxgamePlatform.closeAD); //移除 不然被多次调用
        DispatcherManager.dispatchEvent( WECHATEVENT.WECHATEVENT_getfocus );
    }

    // 关闭广告
    public closeAD(status):void
    {
        WXGamePlatform.lastVideoTime = Laya.Browser.now();
        var wxgamePlatform:WXGamePlatform = WXGamePlatform.Instance;
        if (status && status.isEnded || status == undefined) 
        {
            if( WXGamePlatform.istongjiVideoNum )
            {
                WXGamePlatform.dayVideoNum++;
                wxgamePlatform.updateDayVideoInfo();
                DispatcherManager.dispatchEvent( WECHATEVENT.WECHATEVENT_updateVideoNums );
            }
            if( wxgamePlatform.videocallobj && wxgamePlatform.videosucceedCallback )
            {
                wxgamePlatform.videosucceedCallback.call( wxgamePlatform.videocallobj );
            }
        } 
        else 
        {
            GlobalTip.Instance.showWordTips( "未观看完整视频，无法获得奖励" );
            if( wxgamePlatform.videocallobj && wxgamePlatform.videofailCallback )
            {
                wxgamePlatform.videofailCallback.call( wxgamePlatform.videocallobj );
            }
        }
        WXGamePlatform.videoplaying=false;
        wxgamePlatform.videoAd.offError(wxgamePlatform.onerro); //移除 不然被多次调用
        wxgamePlatform.videoAd.offClose(wxgamePlatform.closeAD); //移除 不然被多次调用
        DispatcherManager.dispatchEvent( WECHATEVENT.WECHATEVENT_getfocus );
    }

    // 广告失败
    public failVideo():void
    {
        WXGamePlatform.lastVideoTime = Laya.Browser.now();
        WXGamePlatform.videoplaying=false;
        GlobalTip.Instance.showWordTips( "广告加载失败,试试别的方式吧~" );
        var wxgamePlatform = WXGamePlatform.Instance;
        wxgamePlatform.videoAd.offError(wxgamePlatform.onerro); //移除 不然被多次调用
        wxgamePlatform.videoAd.offClose(wxgamePlatform.closeAD); //移除 不然被多次调用
        if( wxgamePlatform.videocallobj && wxgamePlatform.videofailCallback ) 
        {
            wxgamePlatform.videofailCallback.call( wxgamePlatform.videocallobj );
        }
        DispatcherManager.dispatchEvent( WECHATEVENT.WECHATEVENT_getfocus );
    }

    public isCanVideo():boolean
    {
        if( WXGamePlatform.dayVideoNum < WXGamePlatform.VideoNum )
        {
            if( WXGamePlatform.dayVideoNum == 0 )
            {
                return true;
            }
            var videobs:number = Math.floor(WXGamePlatform.dayVideoNum/WXGamePlatform.VideotoShare);
            var sharebs:number = Math.floor(WXGamePlatform.dayShareNum/WXGamePlatform.SharetoVideo);
            if( videobs > sharebs )
            {
                return false;
            }
            else if( videobs < sharebs )
            {
                return true;
            }
            else
            {
                var videoyushu:number = WXGamePlatform.dayVideoNum%WXGamePlatform.VideotoShare;
                if( videoyushu != 0 )
                {
                    return true;
                }
                var shareyushu:number = WXGamePlatform.dayShareNum%WXGamePlatform.SharetoVideo;
                if( shareyushu != 0 )
                {
                    return false;
                }
                return true;
            }
        }
        return false;
    }

    private bannerRunTime:number=0;
    private bannerAd;
    public nowStype:any;
    private _bannerTypeList:Array<any> = [];
    public createBanner( bannertype:string="",style:any):void
    {
        if( Laya.Browser.window.wx )
        {
            if( bannertype != "" )
            {
                var bo:boolean = false;
                for( var i:number = 0;i < this._bannerTypeList.length;i++ )
                {
                    if( bannertype == this._bannerTypeList[i].type )
                    {
                        this._bannerTypeList[i].style = style;
                        var arr:Array<any> = this._bannerTypeList.splice( i,1 );
                        this._bannerTypeList.push( arr[0] );
                        bo = true;
                        break;
                    }
                }
                if( !bo )
                {
                    this._bannerTypeList.push( { type:bannertype,style:style } );
                }
            }
            else
            {
                if( this._bannerTypeList.length==0 )
                {
                    return;
                }
                else
                {
                    var item:any = this._bannerTypeList[this._bannerTypeList.length-1];
                    style = item.style;
                }
            }
            if (this.bannerAd) 
            {
                var now = Laya.Browser.now();
                //超过3分钟刷新
                if (now - this.bannerRunTime > 60000 * 3) 
                {

                    this.bannerAd.offError(this.bannerError);
                    this.bannerAd.offResize(this.bannerResize);
                    this.bannerAd.destory();
                    this.createNewBanner(style);
                }
                else
                {
                    this.showBanner(style);
                }
            } 
            else 
            {
                this.createNewBanner(style);
            }
        }
    }

    private _screenwidth:number = 0;
    bannerheight:number = 0;
    bannerwidth:number = 0;
    isonResize:boolean = false;

    private createNewBanner(style: any) {
        var wx = Laya.Browser.window.wx;
        if( wx && wx.createBannerAd )
        {
            this.nowStype = style;
            this.bannerRunTime = Laya.Browser.now();
            var info = this.getSystemInfoSync();
            this._screenwidth = info.screenWidth;
            var scale:number = 1;
            if( style.hasOwnProperty("scale") )
            {
                scale = style.scale;
            }
            this.bannerAd = wx.createBannerAd({
                adUnitId: 'adunit-8c2d586135fa6d4f',
                adIntervals:30,
                style: {
                    left: 0,
                    top: info.screenHeight - 105,
                    width: info.screenWidth * scale
                }
            });
            if (this.bannerAd) {
                this.bannerAd.onError(this.bannerError);
                this.showBanner(style);
            }
        }
    }

    private bannerResize( res ):void
    {
        var self = WXGamePlatform.Instance;
        self.bannerAd.offResize(self.bannerResize);
        self.isonResize = false;
        var nowstype:any = self.nowStype;
        if( !nowstype )
        {
            return;
        }
        var info = self.getSystemInfoSync();
        var percentageH:number = Laya.Browser.clientHeight/Laya.stage.displayHeight;
        var percentageW:number = Laya.Browser.clientWidth/Laya.stage.displayWidth;
        self.bannerwidth = res.width;
        self.bannerheight = res.height;
        if( nowstype.hasOwnProperty("x") && nowstype.x != 0 )
        {
            self.bannerAd.style.left = nowstype.x * percentageW;
        }
        else
        {
            self.bannerAd.style.left = (info.windowWidth - res.width) * 0.5;
        }
        if( nowstype.hasOwnProperty("y") && nowstype.y != 0 )
        {
            self.bannerAd.style.top = nowstype.y * percentageH;
        }
        else
        {
            self.bannerAd.style.top = (info.windowHeight - res.height) - 15;
        }
    }

    private bannerError(err:any):void
    {

    }

    private showBanner( style ) {
        if (this.bannerAd) 
        {
            this.nowStype = style;
            var info = this.getSystemInfoSync();

            var nowstype:any = this.nowStype;
            var scale:number = 1;
            if( nowstype.hasOwnProperty("scale") )
            {
                scale = nowstype.scale;
            }
            var percentageH:number = Laya.Browser.clientHeight/Laya.stage.displayHeight;
            var percentageW:number = Laya.Browser.clientWidth/Laya.stage.displayWidth;
            if( nowstype.hasOwnProperty("x") && nowstype.x != 0 )
            {
                this.bannerAd.style.left = nowstype.x * percentageW;
            }
            else
            {
                this.bannerAd.style.left = (info.windowWidth - this.bannerwidth) * 0.5;
            }
            if( nowstype.hasOwnProperty("y") && nowstype.y != 0 )
            {
                this.bannerAd.style.top = nowstype.y * percentageH;
            }
            else
            {
                this.bannerAd.style.top = (info.windowHeight - this.bannerheight) - 15;
            }
            this.bannerAd.style.width = info.screenWidth * scale;
            if( !this.isonResize )
            {
                this.isonResize = true;
                this.bannerAd.onResize(this.bannerResize);
            }
            this.bannerAd.show();
        }
    }

    public hideBanner( type:string = "" ) {
        if (this.bannerAd) {
            this.bannerAd.hide();
        }
        if( type != "" )
        {
            for( var i:number = 0;i < this._bannerTypeList.length;i++ )
            {
                if( type == this._bannerTypeList[i].type )
                {
                    this._bannerTypeList.splice( i,1 );
                    break;
                }
            }
            if( this._bannerTypeList.length > 0 )
            {
                var item:any = this._bannerTypeList[this._bannerTypeList.length-1];
                this.createBanner( item.type,item.style );
            }
        }
    }

    /**
     * 排行榜打开类型存储
     */
    private _openrankDict:any={};
    // private _wxOpenDataViewer:WXOpenDataViewer;
    /**
     * 打开好友排行榜
     */
    public openFriendRank( type:string,viewType:string,rect:Laya.Rectangle,parent:Laya.Sprite = null,data:any = null ):void
    {
        this.closeziyuStage();
        this._openrankDict[viewType] = {type:type,viewType:viewType,rect:rect,parent:parent,data:data};
        this.initziyuStage(rect,parent);
        this.postMessage( type,data );
    }

    /**
     * 排行榜打开状态时候，切换显示类型
     * @param type 
     */
    public changeFriendRank( type:string ):void
    {
        this.postMessage( type );
    }

    /**
     * 排行榜上一页
     */
    public prePageRank():void
    {

    }

    /**
     * 排行榜下一页
     */
    public nextPageRank():void
    {
        
    }

    /**
     * 关闭好友排行榜
     */
    public closeFriendRank( viewType:string ):void
    {

        this.closeziyuStage();
        if( this._openrankDict[viewType] )
        {
            delete this._openrankDict[viewType];
        }
        for( var s in this._openrankDict )
        {
            var itemd:any = this._openrankDict[s];
            this.openFriendRank( itemd.type,itemd.viewType,itemd.rect,itemd.parent,itemd.data );
            break;
        }
    }

    /**
     * 初始化子域
     * @param rect 
     * @param parent 
     */
    private initziyuStage( rect:Laya.Rectangle,parent:Laya.Sprite ):void
    {
        // if( !this._wxOpenDataViewer )
        // {
        //     this._wxOpenDataViewer = new WXOpenDataViewer();
        //     if( parent )
        //     {
        //         parent.addChild( this._wxOpenDataViewer );
        //     }
        //     else
        //     {
        //         GameLayerManager.Instance.topLayer.displayObject.addChild( this._wxOpenDataViewer );
        //     }
        // }
        // this._wxOpenDataViewer.x = rect.x;
        // this._wxOpenDataViewer.y = rect.y;
        // this._wxOpenDataViewer.width = rect.width;
        // this._wxOpenDataViewer.height = rect.height;
    }

    /**
     * 销毁子域
     */
    private closeziyuStage():void
    {
        // if( this._wxOpenDataViewer )
        // {
        //     this._wxOpenDataViewer.destroy();
        //     this._wxOpenDataViewer.removeSelf();
        //     this._wxOpenDataViewer = null;
        // }
    }

    /**
     * 数据上传（用于排行榜数据显示）
     * @param param1 上报数据
     * @param param2 上报数据
     */
    public storeToCloud(param1:number,param2:number):void
    {
        var cacheMager:LocalDataControl = LocalDataControl.Instance;
        var score1:number = cacheMager.getnum( "param1" );
        // var score2:number = cacheMager.getnum( "param2" );
        param1 = Math.floor(param1);
        param2 = Math.floor(param2);
        var result1:number = param1;
        var result2:number = param2;

        if( result1 < score1 )
        {
            result1 = score1;
        }
        else
        {
            cacheMager.addstr( "param1",result1.toString() );
        }
        var arr:Array<any> = [];
        arr.push( { key:"param1",value:result1.toString() } );
        arr.push( { key:"param2",value:result2 + "" } );
        this.setUserCloudStorage(arr);
    }

    static gameclubButton:any;
    public createGameClubButton( style:any,icon:string = "green" ):void
    {
        var wx:any = Laya.Browser.window.wx;
        if( wx && style )
        {
            style.width = 40;
            style.height = 40;
            WXGamePlatform.gameclubButton = wx.createGameClubButton(
                {
                    icon: icon,
                    style: style
                }
            )
            if(WXGamePlatform.gameclubButton)
            {
                WXGamePlatform.gameclubButton.show();
            }
        }
        
    }
}

