// pages/verify/verify.js
import { createPage, request } from '../../utils/base-page.js'
import { enterLockedRole } from '../../utils/primary-role.js'
import { isStaffMode, restoreStaffContextAfterAuth } from '../../utils/staff-api.js'

const API_MAP = {
  dashou:    '/yonghu/dashouzhuce',
  shangjia:  '/yonghu/shangjiahuce',
  guanshi:   '/yonghu/guanshizhuce',
  zuzhang:   '/yonghu/zuzhangzhuce',
  kaoheguan: '/dengji/khgzc'
}

const STATUS_KEY_MAP = {
  dashou:    'dashoustatus',
  shangjia:  'shangjiastatus',
  guanshi:   'guanshistatus',
  zuzhang:   'zuzhangstatus',
  kaoheguan: 'kaoheguanstatus'
}

const NAME_MAP = {
  dashou:    '接单员',
  shangjia:  '商家',
  guanshi:   '管事',
  zuzhang:   '组长',
  kaoheguan: '考核官'
}

Page(createPage({
  data: {
    authType: '',
    authName: '',
    pageState: 'need_register',
    inviteCode: '',
    isLoading: false,
  },

  onLoad(options) {
    const type = options.type || ''
    if (!API_MAP[type]) {
      wx.showToast({ title: '认证类型错误', icon: 'none' })
      setTimeout(() => wx.navigateBack(), 1500)
      return
    }
    this.setData({ authType: type, authName: NAME_MAP[type] })
    this.checkStatus()
  },

  async onShow() {
    if (this.data.authType) {
      if (this.data.authType === 'shangjia' && wx.getStorageSync('token')) {
        await restoreStaffContextAfterAuth();
        if (isStaffMode()) {
          enterLockedRole('shangjia', getApp());
          return;
        }
      }
      this.checkStatus();
    }
  },

  checkStatus() {
    const key = STATUS_KEY_MAP[this.data.authType]
    const val = wx.getStorageSync(key)
    if (val === 1) {
      this.setData({ pageState: 'done' })
    } else {
      this.setData({ pageState: 'need_register' })
    }
  },

  onInviteCodeInput(e) {
    this.setData({ inviteCode: e.detail.value.trim() })
  },

  async onRegister() {
    const { inviteCode, authType } = this.data
    if (!inviteCode) {
      wx.showToast({ title: '请输入邀请码', icon: 'none' })
      return
    }
    if (inviteCode.length > 100) {
      wx.showToast({ title: '邀请码不能超过100字符', icon: 'none' })
      return
    }

    this.setData({ isLoading: true })
    wx.showLoading({ title: '注册中...', mask: true })

    try {
      const res = await request({
        url: API_MAP[authType],
        method: 'POST',
        data: { inviteCode }
      })

      if (res && res.data.code === 200) {
        const data = res.data.data || res.data
        const app = getApp()

        // 缓存身份状态
        const key = STATUS_KEY_MAP[authType]
        if (data[key] !== undefined) {
          wx.setStorageSync(key, data[key])
          app.globalData[key] = data[key]
        } else {
          wx.setStorageSync(key, 1)
          app.globalData[key] = 1
        }

        // 更新其他可能返回的身份状态字段
        const allKeys = ['dashoustatus', 'shangjiastatus', 'guanshistatus', 'zuzhangstatus', 'kaoheguanstatus']
        allKeys.forEach(k => {
          if (data[k] !== undefined && k !== key) {
            wx.setStorageSync(k, data[k])
            app.globalData[k] = data[k]
          }
        })

        // 保存各身份详细信息
        if (authType === 'dashou') {
          const fields = ['dashounicheng','zhanghaostatus','yongjin','zonge','yajin','chenghao','jifen','clumber','chengjiaoliang','zaixianzhuangtai']
          fields.forEach(f => { if (data[f] !== undefined) app.globalData[f] = data[f] })
        } else if (authType === 'shangjia') {
          app.globalData.shangjia = app.globalData.shangjia || {}
          const sf = ['nicheng','sjyue','fabu','chengjiao','tuikuan','jinridingdan','jinriliushui','jinyuedingdan','jinyueliushui','zhuangtai']
          sf.forEach(f => { if (data[f] !== undefined) app.globalData.shangjia[f] = data[f] })
        } else if (authType === 'guanshi') {
          app.globalData.guanshi = app.globalData.guanshi || {}
          const gf = ['gszhstatus','yaoqingzongshu','fenyongzonge','fenyongtixian','yichongzhiDashou']
          gf.forEach(f => { if (data[f] !== undefined) app.globalData.guanshi[f] = data[f] })
        } else if (authType === 'zuzhang') {
          const zf = ['ketixian','guanshiCount','fenhongZonge']
          zf.forEach(f => { if (data[f] !== undefined) app.globalData[f] = data[f] })
        } else if (authType === 'kaoheguan') {
          app.globalData.kaoheguan = app.globalData.kaoheguan || {}
          const kf = ['shenhe_zongshu','tongguo_zongshu','yue','zonge','shenhe_zhuangtai','bankuai_list']
          kf.forEach(f => { if (data[f] !== undefined) app.globalData.kaoheguan[f] = data[f] })
        }

        wx.hideLoading()
        this.setData({ isLoading: false, pageState: 'done' })
        wx.showToast({ title: '认证成功', icon: 'success' })

        if (authType === 'dashou' || authType === 'shangjia') {
          setTimeout(() => enterLockedRole(authType), 1200)
        } else if (authType === 'guanshi') {
          setTimeout(() => {
            const pages = getCurrentPages()
            if (pages.length > 1) {
              wx.navigateBack()
            } else {
              wx.redirectTo({ url: '/pages/fighter/fighter' })
            }
          }, 800)
        }
      } else {
        wx.hideLoading()
        this.setData({ isLoading: false })
        wx.showToast({ title: res?.data?.msg || '注册失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ isLoading: false })
      wx.showToast({ title: err.message || '注册失败', icon: 'none' })
    }
  },
}))
