
import { ShareModule } from "./ShareModule";
import UserModel from "./UserModel";

import { SettingController } from "../GameLogic/SettingController";
import { AppSetting } from "../GameLogic/AssetManager";
import NetManager, { PROTOCOLS } from "./NetManager";
import GameTool from "../Util/GameTool";
import GameSetting from "./GameSetting";
import ViewManager from "./ViewManager";
export enum ALDType {
    登录加载,
    界面开启
}
export class WXSdk {
    public static Lodining: boolean = false;

    private static shareId = "";
    private static _chanel: string = "";

    public static isAuth = false;
    static get ShareId() {
        return this.shareId;
    }
    static get Chanel() {
        return this._chanel;
    }
    public static init(cb?: any) {
        this.EventStatistics();
        Laya.Browser.window.wx.showShareMenu({
            withShareTicket: true
        });
        Laya.Browser.window.wx.onShow(this.InitWx);
    }
    private static InitWx(option) {
        var shareid = option.query.share_id;
        this.shareId = shareid ? shareid : "";

        GameSetting.wxValue = option.scene;
        var scene = Laya.LocalStorage.getItem("scene");
        if (scene) {
            GameSetting.wxValue = scene;
            console.log("读取配置场景值:" + scene);
        } else {
            console.log("第一次拉取场景值:" + GameSetting.wxValue);
            Laya.LocalStorage.setItem("scene", GameSetting.wxValue)
        }
        var channel: string = option.query.channel;
        this._chanel = channel ? channel : "";
        Laya.Browser.window.wx.offShow(WXSdk.InitWx);
    }

    public static ShareMessage() {
        if (!GameSetting.isWx) return;
        var t: number = UserModel.Instance.CurModel.ServerTime;
        var _title;
        var _url;
        _title = AppSetting.sharetitle;
        _url = AppSetting.shareimage;

        if (_title == null) {
            _title = "枪王之王...";
            _url = "res/share.png"
        }
        else {
            let a = GameTool.SpliteString(_title);
            let b = GameTool.SpliteString(_url);
            _title = a[GameTool.randomInt(0, a.length - 1)];
            _url = b[GameTool.randomInt(0, b.length - 1)];
        }
        console.log("_title:", _title)
        console.log("_url:", _url)
        Laya.Browser.window.wx.onShareAppMessage(() => ({
            title: _title,
            imageUrl: _url,
            query: "share_id=" + UserModel.Instance.CurModel.m_userid + "_other_" + t + "_" + Math.floor(9999 * Math.random()).toString()
        }));
    }


    public static Login(cb: Function) {
        if (WXSdk.Lodining) {
            return;
        }
        WXSdk.Lodining = true;
        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"); }
        });
    }

    //显示加载信息
    public static ShowLoading(title: string = "加载中...", isShowWx = true) {
        console.log(title);
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            if (isShowWx) {
                Laya.Browser.window.wx.showLoading({ title: title, mask: true });
            }
            ViewManager.Instance.OpenMask();
        } else {
            ViewManager.Instance.OpenMask();
        }
    }
    public static HideLoading(isShowWx = true) {
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            if (isShowWx) {
                Laya.Browser.window.wx.hideLoading();
            }
            ViewManager.Instance.CloseMask();
        } else {
            ViewManager.Instance.CloseMask();
        }
    }
    private static sysdata: any;
    public static SystemInfo() {
        if (Laya.Browser.window.wx) {
            if (!WXSdk.sysdata) WXSdk.sysdata = Laya.Browser.window.wx.getSystemInfoSync();
            return WXSdk.sysdata;
        }
    }

    // 显示提示信息//
    public static ShowToast(text?: string, icon = true) {
        if (Laya.Browser.window.wx) {
            var t_icon = icon ? "success" : "none";
            text = text ? text : "暂未开放...";
            Laya.Browser.window.wx.showToast({ title: text, icon: t_icon });
        }
        else {
            console.log(text);
        }
    }

    private static vibrating = false;
    public static ShortVibrate(): void {
        if (Laya.Browser.window.wx && SettingController.Instance.vibrate) {
            if (WXSdk.vibrating) return;
            WXSdk.vibrating = true;
            Laya.Browser.window.wx.vibrateShort({
                complete: function (res) {
                    WXSdk.vibrating = false;
                }
            });
        }
    }

    public static LongVibrate(): void {
        if (Laya.Browser.window.wx && SettingController.Instance.vibrate) {
            if (WXSdk.vibrating) return;
            WXSdk.vibrating = true;
            Laya.Browser.window.wx.vibrateLong({
                complete: function (res) {
                    WXSdk.vibrating = false;
                }
            });
        }
    }

    public static Success(stageId: string): void {
        if (!GameSetting.isWx) return;
        Laya.Browser.window.wx.aldStage.onEnd(
            {
                stageId: stageId,     //关卡ID 该字段必传
                stageName: "第" + stageId + "关", //关卡名称  该字段必传
                event: "complete",   //关卡完成  关卡进行中，用户触发的操作    该字段必传
                params:
                    {
                        desc: "关卡完成"   //描述
                    }
            }
        );

    }
    // //记录阿拉丁事件
    public static AldEvent(eventName: string,a?): void {
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            // var t = "";
            //     if (this.IsNew == 1) {
            //         t = "新用户:";
            //         eventName = t + eventName;
            //         Laya.Browser.window.wx.aldSendEvent(eventName, { key: "" });
            //     } else {
            //         if(AppSetting.aldType==2){
            //           //  t = "新用户:";
            //             eventName = t + eventName;
                        Laya.Browser.window.wx.aldSendEvent(eventName, { key: "" });
                //     }else{
                //     }
                // }
        }
    }

    //记录阿拉丁事件
 //   public static AldEvent(eventName: ALDType, value?): void {
        // return;
        // let name;
        // if (GameSetting.isWx) {
        //     name = ALDType[eventName];
        //     if (this.IsNew == 1) {
        //         Laya.Browser.window.wx.aldSendEvent(name, { "新用户": value });
        //     } else {
        //         Laya.Browser.window.wx.aldSendEvent(name, { "老用户": value });
        //     }
        // }
   // }
    private static IsNew = 0;
    public static EventStatistics() {
        let uuid = Laya.LocalStorage.getItem("uuidTimes");
        let is_new;
        if (uuid) {
            let lastSignTime = new Date(Number(uuid));
            let todayZero = new Date(Laya.timer.currTimer);
            todayZero.setHours(0, 0, 0, 0);
            if (lastSignTime.valueOf() < todayZero.valueOf()) {
                this.IsNew = 0;
            } else {
                this.IsNew = 1;
            }
        } else {
            this.IsNew = 1;
            Laya.LocalStorage.setItem("uuidTimes", Laya.timer.currTimer.toString());
        }
    }
    public static Fail(stageId: string): void {
        if (!GameSetting.isWx) return;
        Laya.Browser.window.wx.aldStage.onEnd(
            {
                stageId: stageId,     //关卡ID 该字段必传
                stageName: "第" + stageId + "关", //关卡名称  该字段必传
                event: "fail",   //关卡完成  关卡进行中，用户触发的操作    该字段必传
                params:
                    {
                        desc: "关卡失败",
                    }
            }
        );

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

    }




    public static Game_Share(callback: Function = null, channel: string = ""): void {
        if (!GameSetting.isWx) {
            return;
        }


        var _title;
        var _url;
        _title = AppSetting.sharetitle;
        _url = AppSetting.shareimage;

        if (_title == null) {
            _title = "枪王之王..."
            _url = "res/share.png"
        } else {
            let a = GameTool.SpliteString(_title);
            let b = GameTool.SpliteString(_url);
            _title = a[GameTool.randomInt(0, a.length - 1)];
            _url = b[GameTool.randomInt(0, b.length - 1)];
        }
        console.log("_title:", _title)
        console.log("_url:", _url)
        var t: number = UserModel.Instance.CurModel.ServerTime;

        // Laya.Browser.window.wx.aldShareAppMessage({
        //     title: _title,
        //     imageUrl: _url,
        //     query: "share_id=" + UserModel.Instance.CurModel.m_userid + "_" + "other" + "_" + t + "_" + Math.floor(9999 * Math.random()).toString(),
        // });
        Laya.Browser.window.wx.shareAppMessage({
            title: _title,
            imageUrl: _url,
            query: "share_id=" + UserModel.Instance.CurModel.m_userid + "_" + "other" + "_" + t + "_" + Math.floor(9999 * Math.random()).toString(),
        });

        ShareModule.GoShare(callback);
    }

    public static LoadSubPackage(name, callback?) {
        if (GameSetting.isWx) {
            const loadTask = Laya.Browser.window.wx.loadSubpackage({
                name: name, // name 可以填 name 或者 root
                success(res) {
                    console.log("分包下载成功:", res);
                    if (callback) callback(true);
                },
                fail(res) {
                    console.log("分包下载失败:" + JSON.stringify(res));
                    if (callback) callback(false);
                }
            });
        } else {
            if (callback) callback(true);
        }
    }
    public static IsNeedUpdate() {
        if (!GameSetting.isWx) return false;
        const updateManager = Laya.Browser.window.wx.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {
            console.log("最新版本:" + res.hasUpdate);
        }
        );
        updateManager.onUpdateReady(function () {
            //GameSetting.isUpdate = true;
            Laya.Browser.window.wx.showModal({
                showCancel: false,
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    updateManager.applyUpdate();
                },
                fail(res?) {
                    updateManager.applyUpdate();
                }
            });
        });
    }
    public static IsAuth(): void {
        if (Laya.Browser.window && Laya.Browser.window.wx) {
            Laya.Browser.window.wx.getSetting({
                success: (res) => {
                    console.log("授权结果..")
                    console.log(res)
                    if (res.authSetting['scope.userInfo'] == true) {
                        WXSdk.isAuth = true;
                        Laya.Browser.window.wx.getUserInfo({
                            lang: 'zh_CN',
                            success: (res) => {
                                UserModel.Instance.CurModel.m_nickname = res.userInfo.nickName;
                                UserModel.Instance.CurModel.m_avatar = res.userInfo.avatarUrl;
                                console.log("已经受过权");
                            },
                            fail: () => {
                                console.log('调用getUserInfo fail');
                            }
                        });
                    }
                }
            })
        }
    }

    public static RequestAuth(callback: Function) {
        if (WXSdk.isAuth) {
            if (callback != null) {
                callback(true);
            }
            return;
        }
        if (GameSetting.isWx) {
            console.log("-----授权")
            let openAuthView = () => {
                let w = Laya.stage.width;
                let h = Laya.stage.height;
                console.log("准备授权")
                let button = Laya.Browser.window.wx.createUserInfoButton({
                    type: 'text', //text  image 
                    text: '',
                    style: {
                        left: 0,
                        top: 0,
                        width: w,
                        height: h,
                        lineHeight: 40,
                        backgroundColor: '#00000000',
                        textAlign: 'center',
                        fontSize: 16,
                        borderRadius: 4
                    }
                });

                let opTapHandler = (res) => {
                    console.log("res:" + JSON.stringify(res));
                    if (res.userInfo) {
                        button.hide();
                        button.offTap(opTapHandler);
                        button.destroy();
                        console.log("userinfo", res);
                        UserModel.Instance.CurModel.m_nickname = res.userInfo.nickName;
                        UserModel.Instance.CurModel.m_avatar = res.userInfo.avatarUrl;
                        let param = [{ "nickname": res.userInfo.nickName }, { "avatar": res.userInfo.avatarUrl }, { "gender": res.userInfo.gender }, { "city": res.userInfo.city },
                        { "country": res.userInfo.country }, { "province": res.userInfo.province }];
                        NetManager.Instance.HttpPostRequest(PROTOCOLS.protocols.Userauth, param, () => {
                            WXSdk.isAuth = true;
                            if (callback != null) {
                                callback(true);
                            }
                        }, null);

                    } else {
                        button.hide();
                        button.offTap(opTapHandler);
                        button.destroy();
                        //TODO
                        if (callback != null) {
                            callback(false);
                        }
                    }
                }
                button.show();
                button.onTap(opTapHandler);
            }
            openAuthView();
        }
        else {
            WXSdk.isAuth = true;
            if (callback != null) {
                callback(true);
            }
        }
    }

    private static button;
    public static showbjWxGameQuan(flag: boolean): void {
        if (!GameSetting.isWx) {
            return;
        }
        if (flag) {
            if (this.button == null) {
                let info = Laya.Browser.window.wx.getSystemInfoSync();
                if (!info) return;
                var top = 0.5 * info.windowHeight// / Laya.stage.height;
                var height = 109 * info.windowHeight / Laya.stage.height;        //109  
                var width = height * 80 / 109;
                Laya.stage.width                                          //80
                this.button = Laya.Browser.window.wx.createGameClubButton
                    ({
                        type: "image",
                        image: 'res/talk.png',
                        style:
                            {
                                //right: 0,
                                left: info.windowWidth * 0.5 + 150 * info.windowWidth / Laya.stage.width,  //160
                                top: top - 240 * info.windowHeight / Laya.stage.height,  //200
                                width: width,
                                height: height
                            }
                    })

            }
            this.button.show();
        }
        else {
            if (this.button) {
                this.button.hide();
            }
        }

    }
}