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

Page({
  data: {
    statusBarHeight: 0,
    siteCode: "",
    role: "",
    phone: "",
    employeeNumber: "",
    nickname: "",
    submitting: false,
  },

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

  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>()
      app.globalData.authUser = {
        userId: data.user_id,
        status: data.status,
        nickname: data.nickname,
      }
      wx.setStorageSync("userId", data.user_id)
      wx.setStorageSync("userStatus", data.status)

      switch (data.status) {
        case "new":
          break
        case "rejected":
          wx.reLaunch({ url: "/pages/no-permission/no-permission" })
          break
        case "approved":
          wx.reLaunch({ url: "/pages/mvp/mvp" })
          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 })
  },

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

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

    if (!siteCode.trim()) {
      wx.showToast({ title: "请输入球房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 {
      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 })
    }
  },
})
