/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | onShow 添加 checkPageAccess 权限守卫 |
| 2026-03-27 | 联调改造 | 重写：Banner 对齐 performance 页面，数据对接后端 PERF-2，卡片样式复用 performance 服务记录明细 |
| 2026-04-20 | 拆分助教视角 | 删除 coachId 分支，本页恢复"任务 tab 助教自查"单一职责；管理者视角迁至 pages/coach-service-records/ |
*/
import { checkPageAccess } from '../../utils/auth-guard'
import { fetchPerformanceRecords, fetchMe } from '../../services/api'
import { nameToAvatarColor } from '../../utils/avatar-color'
import { formatMoney, formatCount } from '../../utils/money'
import { formatHours } from '../../utils/time'
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'
}

/** 角色英文 code → 中文显示名 */
const ROLE_LABELS: Record<string, string> = {
  coach: '助教', staff: '员工', head_coach: '主教练', manager: '店长',
}

/** 按日期分组后的展示结构（对齐 performance 页面） */
interface DateGroup {
  date: string
  totalHours: string
  totalIncome: string
  records: RecordItem[]
}

interface RecordItem {
  customerName: string
  memberId: number
  avatarChar: string
  avatarColor: string
  timeRange: string
  hours: string
  courseType: string
  courseTagClass: string
  location: string
  income: string
}

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

    /** Banner — 对齐 performance 页面 */
    avatarUrl: '',
    coachName: '',
    coachRole: '',
    storeName: '',

    /** 月份切换（onLoad 中改写为业务时钟当前年月） */
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    monthLabel: '',
    canGoPrev: true,
    canGoNext: false,

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

    /** 统计概览（从后端 summary 读取） */
    totalCountLabel: '--',
    totalHoursLabel: '--',
    totalHoursRawLabel: '',
    totalIncomeLabel: '--',

    /** 按日期分组的记录 */
    dateGroups: [] as DateGroup[],

    /** 分页 */
    page: 1,
    pageSize: 20,
    hasMore: false,
  },

  async onLoad() {
    // CHANGE 2026-05-02 | 用业务时钟初始化年月，sandbox 模式按 sandbox_date 显示
    const clock = await getBusinessClock()
    this.setData({
      currentYear: clock.business_year,
      currentMonth: clock.business_month,
      monthLabel: `${clock.business_year}年${clock.business_month}月`,
    })
    this.loadBanner()
    this.loadData()
  },

  onShow() {
    checkPageAccess('pages/performance-records/performance-records')
  },

  onPullDownRefresh() {
    this.setData({ page: 1, dateGroups: [] })
    this.loadData(() => wx.stopPullDownRefresh())
  },

  onReachBottom() {
    if (!this.data.hasMore) return
    this.setData({ page: this.data.page + 1 })
    this.loadData()
  },

  /** 加载 Banner 用户信息（与 performance 页面统一） */
  async loadBanner() {
    try {
      const me = await fetchMe()
      if (!me) return
      const userId = (me as any)?.userId
      const hasAvatar = !!(me as any)?.avatarUrl
      const avatarUrl = hasAvatar && userId ? `${API_BASE}/api/xcx/avatar/${userId}` : ''
      const rawRole = (me as any)?.role || ''
      const coachLevel = (me as any)?.coachLevel || ''
      const roleLabel = ROLE_LABELS[rawRole] || rawRole
      const coachRole = (rawRole === 'coach' && coachLevel) ? `${coachLevel}助教` : roleLabel
      this.setData({
        avatarUrl,
        coachName: (me as any)?.nickname || '',
        coachRole,
        storeName: (me as any)?.storeName || '',
      })
    } catch (_e) {
      // 用户信息加载失败不阻塞页面
    }
  },

  /** 加载绩效明细数据 */
  async loadData(cb?: () => void) {
    if (this.data.page === 1) {
      this.setData({ pageState: 'loading' })
    }
    wx.showLoading({ title: '加载中...', mask: true })

    // 预估规则：当月且当前日期 ≤ 5号（全小程序统一）
    // CHANGE 2026-05-02 | 用业务时钟，sandbox 模式按 sandbox_date 判断
    const clock = await getBusinessClock()
    const { currentYear, currentMonth } = this.data
    const businessDay = parseInt(clock.business_date.slice(8, 10), 10) || 1
    const isCurrentMonth = currentYear === clock.business_year
      && currentMonth === clock.business_month
      && businessDay <= 5

    try {
      const res = await fetchPerformanceRecords({
        year: currentYear,
        month: currentMonth,
        page: this.data.page,
        pageSize: this.data.pageSize,
      })

      // 后端返回的 dateGroups 已按日期分组，前端只需补充头像颜色和课程标签映射
      const newGroups = (res.dateGroups || []).map((g: any) => ({
        ...g,
        records: (g.records || []).map((rec: any) => ({
          ...rec,
          avatarColor: nameToAvatarColor(String(rec.memberId ?? '')),
          avatarChar: rec.avatarChar || (rec.customerName || '?').charAt(0),
          courseTagClass: courseTagClass(rec.courseType || ''),
        })),
      }))

      // 懒加载：追加到已有 dateGroups（需合并同日期组）
      let dateGroups: DateGroup[]
      if (this.data.page === 1) {
        dateGroups = newGroups
      } else {
        dateGroups = this._mergeGroups(this.data.dateGroups, newGroups)
      }

      // 统计概览（从后端 summary 读取，仅第一页设置）
      const updates: Record<string, any> = {
        pageState: dateGroups.length > 0 ? 'normal' : 'empty',
        isCurrentMonth,
        dateGroups,
        hasMore: res.hasMore ?? false,
      }

      if (this.data.page === 1 && res.summary) {
        const s = res.summary
        updates.totalCountLabel = formatCount(s.totalCount, '笔')
        updates.totalHoursLabel = formatHours(s.totalHours)
        updates.totalIncomeLabel = formatMoney(s.totalIncome)
        // 折前时长：仅当与折后不同时显示
        updates.totalHoursRawLabel = (s.totalHoursRaw !== s.totalHours && s.totalHoursRaw > 0)
          ? formatHours(s.totalHoursRaw) : ''
      }

      this.setData(updates)
    } catch (_err) {
      if (this.data.page === 1) {
        this.setData({ pageState: 'error' })
      }
    } finally {
      wx.hideLoading()
    }

    cb?.()
  },

  /** 合并懒加载的日期组（同日期追加记录） */
  _mergeGroups(existing: DateGroup[], incoming: DateGroup[]): DateGroup[] {
    const merged = [...existing]
    for (const g of incoming) {
      const found = merged.find(m => m.date === g.date)
      if (found) {
        found.records = [...found.records, ...g.records]
      } else {
        merged.push(g)
      }
    }
    return merged
  },

  /** 重试加载 */
  onRetry() {
    this.setData({ page: 1, dateGroups: [] })
    this.loadData()
  },

  /** 返回上一页 */
  onNavBack() {
    wx.navigateBack({ fail: () => wx.switchTab({ url: '/pages/task-list/task-list' }) })
  },

  /** 点击服务记录 → 跳转任务详情（与 performance 页面统一） */
  onRecordTap(e: WechatMiniprogram.TouchEvent) {
    const { 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' }),
    })
  },

  /** 切换月份 */
  async switchMonth(e: WechatMiniprogram.TouchEvent) {
    const direction = e.currentTarget.dataset.direction as 'prev' | 'next'
    let { currentYear, currentMonth } = this.data

    if (direction === 'prev') {
      currentMonth--
      if (currentMonth < 1) { currentMonth = 12; currentYear-- }
    } else {
      currentMonth++
      if (currentMonth > 12) { currentMonth = 1; currentYear++ }
    }

    // CHANGE 2026-05-02 | 用业务时钟，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
    const canGoNext = currentYear < nowYear || (currentYear === nowYear && currentMonth < nowMonth)
    const isCurrentMonth = currentYear === nowYear && currentMonth === nowMonth && businessDay <= 5

    // 月份切换重置分页到第 1 页
    this.setData({
      currentYear,
      currentMonth,
      monthLabel: `${currentYear}年${currentMonth}月`,
      canGoNext,
      canGoPrev: true,
      isCurrentMonth,
      page: 1,
      dateGroups: [],
    })

    this.loadData()
  },
})
