// app.ts
import { startSSE, stopSSE } from './utils/server-sent-events'
import { checkUpdate } from './utils/updateManager'

// @ts-ignore
const systemInfo = wx.getWindowInfo();

// 登录相关 storage key 常量
const LOGIN_KEYS = ["mbuId", "userName", "openId", "unionId", "addressId", "defualtAddress"] as const;

export { };

App<IAppOption>({
    globalData: {
        isLogin: false,
        wasLogin: false,
        safeBottom: systemInfo.safeArea.bottom - systemInfo.safeArea.height,
        safeTop: systemInfo.safeArea.top * 2,
        store: {},
        joinedArray: [],
        template: null,
        showStock: false,
        tabbarMap: {},
        tabbarItems: [],
        sseStore: {
            chat: [],
            system: [],
            product: []
        },
        isModalShowing: false,
    },
    async onLaunch(props: any) {
        // 处理 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) {
            // 清理登录相关数据
            LOGIN_KEYS.forEach(key => wx.removeStorageSync(key));
        }

        // 保存上一次的登录状态，用来判断是否从 已登录 变成 未登录
        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;
    },
    getPageParams() {
        return this.globalData.store;
    },
    async getTemplate() {
        return this.globalData.template;
    },
    redirectLogin() {
        if (!this.checkLoginState()) {
            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;
    }
});