/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | approved 跳转改为 getRoleHome(data.role)，保存 role 到 globalData 和 Storage |
| 2026-03-23 | 审核流程增强 | 区分 rejected/disabled 状态展示；rejected 增加"重新申请"按钮跳转申请页预填 |
*/
// pages/no-permission/no-permission.ts
// 无权限页面 — 账号已禁用或申请被拒绝时展示

import { request } from "../../utils/request"
import { getRoleHome, syncVisibleTabs } from "../../utils/auth-guard"

Page({
  data: {
    statusBarHeight: 0,
    // CHANGE 2026-03-23 | 审核流程增强：区分 rejected 和 disabled
    userStatus: "disabled" as "disabled" | "rejected",
    latestApplication: null as null | {
      siteCode: string
      appliedRoleText: string
      phone: string
      employeeNumber: string | null
      reviewNote: string | null
      createdAt: string
    },
  },

  onLoad() {
    const { statusBarHeight = 0 } = wx.getWindowInfo()
    this.setData({ statusBarHeight })
  },

  onShow() {
    this._checkStatus()
  },

  /** 查询最新用户状态，非 disabled/rejected 时自动跳转 */
  async _checkStatus() {
    const token = wx.getStorageSync("token")
    if (!token) {
      wx.reLaunch({ url: "/pages/login/login" })
      return
    }
    try {
      const data = await request({
        url: "/api/xcx/me",
        method: "GET",
        needAuth: true,
      })
      const app = getApp<IAppOption>()
      app.globalData.authUser = {
        userId: data.userId,
        status: data.status,
        nickname: data.nickname,
        role: data.role || undefined,
      }
      wx.setStorageSync("userId", data.userId)
      wx.setStorageSync("userStatus", data.status)
      if (data.role) wx.setStorageSync("userRole", data.role)

      switch (data.status) {
        case "disabled":
          this.setData({ userStatus: "disabled", latestApplication: data.latestApplication || null })
          break
        case "rejected":
          this.setData({ userStatus: "rejected", latestApplication: data.latestApplication || null })
          break
        case "approved":
          syncVisibleTabs(data.role)
          // CHANGE 2026-03-24 | 防御：approved 但 role 为空时跳个人页，不跳登录页
          wx.reLaunch({ url: data.role ? getRoleHome(data.role) : '/pages/my-profile/my-profile' })
          break
        case "pending":
          wx.reLaunch({ url: "/pages/reviewing/reviewing" })
          break
        case "new":
          wx.reLaunch({ url: "/pages/apply/apply" })
          break
      }
    } catch {
      // 网络错误不阻塞
    }
  },

  /** 更换登录账号 */
  onSwitchAccount() {
    const app = getApp<IAppOption>()
    app.globalData.token = undefined
    app.globalData.refreshToken = undefined
    app.globalData.authUser = undefined
    wx.removeStorageSync("token")
    wx.removeStorageSync("refreshToken")
    wx.removeStorageSync("userId")
    wx.removeStorageSync("userStatus")
    wx.reLaunch({ url: "/pages/login/login" })
  },

  // CHANGE 2026-03-23 | 审核流程增强：rejected 用户重新申请（跳转申请页预填上次信息）
  onReapply() {
    const la = this.data.latestApplication
    if (la) {
      const params = [
        `siteCode=${encodeURIComponent(la.siteCode || "")}`,
        `role=${encodeURIComponent(la.appliedRoleText || "")}`,
        `phone=${encodeURIComponent(la.phone || "")}`,
        `employeeNumber=${encodeURIComponent(la.employeeNumber || "")}`,
      ].join("&")
      wx.reLaunch({ url: `/pages/apply/apply?${params}` })
    } else {
      wx.reLaunch({ url: "/pages/apply/apply" })
    }
  },
})
