// TODO: 联调时替换为真实 API 调用
import { initPageAiColor } from '../../utils/ai-color-manager'

/** 业绩明细项（本月/上月） */
interface IncomeItem {
  icon: string
  label: string
  desc: string
  value: string
}

/** 服务记录（按日期分组后的展示结构） */
interface ServiceRecord {
  customerName: string
  avatarChar: string
  avatarColor: string
  timeRange: string
  hours: string
  courseType: string
  courseTypeClass: string
  location: string
  income: string
}

interface DateGroup {
  date: string
  totalHours?: string
  totalIncome?: string
  records: ServiceRecord[]
}

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

    /** Banner 数据 */
    coachName: '小燕',
    coachRole: '助教',
    storeName: '广州朗朗桌球',
    monthlyIncome: '¥6,206',
    lastMonthIncome: '¥16,880',

    /** 收入档位 */
    currentTier: {
      basicRate: 80,
      incentiveRate: 95,
    },
    nextTier: {
      basicRate: 90,
      incentiveRate: 114,
    },
    upgradeHoursNeeded: 15,
    upgradeBonus: 800,

    /** 本月业绩明细 */
    incomeItems: [] as IncomeItem[],
    monthlyTotal: '¥6,950.5',

    /** 服务记录 */
    thisMonthRecords: [] as DateGroup[],
    thisMonthRecordsExpanded: false,
    /** 默认显示前 N 条日期组 */
    visibleRecordGroups: 2,

    /** 新客列表 */
    newCustomers: [] as Array<{ name: string; avatarChar: string; avatarColor: string; lastService: string; count: number }>,
    newCustomerExpanded: false,

    /** 常客列表 */
    regularCustomers: [] as Array<{ name: string; avatarChar: string; avatarColor: string; hours: number; income: string; count: number }>,
    regularCustomerExpanded: false,
  },

  onLoad() {
    // 初始化 AI 图标配色（蓝色 - 数据分析感）
    const { aiColor } = initPageAiColor('performance')
    this.setData({ aiColor })

    this.loadData()
  },

  loadData() {
    this.setData({ pageState: 'loading' })

    setTimeout(() => {
      try {
      // TODO: 替换为真实 API
      const incomeItems: IncomeItem[] = [
        { icon: '🎱', label: '基础课', desc: '80元/h × 75h', value: '¥6,000' },
        { icon: '⭐', label: '激励课', desc: '95.05元/h × 10h', value: '¥950.5' },
        { icon: '💰', label: '充值激励', desc: '客户充值返佣', value: '¥500' },
        { icon: '🏆', label: 'TOP3 销冠奖', desc: '全店业绩前三名奖励', value: '继续努力' },
      ]

      const gradients = [
        'blue', 'pink', 'teal', 'green',
        'orange', 'purple', 'violet', 'amber',
      ]

      // 模拟服务记录按日期分组
      const thisMonthRecords: DateGroup[] = [
        {
          date: '2月7日',
          totalHours: '4.0h',
          totalIncome: '¥350',
          records: [
            { customerName: '王先生', avatarChar: '王', avatarColor: gradients[0], timeRange: '20:00-22:00', hours: '2.0h', courseType: '基础课', courseTypeClass: 'tag-basic', location: '3号台', income: '¥160' },
            { customerName: '李女士', avatarChar: '李', avatarColor: gradients[1], timeRange: '16:00-18:00', hours: '2.0h', courseType: '包厢课', courseTypeClass: 'tag-vip', location: 'VIP1号房', income: '¥190' },
          ],
        },
        {
          date: '2月6日',
          totalHours: '2.0h',
          totalIncome: '¥160',
          records: [
            { customerName: '张先生', avatarChar: '张', avatarColor: gradients[2], timeRange: '19:00-21:00', hours: '2.0h', courseType: '基础课', courseTypeClass: 'tag-basic', location: '5号台', income: '¥160' },
          ],
        },
        {
          date: '2月5日',
          totalHours: '4.0h',
          totalIncome: '¥320',
          records: [
            { customerName: '陈女士', avatarChar: '陈', avatarColor: gradients[2], timeRange: '20:00-22:00', hours: '2.0h', courseType: '基础课', courseTypeClass: 'tag-basic', location: '2号台', income: '¥160' },
            { customerName: '赵先生', avatarChar: '赵', avatarColor: gradients[5], timeRange: '14:00-16:00', hours: '2.0h', courseType: '基础课', courseTypeClass: 'tag-basic', location: '7号台', income: '¥160' },
          ],
        },
        {
          date: '2月4日',
          totalHours: '4.0h',
          totalIncome: '¥350',
          records: [
            { customerName: '孙先生', avatarChar: '孙', avatarColor: gradients[6], timeRange: '19:00-21:00', hours: '2.0h', courseType: '包厢课', courseTypeClass: 'tag-vip', location: 'VIP2号房', income: '¥190' },
            { customerName: '吴女士', avatarChar: '吴', avatarColor: gradients[2], timeRange: '15:00-17:00', hours: '2.0h', courseType: '基础课', courseTypeClass: 'tag-basic', location: '1号台', income: '¥160' },
          ],
        },
      ]

      const newCustomers = [
        { name: '王先生', avatarChar: '王', avatarColor: gradients[0], lastService: '2月7日', count: 2 },
        { name: '李女士', avatarChar: '李', avatarColor: gradients[1], lastService: '2月7日', count: 1 },
        { name: '刘先生', avatarChar: '刘', avatarColor: gradients[4], lastService: '2月6日', count: 1 },
        { name: '周女士', avatarChar: '周', avatarColor: gradients[3], lastService: '2月5日', count: 1 },
        { name: '吴先生', avatarChar: '吴', avatarColor: gradients[7], lastService: '2月4日', count: 1 },
        { name: '郑女士', avatarChar: '郑', avatarColor: gradients[5], lastService: '2月3日', count: 1 },
        { name: '钱先生', avatarChar: '钱', avatarColor: gradients[6], lastService: '2月2日', count: 1 },
        { name: '冯女士', avatarChar: '冯', avatarColor: gradients[2], lastService: '2月1日', count: 1 },
      ]

      const regularCustomers = [
        { name: '张先生', avatarChar: '张', avatarColor: gradients[2], hours: 12, income: '¥960', count: 6 },
        { name: '陈女士', avatarChar: '陈', avatarColor: gradients[2], hours: 10, income: '¥800', count: 5 },
        { name: '赵先生', avatarChar: '赵', avatarColor: gradients[5], hours: 8, income: '¥640', count: 4 },
        { name: '孙先生', avatarChar: '孙', avatarColor: gradients[6], hours: 6, income: '¥570', count: 3 },
        { name: '杨女士', avatarChar: '杨', avatarColor: 'pink', hours: 6, income: '¥480', count: 3 },
        { name: '黄先生', avatarChar: '黄', avatarColor: 'amber', hours: 4, income: '¥380', count: 2 },
        { name: '林女士', avatarChar: '林', avatarColor: 'green', hours: 4, income: '¥320', count: 2 },
        { name: '徐先生', avatarChar: '徐', avatarColor: 'orange', hours: 2, income: '¥190', count: 1 },
      ]

      this.setData({
        pageState: 'normal',
        incomeItems,
        thisMonthRecords,
        newCustomers,
        regularCustomers,
      })
      } catch (_e) {
        this.setData({ pageState: 'error' })
      }
    }, 500)
  },

  /** 加载失败重试 */
  onRetry() {
    this.loadData()
  },

  /** 自定义导航栏返回 */
  onNavBack() {
    wx.navigateBack({ fail: () => wx.switchTab({ url: '/pages/task-list/task-list' }) })
  },

  /** 展开/收起本月服务记录 */
  toggleThisMonthRecords() {
    this.setData({ thisMonthRecordsExpanded: !this.data.thisMonthRecordsExpanded })
  },

  /** 查看全部 → 跳转业绩明细 */
  goToRecords() {
    wx.navigateTo({ url: '/pages/performance-records/performance-records' })
  },

  /** 展开/收起新客列表 */
  toggleNewCustomer() {
    this.setData({ newCustomerExpanded: !this.data.newCustomerExpanded })
  },

  /** 展开/收起常客列表 */
  toggleRegularCustomer() {
    this.setData({ regularCustomerExpanded: !this.data.regularCustomerExpanded })
  },

  /** 点击客户卡片 → 跳转任务详情 */
  onCustomerTap(e: WechatMiniprogram.TouchEvent) {
    const { name } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/task-detail/task-detail?customerName=${name}`,
      fail: () => wx.showToast({ title: '页面跳转失败', icon: 'none' }),
    })
  },

  /** 点击服务记录 → 跳转任务详情 */
  onRecordTap(e: WechatMiniprogram.TouchEvent) {
    const { customerName, taskId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/task-detail/task-detail?customerName=${customerName}${taskId ? `&taskId=${taskId}` : ''}`,
      fail: () => wx.showToast({ title: '页面跳转失败', icon: 'none' }),
    })
  },

  /** 点击收入概览卡片 → 跳转业绩记录 */
  onIncomeCardTap() {
    wx.navigateTo({ url: '/pages/performance-records/performance-records' })
  },
})
