/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | checkAuthStatus 补完：保存 role、syncVisibleTabs、按状态路由（approved 留当前页由守卫处理、disabled 强制登出） |
| 2026-03-27 | 权限改造 W5 | 改用 syncPermissions 替代 syncVisibleTabs，从后端 permissions 驱动 tab 可见性 |
*/
// app.ts
// 应用入口 — 启动时检查登录状态并路由到对应页面
import { request } from "./utils/request"
import { syncPermissions, getPermissionHome, getVisibleTabs } from "./utils/auth-guard"

App<IAppOption>({
  globalData: {},

  onLaunch() {
    // 从 Storage 恢复 token 和用户信息
    const token = wx.getStorageSync("token")
    const refreshToken = wx.getStorageSync("refreshToken")
    const userId = wx.getStorageSync("userId")
    if (token) {
      this.globalData.token = token
      this.globalData.refreshToken = refreshToken
      if (userId) {
        this.globalData.authUser = {
          userId,
          status: wx.getStorageSync("userStatus") || "new",
          role: wx.getStorageSync("userRole") || undefined,
        }
        // onLaunch 阶段 getApp() 尚未就绪，直接用 this.globalData 设置
        // CHANGE 2026-03-27 | 权限码驱动：onLaunch 无 permissions，给默认空 tab
        this.globalData.permissions = []
        this.globalData.visibleTabs = ['my']
      }
      this.checkAuthStatus()
    }
  },

  /**
   * CHANGE 2026-03-22 | 竞态修复
   * CHANGE 2026-03-23 | 角色路由：按角色跳转不同首页
   */
  async checkAuthStatus() {
    const tokenAtStart = this.globalData.token
    try {
      const data = await request({
        url: "/api/xcx/me",
        method: "GET",
        needAuth: true,
      })
      if (this.globalData.token !== tokenAtStart) return

      // CHANGE 2026-03-23 | camelCase 修复：后端 CamelModel 序列化输出 camelCase
      this.globalData.authUser = {
        userId: data.userId,
        status: data.status,
        nickname: data.nickname,
        // CHANGE 2026-03-24 | 头像：保存 avatarUrl 到 globalData
        avatarUrl: data.avatarUrl || undefined,
        role: data.role || undefined,
      }
      wx.setStorageSync("userId", data.userId)
      wx.setStorageSync("userStatus", data.status)
      if (data.role) wx.setStorageSync("userRole", data.role)

      // CHANGE 2026-03-27 | 权限码驱动：同步权限和 tab 可见性
      const permissions: string[] = data.permissions || []
      syncPermissions(permissions)

      // 根据用户状态路由
      switch (data.status) {
        case "approved":
          // 已通过 — 不跳转，用户留在当前页面（由页面守卫处理权限）
          break
        case "pending":
          wx.reLaunch({ url: "/pages/reviewing/reviewing" })
          break
        case "new":
          wx.reLaunch({ url: "/pages/apply/apply" })
          break
        case "rejected":
          wx.reLaunch({ url: "/pages/no-permission/no-permission" })
          break
        case "disabled":
          // 强制登出
          wx.removeStorageSync("token")
          wx.removeStorageSync("refreshToken")
          this.globalData.token = undefined
          this.globalData.refreshToken = undefined
          wx.reLaunch({ url: "/pages/login/login" })
          break
      }
    } catch {
      // 网络错误不阻塞（401 由 request.ts 拦截处理）
    }
  },
})
