import { fetchMe } from '../../services/api'
import { getMenuRoute, navigateTo } from '../../utils/router'

Page({
  data: {
    userInfo: null as any,
  },

  onShow() {
    // 同步 custom-tab-bar 选中态
    const tabBar = this.getTabBar?.()
    if (tabBar) tabBar.setData({ active: 'my' })
    this.loadUserInfo()
  },

  async loadUserInfo() {
    try {
      const info = await fetchMe()
      this.setData({ userInfo: info })
    } catch {
      wx.showToast({ title: '加载用户信息失败', icon: 'none' })
    }
  },

  onMenuTap(e: WechatMiniprogram.TouchEvent) {
    const key = e.currentTarget.dataset.key as string
    const route = getMenuRoute(key)
    if (route) {
      navigateTo(route)
    }
  },

  onLogout() {
    wx.showModal({
      title: '确认退出',
      content: '确认退出当前账号吗？',
      confirmColor: '#e34d59',
      success(res) {
        if (res.confirm) {
          wx.clearStorageSync()
          wx.reLaunch({ url: '/pages/login/login' })
        }
      },
    })
  },
})
