/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-29 | CUST-3 客户消费记录页面 | 新建页面，banner 复用 customer-detail，月份切换复用 customer-service-records，消费记录卡片复用 customer-detail |
*/
import { checkPageAccess } from '../../utils/auth-guard'
import { fetchCustomerConsumptionRecords } from '../../services/api'
// CHANGE 2026-05-02 | 业务时钟：sandbox 模式下用 business_year/month 替代 new Date()
import { getBusinessClock } from '../../utils/runtime-clock'

Page({
  data: {
    pageState: 'loading' as 'loading' | 'error' | 'normal',
    customerId: '',
    detail: {
      name: '',
      avatarChar: '',
      phone: '',
      balance: null as number | null,
      consumption60d: null as number | null,
      idealInterval: null as number | null,
      daysSinceVisit: null as number | null,
    },
    phoneMasked: '',
    phoneVisible: false,
    // 月份切换
    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,
    // 月度汇总
    visitCount: 0,
    consumeTotal: 0,
    rechargeTotal: 0,
    // 消费记录
    records: [] as any[],
    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,
    })
    this.loadMonthData(id, currentYear, currentMonth)
  },

  onShow() {
    checkPageAccess('pages/customer-records/customer-records')
  },

  async loadMonthData(customerId: string, year: number, month: number) {
    const monthLabel = `${year}年${month}月`
    this.setData({ monthLabel, records: [], monthLoading: true, pageState: 'loading' })
    wx.showLoading({ title: '加载中...', mask: true })

    try {
      const d = await fetchCustomerConsumptionRecords({ customerId, year, month })

      // Banner 数据（首次加载设置）
      if (d.name) {
        const phone = d.phoneFull || d.phone || ''
        this.setData({
          detail: {
            name: d.name || '',
            avatarChar: (d.name || '')[0] || '',
            phone: d.phoneFull || '',
            // CHANGE 2026-03-29 | Pydantic 把 consumption_60d → consumption60D（大写 D）
            balance: d.balance ?? null,
            consumption60d: d.consumption60D ?? d.consumption60d ?? null,
            idealInterval: d.idealInterval ?? null,
            daysSinceVisit: d.daysSinceVisit ?? null,
          },
          phoneMasked: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
        })
      }

      // 月度汇总
      const visitCount = d.visitCount ?? 0
      const consumeTotal = d.consumeTotal ?? 0
      const rechargeTotal = d.rechargeTotal ?? 0

      // 消费记录
      const records = d.records || []

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

      this.setData({
        visitCount,
        consumeTotal,
        rechargeTotal,
        records,
        canPrev,
        canNext,
        monthLoading: false,
        pageState: 'normal',
      })
    } catch (err) {
      console.error('[customer-records] loadMonthData failed:', err)
      this.setData({ monthLoading: false, pageState: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  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.loadMonthData(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.loadMonthData(customerId, currentYear, currentMonth)
  },

  onRetry() {
    const { customerId, currentYear, currentMonth } = this.data
    this.loadMonthData(customerId, currentYear, currentMonth)
  },

  onTogglePhone() {
    this.setData({ phoneVisible: !this.data.phoneVisible })
  },

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

  onPullDownRefresh() {
    const { customerId, currentYear, currentMonth } = this.data
    this.loadMonthData(customerId, currentYear, currentMonth)
    setTimeout(() => wx.stopPullDownRefresh(), 600)
  },
})
