// pages/gerenzhongxin/gerenzhongxin.js
const app = getApp()

Page({
  data: {
    avatarUrl: '',
    userNicheng: '',
    userUid: '',
    showLoginBtn: false,
    orderCounts: { daifuwu:0, fuwuzhong:0, yiwancheng:0, yituikuan:0 },
    // 图标
    settingIcon: '', daifuwuIcon: '', fuwuzhongIcon: '', yiwanchengIcon: '', yituikuanIcon: '',
    dashouIcon: '', shangjiaIcon: '', guanshiIcon: '', kefuIcon: '',
    zuzhangIcon: '', guanzhualongIcon: '', arrowRightIcon: '', qingchuIcon: '',
    bottomSafePadding: 0
  },

  onLoad() {
    this.initIconUrls()
    this.loadUserData()
    this.setBottomSafe()
  },

  onShow() {
    this.loadUserData()
    this.updateOrderCounts()
    this.registerNotification()
    this.checkAvatarPrompt()
    this.initIconUrls()
  },

  setBottomSafe() {
    const sys = wx.getSystemInfoSync()
    const safeBottom = sys.screenHeight - sys.safeArea.bottom  // 底部安全区高度(px)
    const tabBarHeight = (sys.windowWidth / 750) * 100          // 100rpx 转为 px
    this.setData({
      bottomSafePadding: safeBottom + tabBarHeight + 4  // 4px 微调，确保不留缝隙
    })
  },

  registerNotification() {
    const comp = this.selectComponent('#global-notification')
    if (comp?.showNotification) {
      app.globalData.globalNotification = {
        show: d => comp.showNotification(d),
        hide: () => comp.hideNotification()
      }
    }
  },

  checkAvatarPrompt() {
    const ds = wx.getStorageSync('dashoustatus')
    const tx = wx.getStorageSync('touxiang') || ''
    if (ds === 1 && (!tx || tx === 'a_long/morentouxiang.jpg')) {
      wx.showModal({
        title: '提示', content: '请先设置头像',
        confirmText: '去设置', confirmColor: '#C9A962',
        success: r => r.confirm && wx.navigateTo({ url: '/pages/xiugai/xiugai' })
      })
    }
  },

  initIconUrls() {
    const base = (app.globalData.ossImageUrl || '') + '/beijing/tubiao/'
    this.setData({
      settingIcon: base + 'grzx_shezhi.jpg',
      daifuwuIcon: base + 'grzx_daifuwu.jpg',
      fuwuzhongIcon: base + 'grzx_fuwuzhong.jpg',
      yiwanchengIcon: base + 'grzx_yiwancheng.jpg',
      yituikuanIcon: base + 'grzx_yituikuan.jpg',
      dashouIcon: base + 'grzx_dashou.jpg',
      shangjiaIcon: base + 'grzx_shangjia.jpg',
      guanshiIcon: base + 'grzx_guanshi.jpg',
      kefuIcon: base + 'grzx_kefu.jpg',
      zuzhangIcon: base + 'grzx_zuzhang.jpg',
      guanzhualongIcon: base + 'grzx_guanzhualong.jpg',
      arrowRightIcon: base + 'grzx_arrow_right.jpg',
      qingchuIcon: base + 'grzx_qingchu.jpg',
      kaoheguanIcon: base + 'kaoheguan.png',   // 考核官认证图标
    })
  },

  loadUserData() {
    const token = wx.getStorageSync('token')
    const nick = wx.getStorageSync('nicheng') || ''
    const uid = wx.getStorageSync('uid') || ''
    const tx = wx.getStorageSync('touxiang') || ''
    const def = app.globalData.morentouxiang || ''
    const oss = app.globalData.ossImageUrl || ''
    let avt = ''
    if (tx) avt = tx.startsWith('http') ? tx : oss + tx
    else if (def) avt = def.startsWith('http') ? def : oss + def
    this.setData({
      avatarUrl: avt, userNicheng: nick, userUid: uid,
      showLoginBtn: !token || !nick || !uid
    })
  },

  updateOrderCounts() {
    const c = app.globalData.dingdanTiaoshu || {}
    this.setData({ orderCounts: {
      daifuwu: c.daifuwu||0, fuwuzhong: c.fuwuzhong||0,
      yiwancheng: c.yiwancheng||0, yituikuan: c.yituikuan||0
    }})
  },

  goToSetting() { wx.navigateTo({ url: '/pages/xiugai/xiugai' }) },

  handleWechatLogin() {
    wx.showLoading({ title: '登录中...' })
    wx.login({
      success: r => {
        if (r.code) this.sendLoginRequest(r.code)
        else { wx.hideLoading(); wx.showToast({ title: '获取code失败', icon: 'none' }) }
      },
      fail: () => { wx.hideLoading(); wx.showToast({ title: '微信登录失败', icon: 'none' }) }
    })
  },

  sendLoginRequest(code) {
    const api = app.globalData.apiBaseUrl
    if (!api) return wx.hideLoading()
    wx.request({
      url: api + '/yonghu/wechatlogin', method: 'POST', data: { code },
      header: { 'content-type': 'application/json' },
      success: res => {
        if (res.statusCode === 200 && res.data?.code === 0 && res.data.data) {
          const d = res.data.data
          wx.setStorageSync('token', d.token)
          ;['nicheng','uid','touxiang','dashoustatus','guanshistatus','shangjiastatus','zuzhangstatus','kaoheguanstatus'].forEach(k => {
            if (d[k] !== undefined) wx.setStorageSync(k, d[k])
          })
          app.globalData.zuzhangstatus = d.zuzhangstatus
          app.globalData.dingdanTiaoshu = {
            daifuwu: d.dingdantiaoshu?.daifuwu||0,
            fuwuzhong: d.dingdantiaoshu?.fuwuzhong||0,
            yiwancheng: d.dingdantiaoshu?.yiwancheng||0,
            yituikuan: d.dingdantiaoshu?.yituikuan||0
          }
          ;['shangjiastatus','dashoustatus','guanshistatus'].forEach(f => {
            if (d[f] !== undefined) app.globalData[f] = d[f]
          })
          this.loadUserData(); this.updateOrderCounts()
          wx.showToast({ title: '登录成功', icon: 'success' })
        } else wx.showToast({ title: res.data?.msg || '登录失败', icon: 'none' })
        wx.hideLoading()
      },
      fail: () => { wx.hideLoading(); wx.showToast({ title: '网络错误', icon: 'none' }) }
    })
  },

  goToOrder(e) { wx.navigateTo({ url: `/pages/dingdan/dingdan?type=${e.currentTarget.dataset.type}` }) },
  goToAuth(e) { wx.navigateTo({ url: `/pages/renzheng/renzheng?type=${e.currentTarget.dataset.type}` }) },

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

  clearCache() {
    wx.showModal({
      title: '清除缓存', content: '将清除所有登录数据，确定继续？',
      confirmText: '确定', cancelText: '取消',
      success: r => {
        if (r.confirm) {
          wx.clearStorageSync()
          app.globalData.dingdanTiaoshu = { daifuwu:0, fuwuzhong:0, yiwancheng:0, yituikuan:0 }
          this.setData({ avatarUrl:'', userNicheng:'', userUid:'', showLoginBtn:true,
            orderCounts:{ daifuwu:0, fuwuzhong:0, yiwancheng:0, yituikuan:0 } })
          wx.showToast({ title: '已清除', icon: 'success' })
        }
      }
    })
  }
})