
import { ShareUtil } from "./ShareUtil";
import { Main } from "../Main";
import { PlayerAccount } from "../Scripts/Network/PlayerAccount";
import { GameUtils } from "../GameUtils/GameUtils";


export enum WxParkInforType
{
    stage
}

export default class WxApi 
{
    private static WxApiInstance:WxApi;
    constructor()
    {
        WxApi.WxApiInstance = this;
    }
    public static get Instance():WxApi
    {
        if(WxApi.WxApiInstance)
        {
            return WxApi.WxApiInstance;
        }
        else
        {
            return new WxApi();
        }
    }

    avator:string = "";
    openId = 0;
    codeValue = "";
    shareOpenId = "";
    shareScene = "";
    static referrerInfoappid = "";
    static querychannel = "";
    static queryuserId = "123";

    public WxInit(callback:Function)
    {
        Laya.Browser.window.wx.showShareMenu({
            withShareTicket: true
        });

        Laya.Browser.window.wx.onShareAppMessage(function () {
            return {
                title: "有人@你，能追上我，让你当王者又如何",
                imageUrl: "https://res.xcx.snsfun.com/melee/share/fallrace1.png",
                query: "userId=" + this.shareUserId,
            }
        });

        Laya.Browser.window.wx.onShow((option) => {
            var adsdasdsa = option.shareTicket;
            var afsafsfsa = option.query.userId;
            var dadads = option.query.shareTitle;
            console.log("scene:", option.scene);
            Main.sceneValue = option.scene;
            WxApi.querychannel = option.query.channel;
            if (WxApi.querychannel != null)  {
                console.log("onShow channel is:", WxApi.querychannel);
            }
            if(option.referrerInfo)
            {
                WxApi.referrerInfoappid = option.referrerInfo.appId;
                console.log("onShow appId is:", option.referrerInfo.appId);
            }
            WxApi.queryuserId = afsafsfsa;
            callback(adsdasdsa, afsafsfsa, WxApi.querychannel, option.scene, dadads);
        });

    }

    public SetShareScence(sceneS)
    {
        if (sceneS != "" && sceneS != null)  {
            this.shareScene = sceneS;
        }
    }

    public ShareScene()
    {
        return this.shareScene;
    }
    public gagasgasgsa()
    {
        if (typeof (Laya.Browser.window.wx) != "undefined")  {
            return Laya.Browser.window.wx.getSystemInfoSync();
        }
    }
    public OpenId(id)
    {
        this.openId = id;
    }
    public ShareId()
    {
        return this.shareOpenId;
    }
    public WXLogin(cb:Function)
    {
        var that = this;
        Laya.Browser.window.wx.login({
            success: function (res) {
                if (res.code) 
                {
                    that.codeValue = res.code;
                    that.avator = res.avator;
                    console.log(res.avator);
                    cb(res);
                }
                else {
                    console.log('获取用户登录态失败！' + res.errMsg);
                }
            },
            fail: function (res) { console.log("wx.login: failed, res=" + res); }
        });
    }

    public SetShareId(tid)
    {
        if (tid != "" && tid != null)  
        {
            this.shareOpenId = tid;
        }
    }

    static CanShake = true;

    private static shake(): void {
        Laya.Browser.window.wx.vibrateShort({});
    }
    private static shakeLong():void
    {
        Laya.Browser.window.wx.vibrateLong({});
    }

    public static Shake(_short = true)
    {
        if(Main.OnWx && WxApi.CanShake)
        {
            if(_short)
            {
                this.shake();
            }
            else
            {
                this.shakeLong();
            }
        }
    }

    public static Message(text: string) 
    {
        if (Laya.Browser.window.wx) 
        {
            Laya.Browser.window.wx.showToast({ title: text });
        }
        else 
        {
            console.log(text);
        }
    }

    // 显示提示信息
    public static ShowToast(text:string){
        if(Laya.Browser.window.wx){
            Laya.Browser.window.wx.showToast( {title:text} );
        }
        else{
            console.log(text);
        }
    }

    //显示加载信息
    public static ShowLoading(title:string="加载中...")
    {
        (Laya.Browser.onMiniGame) && Laya.Browser.window.wx.showLoading({title: title, mask: true});
    }
    public static HideLoading()
    {
        (Laya.Browser.onMiniGame) && Laya.Browser.window.wx.hideLoading();
    }

    public static shareImage(channel:string,callback: Function = null,shareType:string): void 
    {
        if(Laya.Browser.window.wx == null) {
            return;
        }
        if(!PlayerAccount.CurrentAccount.CurAccountData.share)
        {
            WxApi.Message("暂未开放");
            return;
        }

        var sharecontent = PlayerAccount.CurrentAccount.CurAccountData.sharecontent;
        var content = JSON.parse(sharecontent);
        var con = content[GameUtils.getRandomInt(0,content.length - 1)];
        var _title = con.title;
        var _url = con.url;

        var t:number = PlayerAccount.CurrentAccount.ServerTime;
        Laya.Browser.window.wx.aldShareAppMessage({
        title:_title,
        imageUrl:_url,
        query: "userId=" + PlayerAccount.CurrentAccount.CurAccountData.UseId + "_" + shareType + "_" + t + "_" + Math.floor(9999*Math.random()).toString() + "&shareTitle=" + _title,
        });
        if(callback)
        {
            ShareUtil.Instance.beginShare(callback);
        }
    }

    public recordAldEvent(key:string,value:string):void
    {
        if(Laya.Browser.window && Laya.Browser.window.wx)
        {
            Laya.Browser.window.wx.aldSendEvent(key,{key:value});
        }
    }

    public levelStart(stageId :string,stageName:string,userId:string):void
    {
        console.log("开始记录关卡:" + stageId);
        if(Laya.Browser.window && Laya.Browser.window.wx)
        {
                Laya.Browser.window.wx.aldStage.onStart(
                {
                    stageId : stageId,     //关卡ID 该字段必传
                    stageName : stageName, //关卡名称  该字段必传
                    userId : userId //用户ID 可选
                    }
                );
        }
    }
    public levelSuccess(stageId :string,stageName:string,userId:string):void
    {
        console.log("记录关卡:完成" + stageId);
        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 levelFail(stageId :string,stageName:string,userId:string,score:string,carname:string):void
    {
        console.log("记录关卡:失败" + stageId);
        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//描述
                    }
                    }
                );
        }
    }

    public static writeStage(stage: number)
    {
        var kvDataList = new Array();
        let date = new Date().getTime();
        var myValue = JSON.stringify({
            "wxgame": 
            {
                "stage": stage,
                "update_time": date.toString(),
            }
        });

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