import { mockCustomerDetail, mockCustomers } from '../../utils/mock-data'
import type { ConsumptionRecord } from '../../utils/mock-data'
import { sortByTimestamp } from '../../utils/sort'

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

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

  onLoad(options) {
    const id = options?.customerId || options?.id || ''
    this.setData({ customerId: id })
    this.loadData(id)
  },

  /** 加载数据 */
  loadData(id: string) {
    this.setData({ pageState: 'loading' })

    setTimeout(() => {
      // TODO: 替换为真实 API 调用
      const customer = mockCustomers.find((c) => c.id === id)
      const detail = customer
        ? { ...mockCustomerDetail, id: customer.id, name: customer.name }
        : mockCustomerDetail

      const allRecords = sortByTimestamp(detail.consumptionRecords || [], 'date') as ConsumptionRecord[]
      const name = detail.name || '客户'

      this.setData({
        customerName: name,
        customerInitial: name[0] || '?',
        allRecords,
        totalServiceCount: allRecords.length,
      })

      this.updateMonthView()
    }, 400)
  },

  /** 根据当前月份筛选并更新视图 */
  updateMonthView() {
    const { currentYear, currentMonth, allRecords } = this.data
    const monthLabel = `${currentYear}年${currentMonth}月`

    // 筛选当月记录
    const monthPrefix = `${currentYear}-${String(currentMonth).padStart(2, '0')}`
    const monthRecords = allRecords.filter((r) => r.date.startsWith(monthPrefix))

    // 转换为展示格式（对齐 task-detail ServiceRecord，复用 service-record-card 组件）
    // income / duration 均传原始数字，由组件统一加 ¥ 和 h
    const records: ServiceRecord[] = monthRecords.map((r) => {
      const d = new Date(r.date)
      const month = d.getMonth() + 1
      const day = d.getDate()
      const dateLabel = `${month}月${day}日`
      const timeRange = this.generateTimeRange(r.duration)
      const isRecharge = r.project.includes('充值')
      return {
        ...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',
        duration: isRecharge ? 0 : parseFloat((r.duration / 60).toFixed(1)),
        durationRaw: 0,
        income: r.amount,
        isEstimate: false,
        drinks: '',
        date: isRecharge ? dateLabel : `${dateLabel} ${timeRange}`,
      }
    })

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

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

    const isEmpty = records.length === 0 && allRecords.length === 0

    this.setData({
      monthLabel,
      records,
      monthCount,
      monthHours,
      canPrev,
      canNext,
      pageState: isEmpty ? 'empty' : 'normal',
    })
  },

  /** 生成模拟时间段 */
  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'
  },

  /** 模拟台号 */
  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) return
    let { currentYear, currentMonth } = this.data
    currentMonth--
    if (currentMonth < 1) {
      currentMonth = 12
      currentYear--
    }
    this.setData({ currentYear, currentMonth })
    this.updateMonthView()
  },

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

  /** 下拉刷新 */
  onPullDownRefresh() {
    this.loadData(this.data.customerId)
    setTimeout(() => wx.stopPullDownRefresh(), 600)
  },

  /** 重试 */
  onRetry() {
    this.loadData(this.data.customerId)
  },

  /** 触底加载 */
  onReachBottom() {
    // Mock 阶段数据有限，不做分页
    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()
  },
})
