/**
 * 助教服务明细页（管理者视角）。
 *
 * 入口：pages/coach-detail/coach-detail "近期服务明细" 卡片"查看更多"按钮
 * 必传 query：coachId（assistant_id）
 *
 * 与任务 tab 下的 pages/performance-records/ 区别：
 * - Banner 用 fetchCoachBanner 取目标助教信息（name/level/storeName）
 * - 标题展示"<助教名>的业绩"突出查看视角
 * - 单条记录右下角显示"助教预估收入"（去第一人称）
 * - 点击单条记录跳 customer-detail（管理者关心客户而非任务）
 * - 后端 /api/xcx/performance/records?coach_id=xxx，权限码 view_board_coach
 */
import { checkPageAccess } from '../../utils/auth-guard'
import { fetchPerformanceRecords, fetchCoachBanner } from '../../services/api'
import { nameToAvatarColor } from '../../utils/avatar-color'
import { formatMoney, formatCount } from '../../utils/money'
import { formatHours } from '../../utils/time'

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 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
  isScattered?: boolean
}

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

    /** 目标助教 ID（必传，来自 query） */
    coachId: 0,

    /** Banner — 来自 fetchCoachBanner */
    coachName: '',
    coachRole: '',
    storeName: '',
    /** Banner 主标题：用助教名生成"<助教名>的业绩" */
    pageTitle: '业绩明细',

    /** 月份切换 */
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    monthLabel: '',
    canGoPrev: true,
    canGoNext: false,

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

    /** 统计概览 */
    totalCountLabel: '--',
    totalHoursLabel: '--',
    totalHoursRawLabel: '',
    totalIncomeLabel: '--',

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

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

  onLoad(options: Record<string, string | undefined>) {
    const coachIdNum = Number(options?.coachId)
    const coachId = Number.isFinite(coachIdNum) && coachIdNum > 0 ? coachIdNum : 0
    if (coachId === 0) {
      // 必传参数缺失：提示并退回上一页
      wx.showToast({ title: '缺少助教标识', icon: 'none' })
      setTimeout(() => wx.navigateBack({ fail: () => wx.switchTab({ url: '/pages/board-finance/board-finance' }) }), 1000)
      return
    }
    const now = new Date()
    this.setData({
      coachId,
      currentYear: now.getFullYear(),
      currentMonth: now.getMonth() + 1,
      monthLabel: `${now.getFullYear()}年${now.getMonth() + 1}月`,
    })
    this.loadBanner()
    this.loadData()
  },

  onShow() {
    checkPageAccess('pages/coach-service-records/coach-service-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（仅 name/level/storeName，3 字段轻量接口） */
  async loadBanner() {
    try {
      const banner = await fetchCoachBanner(String(this.data.coachId))
      if (!banner) return
      const name = banner.name || ''
      this.setData({
        coachName: name,
        coachRole: banner.level || '助教',
        storeName: banner.storeName || '',
        pageTitle: name ? `${name}的业绩` : '业绩明细',
      })
      // 同步原生 navbar 标题
      if (name) {
        wx.setNavigationBarTitle({ title: `${name}的业绩` })
      }
    } catch (_e) {
      // banner 加载失败不阻塞列表
    }
  },

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

    const now = new Date()
    const { currentYear, currentMonth } = this.data
    const isCurrentMonth = currentYear === now.getFullYear()
      && currentMonth === now.getMonth() + 1
      && now.getDate() <= 5

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

      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 || ''),
        })),
      }))

      let dateGroups: DateGroup[]
      if (this.data.page === 1) {
        dateGroups = newGroups
      } else {
        dateGroups = this._mergeGroups(this.data.dateGroups, newGroups)
      }

      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()
  },

  /** 点击单条记录 → 跳 customer-detail（管理者视角，关心客户） */
  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/customer-detail/customer-detail?id=${memberId}`,
      fail: () => wx.showToast({ title: '页面跳转失败', icon: 'none' }),
    })
  },

  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)
    const isCurrentMonth = currentYear === nowYear && currentMonth === nowMonth && now.getDate() <= 5

    this.setData({
      currentYear,
      currentMonth,
      monthLabel: `${currentYear}年${currentMonth}月`,
      canGoNext,
      canGoPrev: true,
      isCurrentMonth,
      page: 1,
      dateGroups: [],
    })

    this.loadData()
  },
})
