/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | 登录成功后保存 role、syncVisibleTabs、按角色跳转 getRoleHome |
| 2026-03-28 | 登录落地页修复 | 修复权限改造后 login.ts 未同步：改为请求 /me 获取 permissions，用 syncPermissions + getPermissionHome 决定落地页 |
*/
import { request } from "../../utils/request"
import { API_BASE } from "../../utils/config"
import { syncPermissions, getPermissionHome } from "../../utils/auth-guard"

/** develop 环境使用 dev-login 跳过微信 code2Session */
const isDevMode = API_BASE.startsWith("http://127.0.0.1")

Page({
  data: {
    agreed: false,
    loading: false,
    /** 系统状态栏高度（px），用于自定义导航栏顶部偏移 */
    statusBarHeight: 20,
  },

  onLoad() {
    const windowInfo = wx.getWindowInfo()
    this.setData({ statusBarHeight: windowInfo.statusBarHeight || 20 })
  },

  onAgreeChange() {
    this.setData({ agreed: !this.data.agreed })
  },

  async onLogin() {
    if (!this.data.agreed) {
      wx.showToast({ title: "请先同意用户协议", icon: "none" })
      return
    }
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      let data: any

      if (isDevMode) {
        // 开发模式：直接调用 dev-login，无需 wx.login
        // 不传 status，让后端保留用户当前状态（首次创建默认 new）
        data = await request({
          url: "/api/xcx/dev-login",
          method: "POST",
          data: { openid: "dev_test_openid" },
          needAuth: false,
        })
      } else {
        // 正式/体验：走微信 code2Session 流程
        const loginRes = await new Promise<WechatMiniprogram.LoginSuccessCallbackResult>(
          (resolve, reject) => {
            wx.login({
              success: resolve,
              fail: reject,
            })
          },
        )

        data = await request({
          url: "/api/xcx/login",
          method: "POST",
          data: { code: loginRes.code },
          needAuth: false,
        })
      }

      const app = getApp<IAppOption>()
      app.globalData.token = data.accessToken
      app.globalData.refreshToken = data.refreshToken
      wx.setStorageSync("token", data.accessToken)
      wx.setStorageSync("refreshToken", data.refreshToken)

      // 持久化用户身份信息
      // CHANGE 2026-03-23 | 角色路由：保存 role 并按角色跳转
      // CHANGE 2026-03-23 | camelCase 修复：后端 CamelModel 序列化输出 camelCase
      app.globalData.authUser = {
        userId: data.userId,
        status: data.userStatus,
        role: data.role || undefined,
      }
      wx.setStorageSync("userId", data.userId)
      wx.setStorageSync("userStatus", data.userStatus)
      if (data.role) wx.setStorageSync("userRole", data.role)

      // 根据 userStatus 路由
      switch (data.userStatus) {
        case "approved": {
          // CHANGE 2026-03-28 | 权限码驱动跳转：登录接口不返回 permissions，
          // 需额外请求 /api/xcx/me 获取权限码，再决定落地页
          let homePage = '/pages/my-profile/my-profile'
          try {
            const me = await request({ url: "/api/xcx/me", method: "GET", needAuth: true })
            const permissions: string[] = me.permissions || []
            syncPermissions(permissions)
            homePage = getPermissionHome(permissions)
          } catch {
            // /me 失败时降级到个人页，checkAuthStatus 后续会补偿
          }
          wx.reLaunch({ url: homePage })
          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.reLaunch({ url: "/pages/no-permission/no-permission" })
          break
        default:
          wx.reLaunch({ url: "/pages/apply/apply" })
          break
      }
    } catch (err: any) {
      const msg =
        err?.statusCode === 403
          ? "账号已被禁用"
          : err?.statusCode === 401
            ? "登录凭证无效，请重试"
            : "登录失败，请稍后重试"
      wx.showToast({ title: msg, icon: "none" })
    } finally {
      this.setData({ loading: false })
    }
  },
})
