import type { PerformanceRecord } from '../../utils/mock-data'
import { fetchPerformanceRecords } from '../../services/api'
import { nameToAvatarColor } from '../../utils/avatar-color'
import { formatMoney, formatCount } from '../../utils/money'
import { formatHours } from '../../utils/time'

/** 按日期分组后的展示结构 */
interface DateGroup {
  date: string
  totalHours: number
  totalIncome: number
  totalHoursLabel: string
  totalIncomeLabel: string
  records: RecordItem[]
}

interface RecordItem {
  id: string
  customerName: string
  avatarChar: string
  avatarColor: string
  timeRange: string
  hours: number        // 折算后课时（小时，number）
  hoursRaw?: number    // 折算前课时（小时，number，可选）
  courseType: string
  courseTypeClass: string
  location: string
  income: number       // 收入（元，整数）
}

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

    /** Banner */
    coachName: '小燕',
    coachLevel: '星级',
    storeName: '球会名称店',

    /** 月份切换 */
    currentYear: 2026,
    currentMonth: 2,
    monthLabel: '2026年2月',
    canGoPrev: true,
    canGoNext: false,

    /** 统计概览 */
    totalCount: 0,
    totalHours: 0,
    totalIncome: 0,
    totalCountLabel: '--',
    totalHoursLabel: '--',
    totalHoursRawLabel: '',
    totalIncomeLabel: '--',

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

    /** 所有记录（用于筛选） */
    allRecords: [] as any[],

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

  onLoad() {
    this.loadData()
  },

  onPullDownRefresh() {
    this.loadData(() => wx.stopPullDownRefresh())
  },

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

  async loadData(cb?: () => void) {
    this.setData({ pageState: 'loading' })

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

      const records = res.records || []
      // 按日期分组（后端返回的记录已按日期排序）
      const groupMap = new Map<string, DateGroup>()
      for (const r of records) {
        const dateKey = r.date || '未知日期'
        if (!groupMap.has(dateKey)) {
          groupMap.set(dateKey, {
            date: dateKey,
            totalHours: 0,
            totalIncome: 0,
            totalHoursLabel: '',
            totalIncomeLabel: '',
            records: [],
          })
        }
        const group = groupMap.get(dateKey)!
        const hours = (r as any).hours ?? 0
        const income = r.amount ?? 0
        group.totalHours += hours
        group.totalIncome += income
        group.records.push({
          id: r.id,
          customerName: r.customerName,
          avatarChar: r.customerName?.charAt(0) || '?',
          avatarColor: nameToAvatarColor(r.customerName || ''),
          timeRange: (r as any).timeRange || '',
          hours,
          hoursRaw: (r as any).hoursRaw,
          courseType: r.type || '',
          courseTypeClass: `tag-${(r.category || 'basic').toLowerCase()}`,
          location: (r as any).location || '',
          income,
        })
      }

      const dateGroups = Array.from(groupMap.values()).map(g => ({
        ...g,
        totalHoursLabel: formatHours(g.totalHours),
        totalIncomeLabel: formatMoney(g.totalIncome),
      }))

      // 汇总统计
      const totalCount = records.length
      const totalHours = dateGroups.reduce((s, g) => s + g.totalHours, 0)
      const totalIncome = dateGroups.reduce((s, g) => s + g.totalIncome, 0)

      this.setData({
        pageState: dateGroups.length > 0 ? 'normal' : 'empty',
        allRecords: records,
        dateGroups,
        totalCount,
        totalHours,
        totalIncome,
        totalCountLabel: formatCount(totalCount, '笔'),
        totalHoursLabel: formatHours(totalHours),
        totalHoursRawLabel: '',
        totalIncomeLabel: formatMoney(totalIncome),
        hasMore: res.hasMore ?? false,
      })
    } catch (_err) {
      this.setData({ pageState: 'error' })
    }

    cb?.()
  },

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

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

  /** 切换月份 */
  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++
      }
    }

    // 不能超过当前月
    const now = new Date()
    const nowYear = now.getFullYear()
    const nowMonth = now.getMonth() + 1
    const canGoNext = currentYear < nowYear || (currentYear === nowYear && currentMonth < nowMonth)

    this.setData({
      currentYear,
      currentMonth,
      monthLabel: `${currentYear}年${currentMonth}月`,
      canGoNext,
      canGoPrev: true,
    })

    this.loadData()
  },
})
