import  {Main} from "../Main";
// import RankSDK from "../Rank/RankSDK";
 import { AccountManager } from "./AccountManager";
import RankSDK from "../Rank/RankSDK";

export  class WXSDK  {
    private static ins:WXSDK;
    static codeValue = "";
    static shareOpenId = "";
    static openId = 0;
    static shareScene = "";
    static uid = "123";
    static querychannel = "";
    static referrerInfoappId = "";
    constructor(){
        WXSDK.ins = this;
    }
    public static get Instance():WXSDK{
        if(WXSDK.ins){
            return WXSDK.ins
        }
        else{
            return new WXSDK();
        }
    }
    
    static Init(){
        Laya.Browser.window.wx.showShareMenu({
            withShareTicket: true
        });
        Laya.Browser.window.wx.onShareAppMessage(function () {
            // console.log(HPApi.shares);
            // var share = HPApi.shares[Comutil.RandomANumber(0,HPApi.shares.length)];
            return {
                title:"",
                imageUrl: "gameResources/res/share/sharepictrue.png",
                // query: "userId=" + wxsdk.shareOpenId,
            }
        });

        Laya.Browser.window.wx.onShow((option) => {
            var shareTicket = option.shareTicket;
            var userId = option.query.userId;
            var shareTitle = option.query.shareTitle;
            Main.SceneNum = option.scene;
            WXSDK.querychannel = option.query.channel;
            WXSDK.shareOpenId = option.query.userId;
            console.log("option---",option);
            console.log("scene:", option.scene);
            if (WXSDK.querychannel != null){
                console.log("onShow channel is:", WXSDK.querychannel);
            }
            if(option.referrerInfo)
            {
                WXSDK.referrerInfoappId = option.referrerInfo.appId;
                console.log("onShow appId is:", option.referrerInfo.appId);
            }
        });
    }
    
    //微信登陆
    public static DengLu(_complete:Function)
    {
        var that = this;
        Laya.Browser.window.wx.login({
            success: function (res) {
                if (res.code) 
                {
                    console.log("微信登陆成功----");
                    that.codeValue = res.code;
                    RankSDK.ShuShi();
                    console.log("shareid:"+WXSDK.shareOpenId);
                    new AccountManager(res.code,"","","",0,"","","","",WXSDK.shareOpenId,WXSDK.shareOpenId,Main.Ver);
                    _complete(res);
                }
                else {
                    WXSDK.DengLu(WXSDK.DengLu);
                    console.log('wx no code' + res.errMsg);
                }
            },
            fail: function (res) { console.log("wx.login: failed, res=" + res); }
        });
    }
    
    public static ShowTxt(text: string) 
    {
        if (Laya.Browser.window.wx) 
        {
            Laya.Browser.window.wx.showToast({ title: text });
        }
        else 
        {
            console.log(text);
        }
    }
    static shake = true;
    //短震动
    private static ShortShake(): void {
        Laya.Browser.window.wx.vibrateShort({});
    }
    //长震动
    private static LongShake():void
    {
        Laya.Browser.window.wx.vibrateLong({});
    }
    //震动方法
    public static Shake(_short = true)
    {
        if(Laya.Browser.onWeiXin && WXSDK.shake)
        {
            if(_short)
            {
                this.ShortShake();
            }
            else
            {
                this.LongShake();
            }
        }
    }
    //加载分包
    public static LoadSubPackage(name,_complete){
        if(Laya.Browser.onWeiXin){
            const loadTask = Laya.Browser.window.wx.loadSubpackage({
                name: 'Game', // name 可以填 name 或者 root
                success: function(res) {
                    _complete && _complete(true)
                    console.log("分包加载成功");
                },
                fail: function(res) {
                    _complete && _complete(false);
                    console.log("分包加载失败");
                }
              })
        }
        else{
            console.log("未进行分包加载");
            _complete && _complete(true)
        }

    }

//上传分数
    public static UpdateScore(_level: number)
    {
        var kvDataList = new Array();
        let date = new Date().getTime();
        var myValue = JSON.stringify({
            "wxgame": 
            {
                "Level": _level,
                "update_time": date.toString(),
            }
        });

        kvDataList.push({key:"Level", value: myValue});

        if( Laya.Browser.onWeiXin)
        {
            Laya.Browser.window.wx.setUserCloudStorage(
                {
                    KVDataList: kvDataList,
                    success: r=>
                    {
                        console.log("KVDATALIST---",kvDataList);
                        console.log("上传分数成功:"+_level);
                    }
                })
        }
    }
    
    public GuanKaKaiShi(stageId :string,stageName:string,userId:string):void
    {
        if(Laya.Browser.window && Laya.Browser.window.wx)
        {
                Laya.Browser.window.wx.aldStage.onStart(
                {
                    stageId : stageId,     //关卡ID 该字段必传
                    stageName : stageName, //关卡名称  该字段必传
                    userId : userId //用户ID 可选
                    }
                );
        }
    }
    public GuanKaChengGong(stageId :string,stageName:string,userId:string):void
    {
        if(Laya.Browser.window && Laya.Browser.window.wx)
        {
                Laya.Browser.window.wx.aldStage.onEnd(
                {
                    stageId : stageId,     //关卡ID 该字段必传
                    stageName : stageName, //关卡名称  该字段必传
                    userId : userId, //用户ID 可选
                    event : "complete",   //关卡完成  关卡进行中，用户触发的操作    该字段必传
                    params : 
                    {
                        desc : "关卡完成"   //描述
                    }
                    }
                );
        }
    }

    public GuanKaShiBai(stageId :string,stageName:string,userId:string,score:string,carname:string):void
    {
        if(Laya.Browser.window && Laya.Browser.window.wx)
        {
                Laya.Browser.window.wx.aldStage.onEnd(
                {
                    stageId : stageId,     //关卡ID 该字段必传
                    stageName : stageName, //关卡名称  该字段必传
                    userId : userId, //用户ID 可选
                    event : "fail",   //关卡完成  关卡进行中，用户触发的操作    该字段必传
                    params : 
                    {
                        desc : "失败" ,
                        score: score,//描述
                        car: carname//描述
                    }
                    }
                );
        }
    }



    //更新
    IsNeedUpdate() {
        if (!Laya.Browser.onWeiXin) return;
        const updateManager = Laya.Browser.window.wx.getUpdateManager();
			updateManager.onCheckForUpdate(function (res) {
				console.log("最新版本:" + res.hasUpdate);
			}
			);
			updateManager.onUpdateReady(function () {
				Laya.Browser.window.wx.showModal({
					showCancel: false,
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success(res) {
						updateManager.applyUpdate();
					},
					fail(res?) {
						updateManager.applyUpdate();
					}
				});
			});
       }
    
}