/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | onShow 添加 checkPageAccess 权限守卫 |
| 2026-03-27 | 任务A 前端改造 | 修复数据转换（duration/income/timeRange/table/recordType），去掉 loadCustomerInfo 改从 records 响应取客户信息，新增 monthIncome 展示 |
*/
import { checkPageAccess } from '../../utils/auth-guard'
// CHANGE 2026-05-02 | 业务时钟：sandbox 模式下用 business_year/month 替代 new Date()
import { getBusinessClock } from '../../utils/runtime-clock'
// CHANGE 2026-03-27 | 任务A A5: 去掉 fetchCustomerDetail，客户信息从 fetchCustomerRecords 响应中获取
import { fetchCustomerRecords } from '../../services/api'
import { formatCount } from '../../utils/money'
import { formatHours } from '../../utils/time'

// CHANGE 2026-03-27 | 任务A: 对齐后端 ServiceRecordItem（CamelModel），移除废弃字段
/** 服务记录（对齐 task-detail ServiceRecord 结构，复用 service-record-card 组件） */
interface ServiceRecord {
  id: string
  date: string
  /** 台桌号/名称 */
  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: '--',
    /** 当前月份标签 */
    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',
    monthIncome: '¥0',
    monthRelation: '--',
    /** 当前月的服务记录 */
    records: [] as ServiceRecord[],
    /** 是否还有更多 */
    hasMore: false,
    /** 加载更多中 */
    loadingMore: false,
    /** 月份数据加载中（用于月份切换时的 loading 状态） */
    monthLoading: false,
  },

  async onLoad(options) {
    const id = options?.customerId || options?.id || ''
    // CHANGE 2026-05-02 | 默认当前年月走业务时钟，sandbox 模式按 sandbox_date 显示
    const clock = await getBusinessClock()
    const currentYear = clock.business_year
    const currentMonth = clock.business_month
    this.setData({
      customerId: id,
      currentYear,
      currentMonth,
      maxYearMonth: currentYear * 100 + currentMonth,
    })
    // CHANGE 2026-03-27 | 任务A A5: 客户信息从 fetchCustomerRecords 响应中获取，不再单独调 fetchCustomerDetail
    this.loadMonthRecords(id, currentYear, currentMonth)
  },

  onShow() {
    // 权限守卫：检查登录状态、账号禁用、角色权限
    checkPageAccess('pages/customer-service-records/customer-service-records')
  },

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

    // 清空列表 → 显示 loading
    this.setData({
      monthLabel,
      records: [],
      monthLoading: true,
      pageState: 'loading',
    })
    wx.showLoading({ title: '加载中...', mask: true })

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

      // CHANGE 2026-03-27 | 任务A A3: 从 records 响应中提取客户信息（省掉 fetchCustomerDetail 请求）
      const customerName = res.customerName || this.data.customerName || '客户'
      const customerPhone = res.customerPhone || ''
      const customerPhoneFull = res.customerPhoneFull || ''

      // CHANGE 2026-03-27 | 任务A A1: 修复数据转换，对齐后端 CamelModel 字段
      const records: ServiceRecord[] = rawRecords.map((r: any) => {
        // 日期格式化：优先用后端 timeRange，无值时从 date 提取日期部分
        const d = new Date(r.date)
        const m = d.getMonth() + 1
        const day = d.getDate()
        const dateLabel = `${m}月${day}日`
        // recordType 直接用后端返回值
        const recordType = r.recordType || 'course'
        const isRecharge = recordType === 'recharge'
        return {
          id: r.id || '',
          date: r.date || '',
          table: r.table || '',
          // type: 后端返回中文标签（如"陪打"/"超休"/"充值"），直接用
          type: r.type || '课程',
          // typeClass: 后端 typeClass 是 "tag-recharge"/"tag-course"，需映射为组件期望的 CSS class
          typeClass: this.mapTypeClass(r.recordType, r.type),
          recordType: recordType as 'course' | 'recharge',
          // duration 已是小时数，不再 /60
          durationHours: isRecharge ? 0 : (r.duration || 0),
          durationRaw: r.durationRaw || 0,
          // income 直接用后端已计算的到手金额
          income: r.income || 0,
          isEstimate: r.isEstimate || false,
          drinks: r.drinks || '',
          // displayDate 优先用后端 timeRange
          displayDate: isRecharge ? dateLabel : (r.timeRange ? `${dateLabel} ${r.timeRange}` : dateLabel),
        }
      })

      // CHANGE 2026-03-27 | 任务A A2: 月度统计直接用后端汇总值
      const monthCount = formatCount(res.monthCount ?? records.length, '次')
      // monthHours 后端已是小时数
      const monthHours = formatHours(res.monthHours ?? 0)
      // 月度到手收入
      const monthIncome = res.monthIncome != null ? `¥${Math.round(res.monthIncome)}` : '¥0'
      // 关系指数
      const monthRelation = res.relationIndex != null ? String(res.relationIndex) : '--'

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

      this.setData({
        // 客户信息（首次加载时设置，后续月份切换保持不变）
        customerName,
        customerInitial: customerName[0] || '?',
        customerPhone: customerPhone ? customerPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : this.data.customerPhone,
        customerPhoneFull: customerPhoneFull || this.data.customerPhoneFull,
        totalServiceCount: res.totalServiceCount ?? this.data.totalServiceCount,
        relationIndex: monthRelation,
        // 记录和统计
        records,
        monthCount,
        monthHours,
        monthIncome,
        monthRelation,
        canPrev,
        canNext,
        hasMore: res.hasMore || false,
        monthLoading: false,
        pageState: records.length > 0 ? 'normal' : 'normal',
      })
    } catch (err) {
      console.error('[customer-service-records] loadMonthRecords failed:', err)
      this.setData({
        monthLoading: false,
        pageState: 'error',
      })
    } finally {
      wx.hideLoading()
    }
  },

  // CHANGE 2026-03-27 | 任务A: 后端 type/recordType → 前端 CSS class 映射
  /** 根据 recordType 和 type（中文标签）映射为组件期望的 CSS class 后缀 */
  mapTypeClass(recordType?: string, typeLabel?: string): 'basic' | 'vip' | 'tip' | 'recharge' {
    if (recordType === 'recharge') return 'recharge'
    // 激励课/超休/打赏课 → vip 样式
    const label = typeLabel || ''
    if (label.includes('超休') || label.includes('激励') || label.includes('打赏') || label.includes('VIP')) {
      return 'vip'
    }
    return 'basic'
  },

  /** 切换到上一月 */
  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.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()
  },
})
