import { defineStore } from 'pinia'
import { ref } from 'vue'
import type {
  SystemStats,
  UserStats,
  ActivityStats,
  AnimalStats,
  OrderStats,
  RevenueStats,
  TimeRange,
  StatsComparison,
  DashboardMetrics
} from '../../types/stats'

// 模拟数据 - 系统统计
const mockSystemStats: SystemStats = {
  totalUsers: 12560,
  activeUsers: 8560,
  newUsersToday: 125,
  newUsersThisWeek: 890,
  newUsersThisMonth: 3450,
  totalActivities: 2560,
  activeActivities: 1250,
  completedActivities: 890,
  totalAnimals: 560,
  adoptedAnimals: 320,
  availableAnimals: 240,
  totalOrders: 4560,
  pendingOrders: 120,
  completedOrders: 4320,
  cancelledOrders: 120,
  totalRevenue: 125600,
  todayRevenue: 2560,
  weekRevenue: 17890,
  monthRevenue: 56780,
  systemUptime: '99.95%',
  averageResponseTime: 120,
  errorRate: 0.05,
  serverLoad: 45.2
}

// 模拟数据 - 用户统计
const mockUserStats: UserStats = {
  totalUsers: 12560,
  activeUsers: 8560,
  newUsers: {
    today: 125,
    yesterday: 110,
    thisWeek: 890,
    lastWeek: 780,
    thisMonth: 3450,
    lastMonth: 2980
  },
  userGrowthRate: 15.8,
  userRetentionRate: 78.5,
  userChurnRate: 5.2,
  userDemographics: {
    ageDistribution: {
      '18-24': 25.6,
      '25-34': 38.9,
      '35-44': 20.1,
      '45-54': 10.2,
      '55+': 5.2
    },
    genderDistribution: {
      male: 58.3,
      female: 40.1,
      other: 1.6
    },
    locationDistribution: {
      '北京': 18.5,
      '上海': 15.2,
      '广州': 12.8,
      '深圳': 11.5,
      '其他': 42.0
    }
  },
  userActivity: {
    dailyActiveUsers: 8560,
    weeklyActiveUsers: 23450,
    monthlyActiveUsers: 56780,
    averageSessionDuration: 12.5,
    averageSessionsPerUser: 3.2
  },
  userBehavior: {
    averageActivitiesPerUser: 2.1,
    averageAnimalsAdopted: 0.8,
    averageOrdersPerUser: 3.6,
    conversionRate: 28.5,
    engagementRate: 45.2
  },
  userLifetimeValue: 156.8,
  userAcquisitionCost: 25.4,
  userRetentionCost: 12.3
}

// 模拟数据 - 活动统计
const mockActivityStats: ActivityStats = {
  totalActivities: 2560,
  activeActivities: 1250,
  completedActivities: 890,
  cancelledActivities: 120,
  pendingActivities: 300,
  activityGrowthRate: 22.5,
  participationStats: {
    totalParticipants: 12560,
    averageParticipantsPerActivity: 4.9,
    repeatParticipants: 45.2,
    participationRate: 68.9
  },
  revenueStats: {
    totalRevenue: 125600,
    averageRevenuePerActivity: 49.1,
    revenueGrowthRate: 28.3,
    refundRate: 3.2
  },
  categoryDistribution: {
    travel: 35.6,
    movie: 18.9,
    dinner: 15.2,
    game: 12.8,
    sports: 8.5,
    study: 6.3,
    other: 2.7
  },
  locationDistribution: {
    '北京': 22.5,
    '上海': 18.9,
    '广州': 15.6,
    '深圳': 12.8,
    '其他': 30.2
  },
  timeDistribution: {
    '00-06': 5.2,
    '06-12': 25.6,
    '12-18': 35.8,
    '18-24': 33.4
  },
  organizerPerformance: {
    topOrganizers: [
      { organizerId: 101, name: '旅行达人小王', activityCount: 45, revenue: 12500 },
      { organizerId: 102, name: '电影爱好者小李', activityCount: 38, revenue: 9800 },
      { organizerId: 103, name: '美食家小张', activityCount: 32, revenue: 7600 }
    ],
    averageRating: 4.5,
    completionRate: 89.2,
    cancellationRate: 5.8
  }
}

// 模拟数据 - 动物统计
const mockAnimalStats: AnimalStats = {
  totalAnimals: 560,
  adoptedAnimals: 320,
  availableAnimals: 240,
  adoptionRate: 57.1,
  adoptionGrowthRate: 18.9,
  animalTypes: {
    dog: 35.6,
    cat: 28.9,
    sheep: 15.2,
    cow: 8.5,
    chicken: 6.3,
    other: 5.5
  },
  adoptionStats: {
    totalAdoptions: 320,
    averageAdoptionTime: 3.2,
    repeatAdoptions: 12.5,
    adoptionSuccessRate: 92.8
  },
  careStats: {
    totalCareRecords: 12560,
    averageCareFrequency: 2.5,
    medicalCheckups: 456,
    vaccinationRate: 89.5
  },
  locationDistribution: {
    '北京农场': 25.6,
    '上海牧场': 18.9,
    '广州养殖场': 15.2,
    '深圳农场': 12.8,
    '其他': 27.5
  },
  popularAnimals: [
    { animalId: 1, name: '小白', type: 'dog', adoptionCount: 15, viewCount: 1250 },
    { animalId: 2, name: '小花', type: 'cat', adoptionCount: 12, viewCount: 980 },
    { animalId: 3, name: '小羊', type: 'sheep', adoptionCount: 10, viewCount: 760 }
  ],
  revenueStats: {
    totalAdoptionRevenue: 45600,
    averageAdoptionFee: 142.5,
    careProductRevenue: 12500,
    totalRevenue: 58100
  }
}

// 模拟数据 - 订单统计
const mockOrderStats: OrderStats = {
  totalOrders: 4560,
  pendingOrders: 120,
  completedOrders: 4320,
  cancelledOrders: 120,
  orderGrowthRate: 25.8,
  revenueStats: {
    totalRevenue: 125600,
    averageOrderValue: 27.5,
    revenueGrowthRate: 32.1,
    refundAmount: 2560,
    netRevenue: 123040
  },
  orderTypeDistribution: {
    activity: 45.6,
    adoption: 28.9,
    flower: 15.2,
    product: 8.5,
    other: 2.8
  },
  paymentStats: {
    paymentMethods: {
      wechat: 58.9,
      alipay: 35.2,
      bank: 4.2,
      other: 1.7
    },
    paymentSuccessRate: 98.5,
    averagePaymentTime: 2.1,
    refundRate: 3.2
  },
  customerStats: {
    repeatCustomers: 45.6,
    averageOrdersPerCustomer: 3.2,
    customerLifetimeValue: 156.8,
    acquisitionCost: 25.4
  },
  timeDistribution: {
    '00-06': 8.5,
    '06-12': 22.6,
    '12-18': 35.8,
    '18-24': 33.1
  },
  locationDistribution: {
    '北京': 20.5,
    '上海': 18.2,
    '广州': 15.8,
    '深圳': 13.5,
    '其他': 32.0
  }
}

// 模拟数据 - 收入统计
const mockRevenueStats: RevenueStats = {
  totalRevenue: 125600,
  revenueGrowthRate: 32.1,
  dailyRevenue: 2560,
  weeklyRevenue: 17890,
  monthlyRevenue: 56780,
  revenueSources: {
    activity: 45.6,
    adoption: 28.9,
    flower: 15.2,
    product: 8.5,
    other: 2.8
  },
  revenueTrends: {
    last7Days: [1250, 1380, 1560, 1420, 1680, 1920, 2560],
    last30Days: [
      1200, 1250, 1380, 1420, 1560, 1480, 1620, 1780, 1920, 2050,
      2180, 2250, 2380, 2450, 2560, 2680, 2750, 2850, 2920, 3050,
      3120, 3250, 3350, 3420, 3560, 3650, 3780, 3850, 3920, 4050
    ]
  },
  customerMetrics: {
    averageRevenuePerUser: 156.8,
    averageOrderValue: 27.5,
    purchaseFrequency: 3.2,
    customerLifetimeValue: 456.2
  },
  geographicDistribution: {
    '北京': 22.5,
    '上海': 19.8,
    '广州': 16.2,
    '深圳': 13.8,
    '其他': 27.7
  },
  productPerformance: {
    topProducts: [
      { productId: 1, name: '西藏自驾游', revenue: 12500, orders: 256 },
      { productId: 2, name: '小羊认养', revenue: 9800, orders: 189 },
      { productId: 3, name: '玫瑰花束', revenue: 7600, orders: 152 }
    ],
    averageProfitMargin: 35.2,
    returnOnInvestment: 45.8
  }
}

// 模拟数据 - 仪表板指标
const mockDashboardMetrics: DashboardMetrics = {
  keyMetrics: {
    totalUsers: 12560,
    activeUsers: 8560,
    totalActivities: 2560,
    totalOrders: 4560,
    totalRevenue: 125600,
    adoptionRate: 57.1,
    conversionRate: 28.5,
    engagementRate: 45.2,
    retentionRate: 78.5
  },
  growthMetrics: {
    userGrowth: 15.8,
    activityGrowth: 22.5,
    orderGrowth: 25.8,
    revenueGrowth: 32.1
  },
  performanceMetrics: {
    systemUptime: '99.95%',
    averageResponseTime: 120,
    errorRate: 0.05,
    conversionRate: 28.5
  },
  recentActivities: [
    { type: 'user', action: '注册', count: 125, time: '今天' },
    { type: 'activity', action: '创建', count: 45, time: '今天' },
    { type: 'order', action: '完成', count: 89, time: '今天' },
    { type: 'adoption', action: '认养', count: 12, time: '今天' }
  ],
  alerts: [
    { level: 'warning', message: '系统负载较高', time: '2小时前' },
    { level: 'info', message: '新版本发布可用', time: '5小时前' }
  ],
  trends: {
    userTrend: [1250, 1380, 1560, 1420, 1680, 1920, 2560],
    revenueTrend: [1200, 1250, 1380, 1420, 1560, 1480, 1620],
    activityTrend: [45, 52, 48, 56, 62, 58, 65],
    orderTrend: [89, 92, 85, 96, 102, 98, 112]
  },
  forecasts: {
    userForecast: [2800, 2950, 3100, 3250, 3400],
    revenueForecast: [4200, 4500, 4800, 5100, 5400],
    activityForecast: [70, 75, 80, 85, 90],
    orderForecast: [120, 130, 140, 150, 160]
  },
  comparisons: {
    vsPreviousPeriod: {
      userGrowth: { current: 15.8, previous: 12.5, growthRate: 26.4, trend: 'up', timeRange: 'month' },
      revenueGrowth: { current: 32.1, previous: 28.3, growthRate: 13.4, trend: 'up', timeRange: 'month' }
    },
    vsIndustryAverage: {
      userGrowth: { current: 15.8, previous: 10.2, growthRate: 54.9, trend: 'up', timeRange: 'month' },
      revenueGrowth: { current: 32.1, previous: 25.6, growthRate: 25.4, trend: 'up', timeRange: 'month' }
    },
    vsCompetitors: {
      userGrowth: { current: 15.8, previous: 14.2, growthRate: 11.3, trend: 'up', timeRange: 'month' },
      revenueGrowth: { current: 32.1, previous: 30.5, growthRate: 5.2, trend: 'up', timeRange: 'month' }
    }
  }
}

export const useStatsStore = defineStore('stats', () => {
  // 状态
  const systemStats = ref<SystemStats>(mockSystemStats)
  const userStats = ref<UserStats>(mockUserStats)
  const activityStats = ref<ActivityStats>(mockActivityStats)
  const animalStats = ref<AnimalStats>(mockAnimalStats)
  const orderStats = ref<OrderStats>(mockOrderStats)
  const revenueStats = ref<RevenueStats>(mockRevenueStats)
  const dashboardMetrics = ref<DashboardMetrics>(mockDashboardMetrics)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取系统统计
  const fetchSystemStats = async (timeRange?: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 模拟根据时间范围筛选数据
      let stats = { ...mockSystemStats }
      
      if (timeRange) {
        // 这里可以根据时间范围调整统计数据
        const growthFactor = timeRange === 'today' ? 1 : timeRange === 'week' ? 7 : 30
        stats.newUsersToday = Math.round(stats.newUsersToday * (timeRange === 'today' ? 1 : growthFactor / 30))
        stats.todayRevenue = Math.round(stats.todayRevenue * (timeRange === 'today' ? 1 : growthFactor / 30))
      }
      
      systemStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取系统统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取用户统计
  const fetchUserStats = async (timeRange?: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 600))
      
      let stats = { ...mockUserStats }
      
      if (timeRange) {
        const growthFactor = timeRange === 'today' ? 1 : timeRange === 'week' ? 7 : 30
        stats.newUsers.today = Math.round(stats.newUsers.today * (timeRange === 'today' ? 1 : growthFactor / 30))
        stats.newUsers.thisWeek = Math.round(stats.newUsers.thisWeek * (timeRange === 'week' ? 1 : growthFactor / 7))
      }
      
      userStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取用户统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取活动统计
  const fetchActivityStats = async (timeRange?: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 700))
      
      let stats = { ...mockActivityStats }
      
      if (timeRange) {
        const growthFactor = timeRange === 'today' ? 1 : timeRange === 'week' ? 7 : 30
        stats.totalActivities = Math.round(stats.totalActivities * growthFactor / 30)
      }
      
      activityStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取活动统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取动物统计
  const fetchAnimalStats = async (timeRange?: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      let stats = { ...mockAnimalStats }
      
      if (timeRange) {
        const growthFactor = timeRange === 'today' ? 1 : timeRange === 'week' ? 7 : 30
        stats.totalAnimals = Math.round(stats.totalAnimals * growthFactor / 30)
      }
      
      animalStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取动物统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取订单统计
  const fetchOrderStats = async (timeRange?: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 600))
      
      let stats = { ...mockOrderStats }
      
      if (timeRange) {
        const growthFactor = timeRange === 'today' ? 1 : timeRange === 'week' ? 7 : 30
        stats.totalOrders = Math.round(stats.totalOrders * growthFactor / 30)
      }
      
      orderStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取订单统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取收入统计
  const fetchRevenueStats = async (timeRange?: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 800))
      
      let stats = { ...mockRevenueStats }
      
      if (timeRange) {
        const growthFactor = timeRange === 'today' ? 1 : timeRange === 'week' ? 7 : 30
        stats.dailyRevenue = Math.round(stats.dailyRevenue * (timeRange === 'today' ? 1 : growthFactor / 30))
      }
      
      revenueStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取收入统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取仪表板指标
  const fetchDashboardMetrics = async () => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟实时数据更新
      const metrics = {
        ...mockDashboardMetrics,
        keyMetrics: {
          ...mockDashboardMetrics.keyMetrics,
          totalUsers: mockSystemStats.totalUsers,
          activeUsers: mockSystemStats.activeUsers,
          totalRevenue: mockSystemStats.totalRevenue
        }
      }
      
      dashboardMetrics.value = metrics
      return metrics
    } catch (err) {
      error.value = '获取仪表板指标失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取统计对比
  const fetchStatsComparison = async (type: 'users' | 'activities' | 'orders' | 'revenue', timeRange: TimeRange) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 600))
      
      let current: number
      let previous: number
      let growthRate: number
      
      switch (type) {
        case 'users':
          current = mockUserStats.newUsers[timeRange === 'today' ? 'today' : timeRange === 'week' ? 'thisWeek' : 'thisMonth']
          previous = mockUserStats.newUsers[timeRange === 'today' ? 'yesterday' : timeRange === 'week' ? 'lastWeek' : 'lastMonth']
          break
        case 'activities':
          current = mockActivityStats.totalActivities
          previous = Math.round(current * 0.85)
          break
        case 'orders':
          current = mockOrderStats.totalOrders
          previous = Math.round(current * 0.8)
          break
        case 'revenue':
          current = mockRevenueStats[timeRange === 'today' ? 'dailyRevenue' : timeRange === 'week' ? 'weeklyRevenue' : 'monthlyRevenue']
          previous = Math.round(current * 0.75)
          break
        default:
          current = 0
          previous = 0
      }
      
      growthRate = previous > 0 ? ((current - previous) / previous) * 100 : 0
      
      const comparison: StatsComparison = {
        current,
        previous,
        growthRate,
        trend: growthRate >= 0 ? 'up' : 'down',
        timeRange
      }
      
      return comparison
    } catch (err) {
      error.value = '获取统计对比失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 导出统计数据
  const exportStats = async (type: 'users' | 'activities' | 'animals' | 'orders' | 'revenue', format: 'csv' | 'excel') => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 1200))
      
      // 模拟导出操作
      const data = {
        users: mockUserStats,
        activities: mockActivityStats,
        animals: mockAnimalStats,
        orders: mockOrderStats,
        revenue: mockRevenueStats
      }[type]
      
      return {
        filename: `${type}_stats_${new Date().toISOString().split('T')[0]}.${format}`,
        data,
        format,
        exportedAt: new Date().toISOString()
      }
    } catch (err) {
      error.value = '导出统计数据失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 重置错误
  const clearError = () => {
    error.value = null
  }

  return {
    // 状态
    systemStats,
    userStats,
    activityStats,
    animalStats,
    orderStats,
    revenueStats,
    dashboardMetrics,
    loading,
    error,
    
    // 操作
    fetchSystemStats,
    fetchUserStats,
    fetchActivityStats,
    fetchAnimalStats,
    fetchOrderStats,
    fetchRevenueStats,
    fetchDashboardMetrics,
    fetchStatsComparison,
    exportStats,
    clearError
  }
})