/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | approved 跳转改为 getRoleHome(data.role)，保存 role 到 globalData 和 Storage |
| 2026-03-23 | 审核流程增强 | onLoad 支持 URL 参数预填（重新申请场景）；rejected 用户留在申请页而非跳走 |
| 2026-03-24 | 头像昵称获取 | 新增 chooseAvatar 头像选择 + wx.uploadFile 上传；昵称 input type=nickname |
*/
import { request } from "../../utils/request"
import { getRoleHome, syncVisibleTabs } from "../../utils/auth-guard"
// CHANGE 2026-03-24 | 头像上传：需要 API_BASE 构建上传 URL
import { API_BASE } from "../../utils/config"

Page({
  data: {
    statusBarHeight: 0,
    siteCode: "",
    role: "",
    phone: "",
    employeeNumber: "",
    nickname: "",
    submitting: false,
    // CHANGE 2026-03-24 | 头像：chooseAvatar 临时路径（用于预览和上传）
    avatarTempPath: "",
    avatarUploaded: false,
  },

  onLoad(options?: Record<string, string>) {
    const { statusBarHeight } = wx.getWindowInfo()
    this.setData({ statusBarHeight })

    // CHANGE 2026-03-23 | 审核流程增强：支持从重新申请跳转时预填上次信息
    if (options) {
      const prefill: Record<string, string> = {}
      if (options.siteCode) prefill.siteCode = decodeURIComponent(options.siteCode)
      if (options.role) prefill.role = decodeURIComponent(options.role)
      if (options.phone) prefill.phone = decodeURIComponent(options.phone)
      if (options.employeeNumber) prefill.employeeNumber = decodeURIComponent(options.employeeNumber)
      if (Object.keys(prefill).length > 0) {
        this.setData(prefill)
      }
    }
  },

  onShow() {
    this._checkAccess()
  },

  /** 校验用户身份：无 token 跳登录，非 new/rejected 跳对应页 */
  async _checkAccess() {
    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>()
      // CHANGE 2026-03-23 | 角色路由：保存 role 并按角色跳转
      // CHANGE 2026-03-23 | camelCase 修复：后端 CamelModel 序列化输出 camelCase
      app.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)

      switch (data.status) {
        case "new":
        case "rejected":
          // 允许 new 和 rejected 用户留在申请页填表
          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 "disabled":
          wx.reLaunch({ url: "/pages/no-permission/no-permission" })
          break
      }
    } catch {
      // 网络错误不阻塞，允许用户继续填表
    }
  },

  onBack() {
    wx.navigateBack({ fail: () => wx.reLaunch({ url: "/pages/login/login" }) })
  },

  /* 原生 input 的 bindinput 事件 */
  onSiteCodeInput(e: WechatMiniprogram.Input) {
    this.setData({ siteCode: e.detail.value })
  },

  onRoleInput(e: WechatMiniprogram.Input) {
    this.setData({ role: e.detail.value })
  },

  onPhoneInput(e: WechatMiniprogram.Input) {
    this.setData({ phone: e.detail.value })
  },

  onEmployeeNumberInput(e: WechatMiniprogram.Input) {
    this.setData({ employeeNumber: e.detail.value })
  },

  onNicknameInput(e: WechatMiniprogram.Input) {
    this.setData({ nickname: e.detail.value })
  },

  // CHANGE 2026-03-24 | 头像：chooseAvatar 回调，保存临时路径
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    if (avatarUrl) {
      this.setData({ avatarTempPath: avatarUrl, avatarUploaded: false })
    }
  },

  /**
   * CHANGE 2026-03-24 | 头像上传：wx.uploadFile 将临时文件上传到后端
   * chooseAvatar 返回的是临时路径（http://tmp/xxx.jpeg），必须上传持久化
   * CHANGE 2026-03-24 | bug 修复：添加详细错误日志，修复 statusCode 类型比较
   */
  _uploadAvatar(): Promise<boolean> {
    const { avatarTempPath } = this.data
    if (!avatarTempPath) return Promise.resolve(true) // 无头像不阻塞提交
    if (this.data.avatarUploaded) return Promise.resolve(true)

    const token = wx.getStorageSync("token")
    const uploadUrl = `${API_BASE}/api/xcx/avatar/upload`
    console.log("[avatar] 开始上传", { uploadUrl, filePath: avatarTempPath })

    return new Promise((resolve) => {
      wx.uploadFile({
        url: uploadUrl,
        filePath: avatarTempPath,
        name: "file",
        header: { Authorization: `Bearer ${token}` },
        success: (res) => {
          console.log("[avatar] 上传响应", { statusCode: res.statusCode, data: res.data })
          // CHANGE 2026-03-24 | statusCode 可能是 number 或 string，统一用 == 比较
          if (res.statusCode == 200) {
            this.setData({ avatarUploaded: true })
            resolve(true)
          } else {
            let detail = "头像上传失败"
            try {
              const body = JSON.parse(res.data)
              if (body.detail) detail = body.detail
            } catch { /* 忽略解析失败 */ }
            wx.showToast({ title: detail, icon: "none" })
            resolve(false)
          }
        },
        fail: (err) => {
          console.error("[avatar] 上传失败", err)
          wx.showToast({ title: "头像上传失败，请检查网络", icon: "none" })
          resolve(false)
        },
      })
    })
  },

  async onSubmit() {
    if (this.data.submitting) return

    const { siteCode, role, phone, nickname, employeeNumber } = this.data

    // CHANGE 2026-03-23 | 球房ID 改为 6 位字母/数字
    if (!/^[A-Za-z0-9]{6}$/.test(siteCode.trim())) {
      wx.showToast({ title: "请输入6位球房ID", icon: "none" })
      return
    }
    if (!role.trim()) {
      wx.showToast({ title: "请输入申请身份", icon: "none" })
      return
    }
    if (!/^\d{11}$/.test(phone)) {
      wx.showToast({ title: "请输入11位手机号", icon: "none" })
      return
    }
    if (!nickname.trim()) {
      wx.showToast({ title: "请输入昵称", icon: "none" })
      return
    }

    this.setData({ submitting: true })

    try {
      // CHANGE 2026-03-24 | 头像：提交前先上传头像（如有）
      if (this.data.avatarTempPath && !this.data.avatarUploaded) {
        const uploaded = await this._uploadAvatar()
        if (!uploaded) {
          this.setData({ submitting: false })
          return
        }
      }

      await request({
        url: "/api/xcx/apply",
        method: "POST",
        data: {
          site_code: siteCode.trim(),
          applied_role_text: role.trim(),
          phone,
          employee_number: employeeNumber.trim() || undefined,
          nickname: nickname.trim(),
        },
        needAuth: true,
      })

      wx.showToast({ title: "申请已提交", icon: "success" })
      setTimeout(() => {
        wx.reLaunch({ url: "/pages/reviewing/reviewing" })
      }, 800)
    } catch (err: any) {
      const msg =
        err?.data?.detail ||
        (err?.statusCode === 409
          ? "您已有待审核的申请"
          : err?.statusCode === 422
            ? "表单信息有误，请检查"
            : "提交失败，请稍后重试")
      wx.showToast({ title: msg, icon: "none" })
    } finally {
      this.setData({ submitting: false })
    }
  },
})
