/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | approved 跳转改为 getRoleHome(data.role)，保存 role 到 globalData 和 Storage |
| 2026-03-23 | 审核流程增强 | 进度卡片展示提交信息；底部改为"更换登录账号"+"重新申请"双按钮；重新申请取消当前申请并跳转申请页预填 |
*/
import { request } from "../../utils/request"
import { getRoleHome, syncVisibleTabs } from "../../utils/auth-guard"

Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    status: "pending" as "pending" | "rejected",
    application: null as null | {
      id: number
      siteCode: string
      appliedRoleText: string
      phone: string
      employeeNumber: string | null
      status: string
      reviewNote: string | null
      createdAt: string
    },
    cancelling: false,
  },

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

  onShow() {
    this.fetchStatus()
  },

  onPullDownRefresh() {
    this.fetchStatus().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  async fetchStatus() {
    try {
      const data = await request({
        url: "/api/xcx/me",
        method: "GET",
        needAuth: true,
      })

      // CHANGE 2026-03-23 | 角色路由：保存 role 并按角色跳转
      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)

      // 已通过 → 按角色跳转首页
      if (data.status === "approved") {
        syncVisibleTabs(data.role)
        // CHANGE 2026-03-24 | 防御：approved 但 role 为空时跳个人页，不跳登录页
        const home = data.role ? getRoleHome(data.role) : '/pages/my-profile/my-profile'
        wx.reLaunch({ url: home })
        return
      }

      // 已禁用 → 跳转无权限页
      if (data.status === "disabled") {
        wx.reLaunch({ url: "/pages/no-permission/no-permission" })
        return
      }

      // 已拒绝 → 跳转无权限页
      if (data.status === "rejected") {
        wx.reLaunch({ url: "/pages/no-permission/no-permission" })
        return
      }

      // 全新用户（尚未提交申请）→ 跳回申请页
      if (data.status === "new") {
        wx.reLaunch({ url: "/pages/apply/apply" })
        return
      }

      this.setData({
        loading: false,
        status: data.status,
        application: data.latestApplication
          ? {
              ...data.latestApplication,
              // 提交时间只显示到分钟：2026-03-23 01:33
              createdAt: data.latestApplication.createdAt
                ? data.latestApplication.createdAt.replace(/T/, " ").replace(/:\d{2}(\.\d+)?([\+\-].*|Z)?$/, "")
                : "",
            }
          : null,
      })
    } catch (err: any) {
      this.setData({ loading: false })
      wx.showToast({ title: "获取状态失败", icon: "none" })
    }
  },

  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 | 审核流程增强：重新申请（取消当前 pending 申请 → 跳转申请页预填）
  async onReapply() {
    if (this.data.cancelling) return
    this.setData({ cancelling: true })

    try {
      const result = await request({
        url: "/api/xcx/cancel-application",
        method: "POST",
        needAuth: true,
      })

      // 跳转申请页，通过 URL 参数传递预填信息
      const params = [
        `siteCode=${encodeURIComponent(result.siteCode || "")}`,
        `role=${encodeURIComponent(result.appliedRoleText || "")}`,
        `phone=${encodeURIComponent(result.phone || "")}`,
        `employeeNumber=${encodeURIComponent(result.employeeNumber || "")}`,
      ].join("&")

      wx.reLaunch({ url: `/pages/apply/apply?${params}` })
    } catch (err: any) {
      const msg = err?.data?.detail || "取消申请失败，请稍后重试"
      wx.showToast({ title: msg, icon: "none" })
    } finally {
      this.setData({ cancelling: false })
    }
  },
})
