// 时间范围类型
export type TimeRange = 'today' | 'yesterday' | 'week' | 'month' | 'quarter' | 'year'

// 统计对比接口
export interface StatsComparison {
  current: number
  previous: number
  growthRate: number
  trend: 'up' | 'down' | 'stable'
  timeRange: TimeRange
  // 详细信息
  unit?: string
  significance?: 'high' | 'medium' | 'low'
  confidence?: number
}

// 系统统计接口
export interface SystemStats {
  totalUsers: number
  activeUsers: number
  newUsersToday: number
  newUsersThisWeek: number
  newUsersThisMonth: number
  totalActivities: number
  activeActivities: number
  completedActivities: number
  totalAnimals: number
  adoptedAnimals: number
  availableAnimals: number
  totalOrders: number
  pendingOrders: number
  completedOrders: number
  cancelledOrders: number
  totalRevenue: number
  todayRevenue: number
  weekRevenue: number
  monthRevenue: number
  systemUptime: string
  averageResponseTime: number
  errorRate: number
  serverLoad: number
  // 扩展信息
  databaseSize?: number
  cacheHitRate?: number
  apiCalls?: number
  concurrentUsers?: number
  // 性能指标
  pageLoadTime?: number
  apiResponseTime?: number
  databaseQueryTime?: number
  // 资源使用
  memoryUsage?: number
  cpuUsage?: number
  diskUsage?: number
  networkUsage?: number
}

// 用户统计接口
export interface UserStats {
  totalUsers: number
  activeUsers: number
  newUsers: {
    today: number
    yesterday: number
    thisWeek: number
    lastWeek: number
    thisMonth: number
    lastMonth: number
  }
  userGrowthRate: number
  userRetentionRate: number
  userChurnRate: number
  userDemographics: {
    ageDistribution: Record<string, number>
    genderDistribution: Record<string, number>
    locationDistribution: Record<string, number>
    // 扩展信息
    educationDistribution?: Record<string, number>
    occupationDistribution?: Record<string, number>
    incomeDistribution?: Record<string, number>
  }
  userActivity: {
    dailyActiveUsers: number
    weeklyActiveUsers: number
    monthlyActiveUsers: number
    averageSessionDuration: number
    averageSessionsPerUser: number
    // 行为指标
    pagesPerSession?: number
    bounceRate?: number
    returnRate?: number
  }
  userBehavior: {
    averageActivitiesPerUser: number
    averageAnimalsAdopted: number
    averageOrdersPerUser: number
    conversionRate: number
    engagementRate: number
    // 参与度指标
    contentCreationRate?: number
    socialInteractionRate?: number
    referralRate?: number
  }
  // 用户生命周期
  userLifetimeValue: number
  userAcquisitionCost: number
  userRetentionCost: number
  // 用户满意度
  userSatisfactionScore?: number
  netPromoterScore?: number
  customerEffortScore?: number
}

// 活动统计接口
export interface ActivityStats {
  totalActivities: number
  activeActivities: number
  completedActivities: number
  cancelledActivities: number
  pendingActivities: number
  activityGrowthRate: number
  participationStats: {
    totalParticipants: number
    averageParticipantsPerActivity: number
    repeatParticipants: number
    participationRate: number
    // 参与度详情
    maleParticipants?: number
    femaleParticipants?: number
    ageDistribution?: Record<string, number>
    locationDistribution?: Record<string, number>
  }
  revenueStats: {
    totalRevenue: number
    averageRevenuePerActivity: number
    revenueGrowthRate: number
    refundRate: number
    // 收入详情
    ticketRevenue?: number
    serviceRevenue?: number
    productRevenue?: number
    commissionRevenue?: number
  }
  categoryDistribution: Record<string, number>
  locationDistribution: Record<string, number>
  timeDistribution: Record<string, number>
  organizerPerformance: {
    topOrganizers: Array<{
      organizerId: number
      name: string
      activityCount: number
      revenue: number
      rating?: number
      completionRate?: number
    }>
    averageRating: number
    completionRate: number
    cancellationRate: number
    // 组织者指标
    organizerSatisfaction?: number
    organizerRetention?: number
    organizerGrowth?: number
  }
  // 活动质量指标
  activityQualityScore?: number
  participantSatisfaction?: number
  safetyIncidents?: number
  // 营销效果
  marketingROI?: number
  acquisitionCost?: number
  conversionRate?: number
}

// 动物统计接口
export interface AnimalStats {
  totalAnimals: number
  adoptedAnimals: number
  availableAnimals: number
  adoptionRate: number
  adoptionGrowthRate: number
  animalTypes: Record<string, number>
  adoptionStats: {
    totalAdoptions: number
    averageAdoptionTime: number
    repeatAdoptions: number
    adoptionSuccessRate: number
    // 收养详情
    adoptionReasons?: Record<string, number>
    adoptionDuration?: Record<string, number>
    adoptionFrequency?: number
  }
  careStats: {
    totalCareRecords: number
    averageCareFrequency: number
    medicalCheckups: number
    vaccinationRate: number
    // 护理详情
    healthIssues?: number
    treatmentCost?: number
    careQuality?: number
  }
  locationDistribution: Record<string, number>
  popularAnimals: Array<{
    animalId: number
    name: string
    type: string
    adoptionCount: number
    viewCount: number
    likeCount?: number
    shareCount?: number
  }>
  revenueStats: {
    totalAdoptionRevenue: number
    averageAdoptionFee: number
    careProductRevenue: number
    totalRevenue: number
    // 收入详情
    donationRevenue?: number
    sponsorshipRevenue?: number
    merchandiseRevenue?: number
  }
  // 动物福利指标
  animalWelfareScore?: number
  healthIndex?: number
  happinessIndex?: number
  // 可持续发展
  environmentalImpact?: number
  communityEngagement?: number
  educationalValue?: number
}

// 订单统计接口
export interface OrderStats {
  totalOrders: number
  pendingOrders: number
  completedOrders: number
  cancelledOrders: number
  orderGrowthRate: number
  revenueStats: {
    totalRevenue: number
    averageOrderValue: number
    revenueGrowthRate: number
    refundAmount: number
    netRevenue: number
    // 收入构成
    productRevenue?: number
    serviceRevenue?: number
    taxAmount?: number
    shippingCost?: number
  }
  orderTypeDistribution: Record<string, number>
  paymentStats: {
    paymentMethods: Record<string, number>
    paymentSuccessRate: number
    averagePaymentTime: number
    refundRate: number
    // 支付详情
    fraudRate?: number
    chargebackRate?: number
    paymentCost?: number
  }
  customerStats: {
    repeatCustomers: number
    averageOrdersPerCustomer: number
    customerLifetimeValue: number
    acquisitionCost: number
    // 客户行为
    purchaseFrequency?: number
    basketSize?: number
    crossSellRate?: number
  }
  timeDistribution: Record<string, number>
  locationDistribution: Record<string, number>
  // 订单质量指标
  orderAccuracy?: number
  deliveryPerformance?: number
  customerSatisfaction?: number
  // 运营效率
  fulfillmentTime?: number
  inventoryTurnover?: number
  returnRate?: number
}

// 收入统计接口
export interface RevenueStats {
  totalRevenue: number
  revenueGrowthRate: number
  dailyRevenue: number
  weeklyRevenue: number
  monthlyRevenue: number
  revenueSources: Record<string, number>
  revenueTrends: {
    last7Days: number[]
    last30Days: number[]
    // 扩展趋势
    last90Days?: number[]
    last365Days?: number[]
    seasonalPatterns?: Record<string, number>
  }
  customerMetrics: {
    averageRevenuePerUser: number
    averageOrderValue: number
    purchaseFrequency: number
    customerLifetimeValue: number
    // 客户价值
    retentionValue?: number
    acquisitionValue?: number
    referralValue?: number
  }
  geographicDistribution: Record<string, number>
  productPerformance: {
    topProducts: Array<{
      productId: number
      name: string
      revenue: number
      orders: number
      profit?: number
      margin?: number
    }>
    averageProfitMargin: number
    returnOnInvestment: number
    // 产品指标
    productPopularity?: number
    productSatisfaction?: number
    productRetention?: number
  }
  // 财务指标
  grossProfit?: number
  operatingProfit?: number
  netProfit?: number
  cashFlow?: number
  // 预算与实际
  budgetVariance?: number
  forecastAccuracy?: number
  // 税务信息
  taxLiability?: number
  taxCompliance?: number
}

// 仪表板指标接口
export interface DashboardMetrics {
  keyMetrics: {
    totalUsers: number
    activeUsers: number
    totalActivities: number
    totalOrders: number
    totalRevenue: number
    adoptionRate: number
    // 核心指标
    conversionRate?: number
    engagementRate?: number
    retentionRate?: number
  }
  growthMetrics: {
    userGrowth: number
    activityGrowth: number
    orderGrowth: number
    revenueGrowth: number
    // 增长详情
    organicGrowth?: number
    paidGrowth?: number
    referralGrowth?: number
  }
  performanceMetrics: {
    systemUptime: string
    averageResponseTime: number
    errorRate: number
    conversionRate: number
    // 性能详情
    pageSpeed?: number
    apiAvailability?: number
    databasePerformance?: number
  }
  recentActivities: Array<{
    type: string
    action: string
    count: number
    time: string
    // 活动详情
    details?: string
    priority?: 'high' | 'medium' | 'low'
  }>
  alerts: Array<{
    level: 'critical' | 'warning' | 'info' | 'success'
    message: string
    time: string
    // 警报详情
    source?: string
    affectedComponents?: string[]
    resolution?: string
  }>
  // 趋势数据
  trends: {
    userTrend: number[]
    revenueTrend: number[]
    activityTrend: number[]
    orderTrend: number[]
  }
  // 预测数据
  forecasts: {
    userForecast: number[]
    revenueForecast: number[]
    activityForecast: number[]
    orderForecast: number[]
  }
  // 比较数据
  comparisons: {
    vsPreviousPeriod: Record<string, StatsComparison>
    vsIndustryAverage: Record<string, StatsComparison>
    vsCompetitors: Record<string, StatsComparison>
  }
}

// 统计导出参数接口
export interface StatsExportParams {
  type: 'users' | 'activities' | 'animals' | 'orders' | 'revenue' | 'system'
  format: 'csv' | 'excel' | 'json' | 'pdf'
  timeRange: TimeRange
  fields: string[]
  filters?: Record<string, any>
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

// 统计查询参数接口
export interface StatsQueryParams {
  metric: string
  dimensions?: string[]
  filters?: Record<string, any>
  timeRange: TimeRange
  compareWith?: TimeRange
  granularity?: 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'
  limit?: number
  offset?: number
}

// 统计响应接口
export interface StatsResponse {
  data: any[]
  total: number
  timeRange: TimeRange
  generatedAt: string
  metadata: {
    query: StatsQueryParams
    processingTime: number
    dataFreshness: string
    confidence: number
  }
}

// 统计预警配置接口
export interface StatsAlertConfig {
  metric: string
  threshold: number
  condition: 'above' | 'below' | 'equal' | 'change'
  timeRange: TimeRange
  severity: 'critical' | 'warning' | 'info'
  notificationChannels: string[]
  recipients: string[]
  cooldownPeriod: number
  // 高级配置
  aggregation?: string
  windowSize?: number
  minimumSamples?: number
}

// 统计报告接口
export interface StatsReport {
  id: string
  title: string
  type: 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly' | 'custom'
  period: string
  metrics: Record<string, any>
  insights: string[]
  recommendations: string[]
  generatedAt: string
  // 报告详情
  executiveSummary?: string
  detailedAnalysis?: string
  visualizations?: any[]
  attachments?: string[]
  // 分发信息
  recipients?: string[]
  deliveryStatus?: 'pending' | 'sent' | 'delivered' | 'failed'
  // 安全信息
  accessLevel?: 'public' | 'internal' | 'confidential'
  retentionPolicy?: string
}