import { Main } from "../Main";

import { AccountManager } from "./AccountManager";
import { FengXiang } from "../Tools/ShareUtil";



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(){
       
    }
    
    //微信登陆
    public static DengLu(_complete:Function)
    {
        var that = this;
        Laya.Browser.window.wx.login({
            success: function (res) {
                if (res.code) 
                {
                    FengXiang.Instance.RegFenxiang();
                    console.log("微信登陆成功----");
                    that.codeValue = res.code;
                    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.onWeiXin) 
        {
            Laya.Browser.window.wx.showToast({ title: text });
        }
        else 
        {
            console.log(text);
        }
    }
    static OnShow(cb: Function) {
        if (!Laya.Browser.onWeiXin) return;
        Laya.Browser.window.wx.onShow(cb);
    }

    static OffShow(cb: Function) {
        if (!Laya.Browser.onWeiXin) return;
        Laya.Browser.window.wx.offShow(cb);
    }
    
    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)
        }

    }

    /** 是否震动中 */
    static isShake:boolean;
    static times = 1.3;
    static num:number = 0;
    static offsetArr = [0, 0];
    static offset = 14;
    static canshakestage = false;

    static stageShake(callBack:Function = null,speed:number = 32):void
    {
        if(this.isShake || !this.canshakestage) return;
        this.isShake = true;

        var point:Laya.Vector2 = new Laya.Vector2(Laya.stage.x, Laya.stage.y);
        Laya.stage.timerLoop(speed, this, this.shakeObject,[point,callBack]);
    }

    static shakeObject(_point:Laya.Vector2,_callBack):void
    {
        var count:number = (this.num++) % 4;
        this.offsetArr[this.num % 2] = count < 2 ? 0 : this.offset;
        Laya.stage.x = this.offsetArr[0] + _point.x;
        Laya.stage.y = this.offsetArr[1] + _point.y;

        if(this.num > (this.times * 4 + 1))
        {
            Laya.stage.clearTimer(this, this.shakeObject);
            Laya.stage.pos(0,0);
            this.num = 0;
            this.isShake = false;
            if(_callBack != null)
            {
                _callBack();
            }
        }
    }

    //上传新手指引  0为展示  1为不展示
    public static UpdateGuide(ShowGuide:number = 0){
        var kvDataList = new Array();
        let date = new Date().getTime();
        var myValue = JSON.stringify({
            "guide": 
            {
                "ShowGuide": ShowGuide,
                "update_time": date.toString()
            }
        });
        kvDataList.push({key:"ShowGuide", value: myValue});
        if (Laya.Browser.window.wx)  {
            Laya.Browser.window.wx.setUserCloudStorage(
                {
                    KVDataList: kvDataList,
                    success: r =>  {
                        console.log("KVDATALIST---", kvDataList);
                        console.log("上传新手指引成功:" + ShowGuide);
                    }
                })
        }
    }
//上传分数
    public static UpdateScore(max_score: number)
    {
        var kvDataList = new Array();
        let date = new Date().getTime();
        var myValue = JSON.stringify({
            "wxgame": 
            {
                "max_score": max_score,
                "update_time": date.toString(),
            }
        });

        kvDataList.push({key:"max_score", value: myValue});
        
        if( Laya.Browser.window.wx)
        {
            Laya.Browser.window.wx.setUserCloudStorage(
                {
                    KVDataList: kvDataList,
                    success: r=>
                    {
                        console.log("KVDATALIST---",kvDataList);
                        console.log("上传分数成功:"+max_score);
                    }
                })
        }
    }

    public static fengxiangtupian(callback?: Function): void 
    {
        if(Laya.Browser.window.wx == null) {
            return;
        }
        // if(!AccountManager.Instance.curplayerData.fenxiang)
        // {
        //     WXSDK.ShowTxt("暂未开放");
        //     return;
        // }
        var _title = "有人@你，一起骑马仗箭走天涯";
        var t:number = AccountManager.Instance.ServerTime;
        Laya.Browser.window.wx.aldShareAppMessage({
        title:_title,
		imageUrl: "Game/res/textrue/share.jpg",
        query: "userId=" + AccountManager.Instance.curplayerData.userId + "_"  + t + "_" + Math.floor(9999*Math.random()).toString()// + "&shareTitle=" + _title+"&channel="+share_path1,
        });
        if(callback)
        {
            // FengXiang.Instance.kaishifengxiang(callback);
        }
    }

    public static ShareContent():string{
        return AccountManager.Instance.curplayerData.ShareContent;
    }

    static AldEvent(eventName: string, key: string = "用户id", value: string = ""): void {
        if (!Laya.Browser.onWeiXin) return;
        Laya.Browser.window.wx.aldSendEvent(eventName, { key: value });
    }

    static AldStart(stageId: string): void {
        if (!Laya.Browser.onWeiXin) return;
        Laya.Browser.window.wx.aldStage.onStart({
            stageId: stageId,
            stageName: "第" + stageId + "关",
        });
    }

    static AldEnd(stageId: string, isComplete: boolean): void {
        if (!Laya.Browser.onWeiXin) return;
        let event = isComplete ? "complete" : "fail";
        let desc = isComplete ? "关卡完成" : "关卡失败";
        Laya.Browser.window.wx.aldStage.onEnd({
            stageId: stageId,
            stageName: "第" + stageId + "关",
            event: event,
            params: {
                desc: desc
            }
        });
    }


   
}