/** * 统一小程序入口 * 职责:初始化全局状态、从缓存恢复登录态、提供 checkLogin 和状态映射方法。 */ var auth = require("./utils/auth"); var request = require("./utils/request"); var status = require("./utils/status"); var subscribe = require("./utils/subscribe"); var ws = require("./utils/websocket"); App({ globalData: { apiBaseUrl: require("./config").apiBaseUrl, authToken: "", statusBarHeight: 0, navBarHeight: 0, userRole: "", }, // 事件处理器存储 _eventHandlers: {}, onLaunch: function () { var windowInfo = wx.getWindowInfo(); this.globalData.statusBarHeight = windowInfo.statusBarHeight || 20; this.globalData.navBarHeight = 44; var token = auth.getToken(); if (token) { this.globalData.authToken = token; this.globalData.userRole = auth.getUserRole(); this.loadSubscribeTemplateIds(); // 已登录则建立 WebSocket 连接 ws.connect(); } }, request: request, loadSubscribeTemplateIds: async function () { var configKeys = [ "wechat_template_order_status", "wechat_template_approval", "wechat_template_task_assigned", "wechat_template_logistics_timeout", "wechat_template_arrears", "wechat_template_inactive_customer", ]; try { var results = await Promise.all( configKeys.map(function (configKey) { return request({ url: "/api/configs/" + configKey, method: "GET" }); }) ); subscribe.applyConfigItems(results); } catch (error) { console.warn("[Subscribe] 加载模板 ID 失败,继续使用本地默认值:", error.message || error); } }, checkLogin: function () { if (!auth.isLoggedIn()) { wx.redirectTo({ url: "/pages/login/login" }); return false; } return true; }, /** * 注册事件监听 */ on: function (eventName, handler) { if (!this._eventHandlers[eventName]) { this._eventHandlers[eventName] = []; } this._eventHandlers[eventName].push(handler); }, /** * 移除事件监听 */ off: function (eventName, handler) { if (!this._eventHandlers[eventName]) return; if (handler) { this._eventHandlers[eventName] = this._eventHandlers[eventName].filter(function (h) { return h !== handler; }); } else { delete this._eventHandlers[eventName]; } }, /** * 建立 WebSocket 连接(登录后调用) */ connectWebSocket: function () { ws.connect(); }, /** * 断开 WebSocket 连接(登出时调用) */ disconnectWebSocket: function () { ws.disconnect(); }, mapTaskStatus: status.mapTaskStatus, mapOrderStatus: status.mapOrderStatus, });