/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | onShow 添加 checkPageAccess 权限守卫 |
| 2026-03-24 | 角色标签显示修复 | coachRole 从英文 code 映射中文；助教显示"X级助教"，与 task-list 页一致 |
*/
import { checkPageAccess } from '../../utils/auth-guard'
import { initPageAiColor } from '../../utils/ai-color-manager'
import { fetchMe, fetchPerformanceOverview } from '../../services/api'
import { nameToAvatarColor } from '../../utils/avatar-color'
// CHANGE 2026-03-27 | 头像：需要 API_BASE 构建头像完整 URL
import { API_BASE } from '../../utils/config'
// CHANGE 2026-05-02 | 业务时钟：sandbox 模式下用 business_year/month 替代 new Date()
import { getBusinessClock } from '../../utils/runtime-clock'

/** 中文课程类型 → 英文 CSS key（WXSS 不支持中文类名） */
const COURSE_TAG_MAP: Record<string, string> = {
  '陪打': 'basic', '基础课': 'basic',
  '包厢': 'room', '包厢课': 'room',
  '超休': 'incentive', '激励课': 'incentive', '打赏课': 'incentive',
}
function courseTagClass(courseType: string): string {
  return COURSE_TAG_MAP[courseType] || 'basic'
}

/** 业绩明细项（本月/上月） */
interface IncomeItem {
  icon: string
  label: string
  desc: string
  value: string
}

/** 服务记录（按日期分组后的展示结构） */
interface ServiceRecord {
  customerName: string
  memberId: number
  avatarChar: string
  avatarColor: string
  timeRange: string
  hours: string
  courseType: string
  location: string
  income: string
}

interface DateGroup {
  date: string
  totalHours?: string
  totalIncome?: string
  records: ServiceRecord[]
}

Page({
  /** 从任务页"查看所有客户"入口进入时，数据加载完后滚动到底部 */
  _scrollToBottom: false,

  data: {
    pageState: 'loading' as 'loading' | 'empty' | 'error' | 'normal',

    /** Banner 数据 */
    avatarUrl: '',
    coachName: '',
    coachRole: '',
    storeName: '',
    monthlyIncome: '',
    lastMonthIncome: '',

    /** 当月预估判断 */
    isCurrentMonth: true,

    /** 收入档位 */
    currentTier: {
      basicRate: 0,
      incentiveRate: 0,
    },
    nextTier: {
      basicRate: 0,
      incentiveRate: 0,
    },
    upgradeHoursNeeded: 0,
    upgradeBonus: 0,

    /** 本月业绩明细 */
    incomeItems: [] as IncomeItem[],
    monthlyTotal: '',

    /** 服务记录 */
    thisMonthRecords: [] as DateGroup[],
    thisMonthRecordsExpanded: false,
    /** 默认显示前 N 条日期组 */
    visibleRecordGroups: 2,

    /** 新客列表 */
    newCustomers: [] as Array<{ name: string; memberId: number; avatarChar: string; avatarColor: string; lastService: string; count: number }>,
    newCustomerExpanded: false,

    /** 常客列表 */
    regularCustomers: [] as Array<{ name: string; memberId: number; avatarChar: string; avatarColor: string; hours: number; income: string; count: number }>,
    regularCustomerExpanded: false,
  },

  onLoad(options?: { scrollToBottom?: string }) {
    // 初始化 AI 图标配色（蓝色 - 数据分析感）
    const { aiColor } = initPageAiColor('performance')
    this.setData({ aiColor })

    // 记录是否需要滚动到底部（从任务页"查看所有客户"入口进入）
    this._scrollToBottom = options?.scrollToBottom === '1'

    this.loadData()
  },

  onShow() {
    // 权限守卫：检查登录状态、账号禁用、角色权限
    checkPageAccess('pages/performance/performance')
  },

  async loadData() {
    this.setData({ pageState: 'loading' })
    wx.showLoading({ title: '加载中...', mask: true })

    // CHANGE 2026-05-02 | G2 当月预估判断改用业务时钟（sandbox 模式按 sandbox_date 判断）
    const clock = await getBusinessClock()
    const nowYear = clock.business_year
    const nowMonth = clock.business_month
    const businessDay = parseInt(clock.business_date.slice(8, 10), 10) || 1
    // TODO: 联调时从接口参数或页面参数获取 year/month
    const year = nowYear
    const month = nowMonth
    // CHANGE 2026-03-24 | 预估规则：当月且当前日期 ≤ 5号才显示"预估"
    const isCurrentMonth = year === nowYear && month === nowMonth && businessDay <= 5

    try {
      // 并行请求用户信息和绩效概览
      const [me, overview] = await Promise.all([
        fetchMe().catch(() => null),
        fetchPerformanceOverview({ year, month }),
      ])

      // 用户信息（fetchMe 失败不阻塞，用 overview 返回的兜底）
      // CHANGE 2026-03-27 | 头像：读 avatarUrl（CamelModel 转换后的字段名），拼接完整 URL
      // 统一与 task-list 页面的用户信息获取逻辑
      const userId = (me as any)?.userId
      const hasAvatar = !!(me as any)?.avatarUrl
      const avatarUrl = hasAvatar && userId ? `${API_BASE}/api/xcx/avatar/${userId}` : ''
      const coachName = overview.coachName || (me as any)?.nickname || (me as any)?.name || ''
      // CHANGE 2026-03-27 | 角色标签：统一用 fetchMe 的 role（英文 code），不用 overview.coachRole
      // overview.coachRole 可能返回 "assistant" 等非标准值，ROLE_LABELS 无法映射
      const ROLE_LABELS: Record<string, string> = { coach: '助教', staff: '员工', head_coach: '主教练', manager: '店长' }
      const rawRole = (me as any)?.role || overview.coachRole || ''
      const coachLevel = (me as any)?.coachLevel || (me as any)?.coach_level || ''
      const roleLabel = ROLE_LABELS[rawRole] || rawRole
      const coachRole = (rawRole === 'coach' && coachLevel) ? `${coachLevel}助教` : roleLabel
      const storeName = overview.storeName || (me as any)?.storeName || ''

      // CHANGE 2026-03-24 | 头像颜色改为前端根据 member_id 计算
      const thisMonthRecords = (overview.thisMonthRecords || []).map((group: any) => ({
        ...group,
        records: (group.records || []).map((rec: any) => ({
          ...rec,
          avatarColor: nameToAvatarColor(String(rec.memberId ?? rec.member_id ?? '')),
          courseTagClass: courseTagClass(rec.courseType ?? rec.course_type ?? ''),
        })),
      }))
      const newCustomers = (overview.newCustomers || []).map((c: any) => ({
        ...c,
        avatarColor: nameToAvatarColor(String(c.memberId ?? c.member_id ?? '')),
      }))
      const regularCustomers = (overview.regularCustomers || []).map((c: any) => ({
        ...c,
        avatarColor: nameToAvatarColor(String(c.memberId ?? c.member_id ?? '')),
      }))

      this.setData({
        pageState: 'normal',
        isCurrentMonth,
        avatarUrl,
        coachName,
        coachRole,
        storeName,
        monthlyIncome: overview.monthlyIncome,
        lastMonthIncome: overview.lastMonthIncome,
        currentTier: {
          basicRate: overview.currentTier.basicRate,
          incentiveRate: overview.currentTier.incentiveRate,
        },
        nextTier: {
          basicRate: overview.nextTier.basicRate,
          incentiveRate: overview.nextTier.incentiveRate,
        },
        upgradeHoursNeeded: overview.upgradeHoursNeeded,
        upgradeBonus: overview.upgradeBonus,
        incomeItems: overview.incomeItems,
        monthlyTotal: overview.monthlyTotal,
        thisMonthRecords,
        newCustomers,
        regularCustomers,
      })

      // 从任务页"查看所有客户"入口进入时，自动展开常客列表并滚动到底部
      if (this._scrollToBottom) {
        this._scrollToBottom = false
        this.setData({
          regularCustomerExpanded: true,
          newCustomerExpanded: true,
        })
        setTimeout(() => {
          wx.pageScrollTo({ scrollTop: 99999, duration: 300 })
        }, 150)
      }
    } catch (_e) {
      this.setData({ pageState: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  /** 加载失败重试 */
  onRetry() {
    this.loadData()
  },

  /** 自定义导航栏返回 */
  onNavBack() {
    wx.navigateBack({ fail: () => wx.switchTab({ url: '/pages/task-list/task-list' }) })
  },

  /** 展开/收起本月服务记录 */
  toggleThisMonthRecords() {
    this.setData({ thisMonthRecordsExpanded: !this.data.thisMonthRecordsExpanded })
  },

  /** 查看全部 → 跳转业绩明细 */
  goToRecords() {
    wx.navigateTo({ url: '/pages/performance-records/performance-records' })
  },

  /** 展开/收起新客列表 */
  toggleNewCustomer() {
    this.setData({ newCustomerExpanded: !this.data.newCustomerExpanded })
  },

  /** 展开/收起常客列表 */
  toggleRegularCustomer() {
    this.setData({ regularCustomerExpanded: !this.data.regularCustomerExpanded })
  },

  /** 点击客户卡片 → 跳转任务详情 */
  // CHANGE 2026-03-25 | 传 memberId 替代 customerName，详情页按 member 查询任务
  // CHANGE 2026-03-27 | 任务C1: 散客/未知客户（memberId <= 0）拦截，不跳转
  onCustomerTap(e: WechatMiniprogram.TouchEvent) {
    const { name, memberId } = e.currentTarget.dataset
    const mid = Number(memberId)
    if (!mid || mid <= 0) {
      wx.showToast({ title: '未知客户不提供查看详情', icon: 'none' })
      return
    }
    wx.navigateTo({
      url: `/pages/task-detail/task-detail?memberId=${memberId || ''}`,
      fail: () => wx.showToast({ title: '页面跳转失败', icon: 'none' }),
    })
  },

  /** 点击服务记录 → 跳转任务详情 */
  // CHANGE 2026-03-25 | 优先用 taskId，fallback 用 memberId
  onRecordTap(e: WechatMiniprogram.TouchEvent) {
    const { customerName, taskId, memberId } = e.currentTarget.dataset
    const params = taskId ? `id=${taskId}` : `memberId=${memberId || ''}`
    wx.navigateTo({
      url: `/pages/task-detail/task-detail?${params}`,
      fail: () => wx.showToast({ title: '页面跳转失败', icon: 'none' }),
    })
  },

  /** 点击收入概览卡片 → 跳转业绩记录 */
  onIncomeCardTap() {
    wx.navigateTo({ url: '/pages/performance-records/performance-records' })
  },
})
