// app.ts
import { startSSE, stopSSE } from './utils/server-sent-events'
import { checkUpdate } from './utils/updateManager'
import { BASE_URL } from './env'
// @ts-ignore
const systemInfo = wx.getWindowInfo();

// 域名包含 .test. 则为测试环境，不拦截登录
const isTestDomain = (): boolean => BASE_URL.includes('.test.');

// 判断是否在 PC/Windows 环境运行
const isPCEnvironment = (): boolean => {
    const sysInfo = wx.getSystemInfoSync();
    return ['windows', 'mac'].includes(sysInfo.platform);
};
export { };
App<IAppOption>({
    globalData: {
        isLogin: false, //
        wasLogin: false, // 之前是否登录过，用来判断是不是 登录状态失效
        safeBottom: systemInfo.safeArea.bottom - systemInfo.safeArea.height,
        safeTop: systemInfo.safeArea.top * 2,
        store: {},
        joinedArray: [], //加入的频道，加入了就不会重复加入
        sseStore: {
            chat: [],
            system: [],
            product: []
        },
        isModalShowing: false,  //防止有多个登录弹窗打开
    },
    async onLaunch(props: any) {
        // 非测试环境在 PC 端打开时提示无法使用
        if (!isTestDomain() && isPCEnvironment()) {
            wx.showModal({
                title: "提示",
                content: "该环境无法使用",
                showCancel: false,
                confirmText: "我知道了"
            });
            return;
        }

        wx.removeStorageSync("state");
        if (props.query.state) {
            wx.setStorageSync("state", props.query.state)
        } else {
            wx.removeStorageSync("state")
        }
        // 检查小程序版本更新
        checkUpdate();

        this.checkLoginState();
        startSSE();
    },
    onHide() {
        stopSSE();
    },
    checkLoginState() {
        const openId = wx.getStorageSync("openId");
        const unionId = wx.getStorageSync("unionId");
        const userId = wx.getStorageSync("userId");

        const ok = openId && unionId && userId;

        if (!ok) {
            // 清理
            wx.removeStorageSync("mbuId");
            wx.removeStorageSync("userName");
            wx.removeStorageSync("openId");
            wx.removeStorageSync("unionId");
            wx.removeStorageSync("addressId");
            wx.removeStorageSync("defualtAddress");
        }

        // 保存上一次的登录状态，用来判断是否从 已登录 变成 未登录
        const prev = this.globalData.isLogin;
        this.globalData.isLogin = !!ok;
        this.globalData.wasLogin = prev;
        return this.globalData.isLogin;
    },
    login(value: string) {
        if (!this.checkLoginState()) {
            wx.reLaunch({ url: `/pages/login/login?back=${value}` });
            return false;
        }
        return true;
    },
    redirectLogin() {
        if (!this.checkLoginState()) {
            //已有modal在展示，就不展示了
            if (this.globalData.isModalShowing) {
                return false;
            }

            this.globalData.isModalShowing = true;

            const content = this.globalData.wasLogin
                ? "登录状态失效,请重新登录!"
                : "请登录获取完整服务！";

            wx.showModal({
                title: "登录提示",
                content,
                confirmText: "去登录",
                success: (options) => {
                    if (options.confirm) {
                        wx.navigateTo({ url: "/pages/login/login" });
                    }
                },
                complete: () => {
                    this.globalData.isModalShowing = false;
                }
            });

            return false;
        }

        return true;
    }
});
