/**
 * 数据分析模块 API
 */
import request from '../request'

// 时间范围类型
export type TimeRange = '7d' | '30d' | '90d' | '1y' | 'custom'

// 统计数据基础类型
export interface StatisticItem {
  name: string
  value: number
  change?: number // 变化百分比
  trend?: 'up' | 'down' | 'stable'
}

// 时间序列数据点
export interface TimeSeriesPoint {
  date: string
  value: number
  label?: string
}

// 分布数据
export interface DistributionItem {
  category: string
  count: number
  percentage: number
  color?: string
}

// 系统整体统计
export interface SystemOverview {
  totalUsers: number
  activeUsers: number
  totalCourses: number
  totalExams: number
  totalPracticeSessions: number
  totalLearningHours: number
  averageScore: number
  completionRate: number
  userGrowth: TimeSeriesPoint[]
  activityTrend: TimeSeriesPoint[]
  popularCourses: Array<{
    id: number
    name: string
    learnerCount: number
    completionRate: number
    averageRating: number
  }>
}

// 用户学习分析
export interface UserLearningAnalysis {
  userId: number
  userName: string
  totalLearningHours: number
  completedCourses: number
  averageScore: number
  examCount: number
  practiceSessionCount: number
  abilityRadar: Array<{
    ability: string
    score: number
    maxScore: number
    level: 'beginner' | 'intermediate' | 'advanced' | 'expert'
  }>
  learningProgress: Array<{
    courseId: number
    courseName: string
    progress: number
    startDate: string
    lastActiveDate: string
    estimatedCompletionDate?: string
  }>
  performanceTrend: TimeSeriesPoint[]
  weeklyActivity: Array<{
    week: string
    hours: number
    sessions: number
  }>
  strongSubjects: string[]
  weakSubjects: string[]
  recommendations: Array<{
    type: 'course' | 'practice' | 'review'
    title: string
    reason: string
    priority: 'high' | 'medium' | 'low'
  }>
}

// 团队分析数据
export interface TeamAnalysis {
  teamId: number
  teamName: string
  memberCount: number
  activeMemberCount: number
  totalLearningHours: number
  averageProgress: number
  averageScore: number
  completedCourses: number
  memberPerformance: Array<{
    userId: number
    userName: string
    progress: number
    score: number
    rank: number
    learningHours: number
    lastActiveDate: string
  }>
  progressDistribution: DistributionItem[]
  scoreDistribution: DistributionItem[]
  activityTrend: TimeSeriesPoint[]
  topPerformers: Array<{
    userId: number
    userName: string
    score: number
    improvement: number
  }>
  needsAttention: Array<{
    userId: number
    userName: string
    issue: string
    severity: 'high' | 'medium' | 'low'
  }>
}

// 课程分析数据
export interface CourseAnalysis {
  courseId: number
  courseName: string
  totalLearners: number
  activeLearners: number
  completionRate: number
  averageRating: number
  averageCompletionTime: number
  difficultyDistribution: DistributionItem[]
  progressDistribution: DistributionItem[]
  ratingDistribution: DistributionItem[]
  learningTrend: TimeSeriesPoint[]
  dropOffPoints: Array<{
    materialId: number
    materialName: string
    dropOffRate: number
    avgTimeSpent: number
  }>
  feedback: Array<{
    userId: number
    userName: string
    rating: number
    comment: string
    date: string
  }>
  knowledgePointMastery: Array<{
    pointId: string
    pointName: string
    masteryRate: number
    avgAttempts: number
    difficulty: string
  }>
}

// 考试分析数据
export interface ExamAnalysis {
  totalExams: number
  totalParticipants: number
  averageScore: number
  passRate: number
  scoreDistribution: DistributionItem[]
  difficultyDistribution: DistributionItem[]
  subjectPerformance: Array<{
    subject: string
    averageScore: number
    passRate: number
    participantCount: number
  }>
  questionAnalysis: Array<{
    questionId: string
    questionType: string
    subject: string
    difficulty: string
    correctRate: number
    averageTime: number
    mistakeCount: number
  }>
  timeTrend: TimeSeriesPoint[]
  improvementTrend: TimeSeriesPoint[]
}

// AI陪练分析数据
export interface PracticeAnalysis {
  totalSessions: number
  totalParticipants: number
  averageScore: number
  averageDuration: number
  completionRate: number
  scenePopularity: Array<{
    sceneId: number
    sceneName: string
    sessionCount: number
    averageScore: number
    averageDuration: number
  }>
  performanceDistribution: DistributionItem[]
  skillImprovement: Array<{
    skill: string
    beforeScore: number
    afterScore: number
    improvement: number
  }>
  sessionTrend: TimeSeriesPoint[]
  userEngagement: Array<{
    userId: number
    userName: string
    sessionCount: number
    averageScore: number
    totalDuration: number
    lastSessionDate: string
  }>
}

/**
 * 获取系统整体统计
 */
export const getSystemOverview = (timeRange: TimeRange = '30d') => {
  return request.get<SystemOverview>('/api/v1/analytics/overview', {
    params: { timeRange }
  })
}

/**
 * 获取用户学习分析
 */
export const getUserLearningAnalysis = (userId?: number, timeRange: TimeRange = '30d') => {
  const params: any = { timeRange }
  if (userId) params.userId = userId
  return request.get<UserLearningAnalysis>('/api/v1/analytics/user-learning', { params })
}

/**
 * 获取团队分析数据
 */
export const getTeamAnalysis = (teamId?: number, timeRange: TimeRange = '30d') => {
  const params: any = { timeRange }
  if (teamId) params.teamId = teamId
  return request.get<TeamAnalysis>('/api/v1/analytics/team', { params })
}

/**
 * 获取课程分析数据
 */
export const getCourseAnalysis = (courseId?: number, timeRange: TimeRange = '30d') => {
  const params: any = { timeRange }
  if (courseId) params.courseId = courseId
  return request.get<CourseAnalysis>('/api/v1/analytics/course', { params })
}

/**
 * 获取考试分析数据
 */
export const getExamAnalysis = (params: {
  examType?: string
  subject?: string
  timeRange?: TimeRange
  courseId?: number
} = {}) => {
  return request.get<ExamAnalysis>('/api/v1/analytics/exam', { params })
}

/**
 * 获取AI陪练分析数据
 */
export const getPracticeAnalysis = (params: {
  sceneId?: number
  category?: string
  timeRange?: TimeRange
} = {}) => {
  return request.get<PracticeAnalysis>('/api/v1/analytics/practice', { params })
}

/**
 * 获取学习趋势数据
 */
export const getLearningTrends = (params: {
  type: 'user' | 'team' | 'course' | 'exam' | 'practice'
  id?: number
  metrics: string[]
  timeRange: TimeRange
  granularity?: 'day' | 'week' | 'month'
}) => {
  return request.get<{
    [metric: string]: TimeSeriesPoint[]
  }>('/api/v1/analytics/trends', { params })
}

/**
 * 获取能力雷达图数据
 */
export const getAbilityRadar = (userId?: number) => {
  const params = userId ? { userId } : {}
  return request.get<{
    categories: Array<{
      name: string
      score: number
      maxScore: number
      skills: Array<{
        name: string
        score: number
        maxScore: number
        level: string
      }>
    }>
    overallScore: number
    maxOverallScore: number
    lastUpdated: string
    comparison?: {
      teamAverage: number
      positionAverage: number
      improvement: number
    }
  }>('/api/v1/analytics/ability-radar', { params })
}

/**
 * 获取学习路径进度分析
 */
export const getLearningPathProgress = (userId?: number, pathId?: number) => {
  const params: any = {}
  if (userId) params.userId = userId
  if (pathId) params.pathId = pathId
  return request.get<{
    pathId: number
    pathName: string
    totalCourses: number
    completedCourses: number
    progress: number
    estimatedCompletionDate: string
    courses: Array<{
      courseId: number
      courseName: string
      isRequired: boolean
      isCompleted: boolean
      progress: number
      estimatedDays: number
      actualDays?: number
      prerequisites: number[]
      status: 'not_started' | 'in_progress' | 'completed' | 'blocked'
    }>
    milestones: Array<{
      name: string
      completedAt?: string
      isCompleted: boolean
      requiredCourses: number[]
    }>
  }>('/api/v1/analytics/learning-path-progress', { params })
}

/**
 * 获取排行榜数据
 */
export const getRankings = (params: {
  type: 'score' | 'progress' | 'activity' | 'improvement'
  scope: 'global' | 'team' | 'position'
  scopeId?: number
  timeRange: TimeRange
  limit?: number
}) => {
  return request.get<{
    rankings: Array<{
      rank: number
      userId: number
      userName: string
      userAvatar?: string
      teamName?: string
      value: number
      change?: number
      trend?: 'up' | 'down' | 'stable'
    }>
    currentUser?: {
      rank: number
      value: number
      change?: number
    }
    total: number
  }>('/api/v1/analytics/rankings', { params })
}

/**
 * 导出分析报告
 */
export const exportAnalysisReport = (params: {
  type: 'overview' | 'user' | 'team' | 'course' | 'exam' | 'practice'
  id?: number
  timeRange: TimeRange
  format: 'pdf' | 'excel' | 'csv'
  includeCharts?: boolean
}) => {
  return request.post<{
    downloadUrl: string
    fileName: string
    fileSize: number
    expiresAt: string
  }>('/api/v1/analytics/export', params)
}

/**
 * 获取实时数据
 */
export const getRealTimeData = () => {
  return request.get<{
    onlineUsers: number
    activeExams: number
    activePracticeSessions: number
    recentActivities: Array<{
      id: string
      type: 'login' | 'course_start' | 'exam_complete' | 'practice_complete'
      userId: number
      userName: string
      description: string
      timestamp: string
    }>
    systemLoad: {
      cpu: number
      memory: number
      storage: number
    }
  }>('/api/v1/analytics/realtime')
}
