// CHANGE 2026-03-20 | RNS1.4 T10.2: 月份切换改为按月请求 API，移除 mock 全量加载+本地过滤
import { fetchCustomerRecords, fetchCustomerDetail } from '../../services/api'

/** 服务记录（对齐 task-detail ServiceRecord 结构，复用 service-record-card 组件） */
interface ServiceRecord {
  id: string
  date: string
  project: string
  duration: number
  amount: number
  coachName: string
  /** 台桌号，如 "A12号台" */
  table: string
  /** 课程类型标签，如 "基础课" */
  type: string
  /** 课程样式 class 后缀：basic / vip / tip / recharge */
  typeClass: 'basic' | 'vip' | 'tip' | 'recharge'
  /** 卡片类型：course=普通课，recharge=充值提成 */
  recordType: 'course' | 'recharge'
  /** 折算后小时数（原始数字，组件负责加 h 后缀） */
  durationHours: number
  /** 折算前小时数（原始数字，组件负责加 h 后缀） */
  durationRaw: number
  /** 到手金额（原始数字，组件负责加 ¥ 前缀） */
  income: number
  /** 是否预估金额 */
  isEstimate: boolean
  /** 商品/饮品描述 */
  drinks: string
  /** 显示用日期，如 "2月5日 15:00 - 17:00" */
  displayDate: string
}

Page({
  data: {
    /** 页面状态 */
    pageState: 'loading' as 'loading' | 'empty' | 'error' | 'normal',
    /** 客户 ID */
    customerId: '',
    /** 客户名 */
    customerName: '',
    /** 客户名首字 */
    customerInitial: '',
    /** 客户电话（脱敏） */
    customerPhone: '',
    /** 客户电话（完整，查看后显示） */
    customerPhoneFull: '',
    /** 手机号是否已展开 */
    phoneVisible: false,
    /** 累计服务次数 */
    totalServiceCount: 0,
    /** 关系指数 */
    relationIndex: '0.85',
    /** 当前月份标签 */
    monthLabel: '',
    /** 当前年 */
    currentYear: new Date().getFullYear(),
    /** 当前月 */
    currentMonth: new Date().getMonth() + 1,
    /** 最小年月（数据起始） */
    minYearMonth: 202501,
    /** 最大年月（当前月） */
    maxYearMonth: new Date().getFullYear() * 100 + (new Date().getMonth() + 1),
    /** 是否可切换上月 */
    canPrev: true,
    /** 是否可切换下月 */
    canNext: false,
    /** 月度统计 */
    monthCount: '0次',
    monthHours: '0h',
    monthRelation: '0.85',
    /** 当前月的服务记录 */
    records: [] as ServiceRecord[],
    /** 是否还有更多 */
    hasMore: false,
    /** 加载更多中 */
    loadingMore: false,
    /** 月份数据加载中（用于月份切换时的 loading 状态） */
    monthLoading: false,
  },

  onLoad(options) {
    const id = options?.customerId || options?.id || ''
    // 默认当前年月
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1
    this.setData({
      customerId: id,
      currentYear,
      currentMonth,
      maxYearMonth: currentYear * 100 + currentMonth,
    })
    this.loadCustomerInfo(id)
    this.loadMonthRecords(id, currentYear, currentMonth)
  },

  /** 加载客户基本信息（头部展示） */
  async loadCustomerInfo(id: string) {
    try {
      const detail = await fetchCustomerDetail(id)
      if (detail) {
        const name = detail.name || '客户'
        this.setData({
          customerName: name,
          customerInitial: name[0] || '?',
          customerPhone: detail.phone ? detail.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '',
          customerPhoneFull: detail.phone || '',
          // totalServiceCount 由真实 API 返回；mock 类型无此字段，安全取值
          totalServiceCount: (detail as any).totalServiceCount ?? 0,
        })
      }
    } catch (err) {
      console.error('[customer-service-records] loadCustomerInfo failed:', err)
      // 客户信息加载失败不阻塞记录展示
    }
  },

  /** 按月加载服务记录（核心方法） */
  async loadMonthRecords(customerId: string, year: number, month: number) {
    const monthLabel = `${year}年${month}月`

    // 清空列表 → 显示 loading
    this.setData({
      monthLabel,
      records: [],
      monthLoading: true,
      pageState: 'loading',
    })

    try {
      const res = await fetchCustomerRecords({ customerId, year, month })
      const rawRecords: any[] = res.records || []

      // 转换为展示格式（对齐 service-record-card 组件）
      const records: ServiceRecord[] = rawRecords.map((r: any) => {
        const d = new Date(r.date)
        const m = d.getMonth() + 1
        const day = d.getDate()
        const dateLabel = `${m}月${day}日`
        const timeRange = this.generateTimeRange(r.duration || 0)
        const isRecharge = (r.project || '').includes('充值')
        return {
          id: r.id || '',
          date: r.date || '',
          project: r.project || '',
          duration: r.duration || 0,
          amount: r.amount || 0,
          coachName: r.coachName || '',
          table: r.table || this.getTableNo(r.id || ''),
          type: this.getTypeLabel(r.project || ''),
          typeClass: this.getTypeClass(r.project || '') as 'basic' | 'vip' | 'tip' | 'recharge',
          recordType: (isRecharge ? 'recharge' : 'course') as 'course' | 'recharge',
          durationHours: isRecharge ? 0 : parseFloat(((r.duration || 0) / 60).toFixed(1)),
          durationRaw: 0,
          income: r.amount || 0,
          isEstimate: r.isEstimate || false,
          drinks: r.drinks || '',
          displayDate: isRecharge ? dateLabel : `${dateLabel} ${timeRange}`,
        }
      })

      // 月度统计
      const totalMinutes = rawRecords.reduce((sum: number, r: any) => sum + (r.duration || 0), 0)
      const monthCount = records.length + '次'
      const monthHours = (totalMinutes / 60).toFixed(1) + 'h'

      // 边界判断
      const yearMonth = year * 100 + month
      const canPrev = yearMonth > this.data.minYearMonth
      const canNext = yearMonth < this.data.maxYearMonth

      this.setData({
        records,
        monthCount,
        monthHours,
        canPrev,
        canNext,
        hasMore: res.hasMore || false,
        monthLoading: false,
        pageState: 'normal',
      })
    } catch (err) {
      console.error('[customer-service-records] loadMonthRecords failed:', err)
      this.setData({
        monthLoading: false,
        pageState: 'error',
      })
    }
  },

  /** 生成模拟时间段（后端未返回具体时段时的 fallback） */
  generateTimeRange(durationMin: number): string {
    const startHour = 14 + Math.floor(Math.random() * 6)
    const endMin = startHour * 60 + durationMin
    const endHour = Math.floor(endMin / 60)
    const endMinute = endMin % 60
    return `${startHour}:00 - ${endHour}:${String(endMinute).padStart(2, '0')}`
  },

  /** 课程类型标签 */
  getTypeLabel(project: string): string {
    if (project.includes('小组')) return '小组课'
    if (project.includes('1v1')) return '基础课'
    if (project.includes('充值')) return '充值'
    if (project.includes('斯诺克')) return '斯诺克'
    return '基础课'
  },

  /** 课程类型样式（对齐 service-record-card typeClass prop）*/
  getTypeClass(project: string): string {
    if (project.includes('充值')) return 'recharge'
    if (project.includes('小组')) return 'vip'
    if (project.includes('斯诺克')) return 'vip'
    return 'basic'
  },

  /** 模拟台号（后端未返回台号时的 fallback） */
  getTableNo(id: string): string {
    const tables = ['A12号台', '3号台', 'VIP1号房', '5号台', 'VIP2号房', '8号台']
    const idx = parseInt(id.replace(/\D/g, '') || '0', 10) % tables.length
    return tables[idx]
  },

  /** 切换到上一月 */
  onPrevMonth() {
    if (!this.data.canPrev || this.data.monthLoading) return
    let { currentYear, currentMonth, customerId } = this.data
    currentMonth--
    if (currentMonth < 1) {
      currentMonth = 12
      currentYear--
    }
    this.setData({ currentYear, currentMonth })
    this.loadMonthRecords(customerId, currentYear, currentMonth)
  },

  /** 切换到下一月 */
  onNextMonth() {
    if (!this.data.canNext || this.data.monthLoading) return
    let { currentYear, currentMonth, customerId } = this.data
    currentMonth++
    if (currentMonth > 12) {
      currentMonth = 1
      currentYear++
    }
    this.setData({ currentYear, currentMonth })
    this.loadMonthRecords(customerId, currentYear, currentMonth)
  },

  /** 下拉刷新 */
  onPullDownRefresh() {
    const { customerId, currentYear, currentMonth } = this.data
    this.loadCustomerInfo(customerId)
    this.loadMonthRecords(customerId, currentYear, currentMonth)
    setTimeout(() => wx.stopPullDownRefresh(), 600)
  },

  /** 重试 */
  onRetry() {
    const { customerId, currentYear, currentMonth } = this.data
    this.loadMonthRecords(customerId, currentYear, currentMonth)
  },

  /** 触底加载 */
  onReachBottom() {
    // 按月请求模式下暂不分页，后续可扩展
    if (this.data.loadingMore || !this.data.hasMore) return
    this.setData({ loadingMore: true })
    setTimeout(() => {
      this.setData({ loadingMore: false, hasMore: false })
    }, 500)
  },

  /** 查看/隐藏手机号 */
  onTogglePhone() {
    this.setData({ phoneVisible: !this.data.phoneVisible })
  },

  /** 复制手机号 */
  onCopyPhone() {
    const phone = this.data.customerPhoneFull
    wx.setClipboardData({
      data: phone,
      success: () => {
        wx.showToast({ title: '手机号码已复制', icon: 'none' })
      },
    })
  },

  /** 返回上一页 */
  onBack() {
    wx.navigateBack()
  },
})
