import { Main } from "../Main";
import ViewManager from "../game_logic/ViewManager";
import { SettingController } from "../game_logic/SettingController";
import { ShareModule } from "./ShareModule";
import UserModel from "./UserModel";

export class WXSdk {
    public setShareId(tid) {
        if (tid != "" && tid != null) {
            this.shareId = tid;
            console.log("[LOG]: setShareOpenId.tid=", this.shareId)
        }
    }
    private static instance: WXSdk;
    public static get Instance(): WXSdk {
        return WXSdk.instance || (WXSdk.instance = new WXSdk());
    }
    public static Lodining: boolean = false;
    public get getShareId() {
        return this.shareId;
    }
    public set ShareScene(sceneS) {
        if (sceneS != "" && sceneS != null) {
            this.shareScene = sceneS;
        }
    }
    public init(cb: any) {
        Laya.Browser.window.wx.showShareMenu({
            withShareTicket: true
        });
        //this.shezhiShareMessage(null, null);
        Laya.Browser.window.wx.onShow(function (option) {
            var shareTicket = option.shareTicket;
            var shareid = option.query.shareid;
            var scene = decodeURIComponent(option.query.scene);
            console.log("全局path=:", option.path);
            console.log("decodeURIComponent", option.query.scene);
            var sceneQuery = JSON.stringify(option.query);
            if (Main.wxValue =="")  {
                Main.wxValue = option.scene;
            }
            console.log("scene", option.scene);
            console.log("sceneQuery", sceneQuery);
            var channel = option.query.channel;
            var appid;
            if (option.referrerInfo) {
                console.log("referrerInfo:" + JSON.stringify(option.referrerInfo));
                appid = option.referrerInfo.appId;
                if (appid) {
                    console.log("onShow appis is:", appid);
                } else {
                    console.log("onShow appis is null");
                }
            } else {
                console.log("referrerInfo为空");
            }
            if (channel != null) {
                console.log("onShow channel is:", channel);
            }
            cb(shareTicket, shareid, channel, appid);
        });
    }
    public get ShareScene() {
        return this.shareScene;
    }
    public static ShareMessage(title?, imageUrl?) {
        if (!Main.IsWx) return;
        var t: number = UserModel.Instance.CurModel.ServerTime;
        var _title = title;
        var _url = imageUrl;
        if (!_title) {
            _title = UserModel.Instance.CurModel.sharetitle;
            _url = UserModel.Instance.CurModel.shareimage;
        }
        Laya.Browser.window.wx.onShareAppMessage(() => ({
            title: _title,
            imageUrl: _url,
            query: "shareid=" + UserModel.Instance.CurModel.userid + "_" + t + "_" + Math.floor(9999 * Math.random()).toString()
        }));
    }
    public wx_login(cb: Function) {
        if (WXSdk.Lodining) {
            return;
        }
        WXSdk.Lodining = true;
        console.log("Excute wx.login! shareOpenId: " + this.shareId);
        Laya.Browser.window.wx.login({
            success: function (res) {
                console.log("wx.login: success! res.code=" + res.code);
                if (res.code) {
                    WXSdk.Lodining = false;
                    console.log("将要传递的参数:" + res);
                    cb(res);
                }
                else {
                    console.log('获取用户登录态失败！' + res.errMsg);
                    cb("error");
                }

            },
            fail: function (res) { console.log("wx.login: failed, res=" + res); WXSdk.Lodining = false; cb("error"); }
        });
    }
    private shareId = "";
    private shareScene = "";
    //显示加载信息
    public static ShowLoading(title: string = "加载中...", isShowWx = true) {
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            if (isShowWx) {
                Laya.Browser.window.wx.showLoading({ title: title, mask: true });
            }
            ViewManager.Instance.OpenMask();
        }
    }
    public static SystemInfo() {
        if (Laya.Browser.window.wx) {
            return Laya.Browser.window.wx.getSystemInfoSync();
        }
    }
    // private static button;
    // public static showbjWxGameQuan(flag: boolean): void {
    //     if (Laya.Browser.window.wx == null) {
    //         return;
    //     }
    //     if (flag) {
    //         if (WeiXinSDK.button == null) {
    //             let info = Laya.Browser.window.wx.getSystemInfoSync();
    //             if (!info) return;
    //             var top = 474 * info.windowHeight / Laya.stage.height;
    //             var height = 94 * info.windowHeight / Laya.stage.height;
    //             var width = height * 95 / 94;
    //             WeiXinSDK.button = Laya.Browser.window.wx.createGameClubButton
    //                 ({
    //                     type: "image",
    //                     image: 'res/wx.png',
    //                     style:
    //                         {
    //                             left: 0,
    //                             top: top,
    //                             width: width,
    //                             height: height
    //                         }
    //                 })

    //         }
    //         WeiXinSDK.button.show();
    //     }
    //     else {
    //         if (WeiXinSDK.button) {
    //             WeiXinSDK.button.hide();
    //         }
    //     }
    // }
    //退出


    // 显示提示信息//
    public static ShowToast(text: string, icon = true) {
        if (Laya.Browser.window.wx) {
            var t_icon = icon ? "success" : "none";
            Laya.Browser.window.wx.showToast({ title: text, icon: t_icon });
        }
        else {
            console.log(text);
        }
    }
    //1:pet 2:人物
    // public static XianShi_Model(content: string, callback: Function = null, type = 1, title = "") {
    //     if (Laya.Browser.window && Laya.Browser.window.wx) {
    //         if (type == 1) {
    //             var cancelText = "残忍丢掉";
    //             var confirmText = "带上一起";
    //         } else {
    //             var cancelText = "不想";
    //             var confirmText = "想";
    //         }

    //         Laya.Browser.window.wx.showModal({
    //             title: title,
    //             content: content,
    //             cancelText: cancelText,
    //             confirmText: confirmText,
    //             success(res) {
    //                 if (res.confirm) {
    //                     console.log('用户点击确定');
    //                     callback(true);
    //                 } else if (res.cancel) {
    //                     console.log('用户点击取消');
    //                     callback(false);
    //                 }
    //             },
    //             fail(res?) {
    //                 console.log('用户点击取消');
    //                 callback(false);
    //             }
    //         })
    //     }
    // }
    public static ShortVibrate(): void {
        if (Laya.Browser.window.wx && SettingController.Instance.vibrate) {
            Laya.Browser.window.wx.vibrateShort({});
        }
    }

    public static LongVibrate(): void {
        if (Laya.Browser.window.wx && SettingController.Instance.vibrate) {
            Laya.Browser.window.wx.vibrateLong({});
        }
    }
    public static HideLoading(isShowWx = true) {
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            if (isShowWx) {
                Laya.Browser.window.wx.hideLoading();
            }
            ViewManager.Instance.CloseMask();
        }
    }
    public static Success(stageId: string): void {
        if (!Main.IsWx) return;
        Laya.Browser.window.wx.aldStage.onEnd(
            {
                stageId: stageId,     //关卡ID 该字段必传
                stageName: "第" + stageId + "关", //关卡名称  该字段必传
                event: "complete",   //关卡完成  关卡进行中，用户触发的操作    该字段必传
                params:
                    {
                        desc: "关卡完成"   //描述
                    }
            }
        );

    }
    //记录阿拉丁事件
    public static AldEvent(eventName: string, key?: string, value?: string): void {
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            if (!key) key = "用户id";
            if (!value) {

                value = "";
                console.log(value);
            }
            Laya.Browser.window.wx.aldSendEvent(eventName, { key: value });
        }
    }
    public static Fail(stageId: string): void {
        if (!Main.IsWx) return;
        Laya.Browser.window.wx.aldStage.onEnd(
            {
                stageId: stageId,     //关卡ID 该字段必传
                stageName: "第" + stageId + "关", //关卡名称  该字段必传
                event: "fail",   //关卡完成  关卡进行中，用户触发的操作    该字段必传
                params:
                    {
                        desc: "关卡失败",
                    }
            }
        );

    }
    // public static leveleRuning(stageId: string, userid: string, eventtype: number, itemName: string) {
    //     if (Laya.Browser.window && Laya.Browser.window.wx) {
    //         //Laya.Browser.window.wx.aldStage.onRunning({"stageId":stageId,"stageName":stageName,"userId":userid});
    //         var eventT = eventtype == 0 ? "award" : "revive";
    //         Laya.Browser.window.wx.aldStage.onRunning({
    //             stageId: stageId,
    //             stageName: "第" + stageId + "关",
    //             userId: userid,
    //             event: eventT,
    //             params: {
    //                 itemName: itemName,
    //             }
    //         })
    //     }
    // }

    public static Start(stageId: string): void {
        if (!Main.IsWx) return;
        Laya.Browser.window.wx.aldStage.onStart(
            {
                stageId: stageId,     //关卡ID 该字段必传
                stageName: "第" + stageId + "关", //关卡名称  该字段必传
            }
        );

    }




    public static Game_Share(callback: Function = null, channel: string = ""): void {
        if (!Main.IsWx) {
            return;
        }
        var url;
        var title;
        url = UserModel.Instance.CurModel.shareimage;
        title = UserModel.Instance.CurModel.sharetitle;
        console.log(url + "  " + title);

       
        if (channel != null) {
            // WeiXinSDK.AldEvent("用户分享");
        }
        var t: number;// = UserModel.Get_Instance.CurModel.HuoQu_ServerTime;
        var path = "";
        Laya.Browser.window.wx.aldShareAppMessage({
            title: title,
            imageUrl: url,
            query: "shareid=" + UserModel.Instance.CurModel.userid + "_" + "other" + "_" + t + "_" + Math.floor(9999 * Math.random()).toString(),
        });

        ShareModule.GoShare(callback);

    }
}