/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | onShow 添加 checkPageAccess 权限守卫 |
| 2026-03-24 | 头像昵称获取 | loadUserInfo 从 fetchMe 的 avatar_url 构建完整头像 URL |
*/
import { checkPageAccess } from '../../utils/auth-guard'
import { fetchMe } from '../../services/api'
import { getMenuRoute, navigateTo } from '../../utils/router'
// CHANGE 2026-03-24 | 头像：需要 API_BASE 构建头像完整 URL
import { API_BASE } from '../../utils/config'

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

  async onShow() {
    // 权限守卫：检查登录状态、账号禁用、角色权限
    const allowed = await checkPageAccess('pages/my-profile/my-profile')
    if (!allowed) return
    // 同步 custom-tab-bar 选中态
    const tabBar = this.getTabBar?.()
    if (tabBar) tabBar.setData({ active: 'my' })
    this.loadUserInfo()
  },

  /** G1: 从全局用户信息或 fetchMe 获取头像等字段 */
  async loadUserInfo() {
    // 优先从 globalData 读取已有用户信息
    const app = getApp<IAppOption>()
    const authUser = app.globalData.authUser
    if (authUser?.nickname) {
      this.setData({
        userInfo: {
          name: authUser.nickname,
          role: '',
          storeName: '',
        },
        // CHANGE 2026-03-24 | 头像：从 globalData 读取 avatarUrl，构建完整 URL
        avatarUrl: authUser.avatarUrl
          ? `${API_BASE}/api/xcx/avatar/${authUser.userId}`
          : '',
      })
    }
    // 兜底：调用 fetchMe 获取完整用户信息
    try {
      const info = await fetchMe()
      if (info) {
        // CHANGE 2026-03-24 | 头像：后端返回 avatarUrl（相对路径），有值则通过头像接口获取
        const userId = (info as any).userId || authUser?.userId
        const hasAvatar = !!(info as any).avatarUrl
        this.setData({
          userInfo: info,
          avatarUrl: hasAvatar && userId
            ? `${API_BASE}/api/xcx/avatar/${userId}`
            : this.data.avatarUrl,
        })
      }
    } 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' })
        }
      },
    })
  },
})
