import { request } from "../../utils/request"
import { API_BASE } from "../../utils/config"

/** 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.access_token
      app.globalData.refreshToken = data.refresh_token
      wx.setStorageSync("token", data.access_token)
      wx.setStorageSync("refreshToken", data.refresh_token)

      // 持久化用户身份信息
      app.globalData.authUser = {
        userId: data.user_id,
        status: data.user_status,
      }
      wx.setStorageSync("userId", data.user_id)
      wx.setStorageSync("userStatus", data.user_status)

      // 根据 user_status 路由
      switch (data.user_status) {
        case "approved":
          wx.reLaunch({ url: "/pages/task-list/task-list" })
          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 })
    }
  },
})
