// pages/renzheng/renzheng.js
import request from '../../utils/request.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({
  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()
  },

  onShow() {
    if (this.data.authType) 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' })
      } 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' })
    }
  },

  goToKefu() {
    const app = getApp()
    const { link, enterpriseId } = app.globalData.kefuConfig || {}
    if (!link || !enterpriseId) {
      wx.showToast({ title: '客服配置未加载', icon: 'none' })
      return
    }
    wx.openCustomerServiceChat({ extInfo: { url: link }, corpId: enterpriseId })
  }
})