/**
 * 管理者功能模块 API
 */
import request from '../request'
import { CourseInfo, CourseMaterial } from '../trainee'
import { UserInfo } from '../auth'

// 团队统计数据
export interface TeamStats {
  totalMembers: number
  activeMembers: number
  averageProgress: number
  averageScore: number
  completedCourses: number
  totalCourses: number
  monthlyActiveUsers: number
  learningHours: number
}

// 团队成员详情
export interface TeamMemberDetail extends UserInfo {
  learningProgress: number
  averageScore: number
  completedCourses: number
  totalLearningHours: number
  lastActiveTime: string
  currentCourses: Array<{
    id: number
    name: string
    progress: number
  }>
}

// 学习任务
export interface LearningTask {
  id: number
  title: string
  description?: string
  courseIds: number[]
  assignedUserIds: number[]
  assignedTeamIds: number[]
  dueDate?: string
  priority: 'low' | 'medium' | 'high'
  status: 'draft' | 'published' | 'completed' | 'overdue'
  createdBy: number
  createdByName: string
  createdAt: string
  updatedAt: string
  completionRate: number
}

// 创建任务请求
export interface CreateTaskRequest {
  title: string
  description?: string
  courseIds: number[]
  assignedUserIds?: number[]
  assignedTeamIds?: number[]
  dueDate?: string
  priority: 'low' | 'medium' | 'high'
}

// 课程统计信息
export interface CourseStats {
  totalCourses: number
  publishedCourses: number
  draftCourses: number
  totalMaterials: number
  totalLearners: number
  averageRating: number
  completionRate: number
}

// 创建课程请求
export interface CreateCourseRequest {
  title: string
  description?: string
  category: string
  difficulty: 'beginner' | 'intermediate' | 'advanced'
  coverImage?: string
  tags?: string[]
  estimatedDuration?: number
  assignedPositions?: number[]
}

// 课程详情（管理视图）
export interface CourseDetailForManager extends CourseInfo {
  materials: CourseMaterial[]
  assignedPositions: Array<{
    id: number
    name: string
  }>
  learnerCount: number
  completionRate: number
  averageRating: number
  knowledgePoints: Array<{
    id: string
    title: string
    description: string
    difficulty: string
    tags: string[]
  }>
}

// 成长路径配置
export interface GrowthPathConfig {
  id: number
  positionId: number
  positionName: string
  name: string
  description?: string
  courses: Array<{
    courseId: number
    courseName: string
    isRequired: boolean
    prerequisites: number[]
    order: number
    estimatedDays: number
  }>
  totalCourses: number
  requiredCourses: number
  optionalCourses: number
  estimatedDays: number
  status: 'active' | 'inactive'
  createdAt: string
  updatedAt: string
}

// AI陪练场景（管理视图）
export interface PracticeSceneForManager {
  id: number
  name: string
  description: string
  category: string
  difficulty: 'easy' | 'medium' | 'hard'
  estimatedDuration: number
  usageCount: number
  averageRating: number
  status: 'active' | 'inactive'
  tags: string[]
  aiRole: string
  objectives: string[]
  keywords: string[]
  backgroundInfo: string
  botId?: string
  createdBy: number
  createdByName: string
  createdAt: string
  updatedAt: string
}

// 创建陪练场景请求
export interface CreatePracticeSceneRequest {
  name: string
  description: string
  category: string
  difficulty: 'easy' | 'medium' | 'hard'
  estimatedDuration: number
  tags?: string[]
  aiRole: string
  objectives: string[]
  keywords: string[]
  backgroundInfo: string
  botId?: string
}

// 学员考试成绩
export interface StudentExamScore {
  id: string
  studentId: number
  studentName: string
  studentEmail: string
  teamName?: string
  examName: string
  examType: string
  subject: string
  totalScore: number
  userScore: number
  accuracy: number
  duration: number
  examTime: string
  status: 'completed' | 'in_progress' | 'abandoned'
}

// 学员陪练记录
export interface StudentPracticeRecord {
  id: string
  studentId: number
  studentName: string
  studentEmail: string
  teamName?: string
  sceneName: string
  sceneCategory: string
  duration: number
  messageCount: number
  overallScore: number
  result: 'excellent' | 'good' | 'average' | 'needs_improvement'
  practiceTime: string
}

/**
 * 获取团队统计数据
 */
export const getTeamStats = (teamId?: number) => {
  const params = teamId ? { teamId } : {}
  return request.get<TeamStats>('/api/v1/manager/team-stats', { params })
}

/**
 * 获取团队成员详情列表
 */
export const getTeamMemberDetails = (params: {
  teamId?: number
  page?: number
  size?: number
  keyword?: string
} = {}) => {
  return request.get<{
    items: TeamMemberDetail[]
    total: number
    page: number
    size: number
  }>('/api/v1/manager/team-members', { params })
}

/**
 * 获取学习任务列表
 */
export const getLearningTasks = (params: {
  page?: number
  size?: number
  status?: string
  priority?: string
  keyword?: string
} = {}) => {
  return request.get<{
    items: LearningTask[]
    total: number
    page: number
    size: number
  }>('/api/v1/manager/tasks', { params })
}

/**
 * 创建学习任务
 */
export const createLearningTask = (data: CreateTaskRequest) => {
  return request.post<LearningTask>('/api/v1/manager/tasks', data)
}

/**
 * 更新学习任务
 */
export const updateLearningTask = (taskId: number, data: Partial<CreateTaskRequest>) => {
  return request.put<LearningTask>(`/api/v1/manager/tasks/${taskId}`, data)
}

/**
 * 删除学习任务
 */
export const deleteLearningTask = (taskId: number) => {
  return request.delete(`/api/v1/manager/tasks/${taskId}`)
}

/**
 * 发布学习任务
 */
export const publishLearningTask = (taskId: number) => {
  return request.post(`/api/v1/manager/tasks/${taskId}/publish`)
}

/**
 * 获取课程统计信息
 */
export const getCourseStats = () => {
  return request.get<CourseStats>('/api/v1/manager/course-stats')
}

/**
 * 获取课程列表（管理视图）
 */
export const getManagerCourses = (params: {
  page?: number
  size?: number
  category?: string
  status?: string
  keyword?: string
} = {}) => {
  return request.get<{
    items: CourseInfo[]
    total: number
    page: number
    size: number
  }>('/api/v1/manager/courses', { params })
}

/**
 * 创建课程
 */
export const createCourse = (data: CreateCourseRequest) => {
  return request.post<CourseInfo>('/api/v1/manager/courses', data)
}

/**
 * 获取课程详情（管理视图）
 */
export const getManagerCourseDetail = (courseId: number) => {
  return request.get<CourseDetailForManager>(`/api/v1/manager/courses/${courseId}`)
}

/**
 * 更新课程
 */
export const updateCourse = (courseId: number, data: Partial<CreateCourseRequest>) => {
  return request.put<CourseInfo>(`/api/v1/manager/courses/${courseId}`, data)
}

/**
 * 删除课程
 */
export const deleteCourse = (courseId: number) => {
  return request.delete(`/api/v1/manager/courses/${courseId}`)
}

/**
 * 上传课程材料
 */
export const uploadCourseMaterial = (courseId: number, file: File, title?: string) => {
  const formData = new FormData()
  formData.append('file', file)
  if (title) {
    formData.append('title', title)
  }
  return request.post<CourseMaterial>(`/api/v1/manager/courses/${courseId}/materials`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除课程材料
 */
export const deleteCourseMaterial = (courseId: number, materialId: number) => {
  return request.delete(`/api/v1/manager/courses/${courseId}/materials/${materialId}`)
}

/**
 * 分配课程到岗位
 */
export const assignCourseToPositions = (courseId: number, positionIds: number[]) => {
  return request.post(`/api/v1/manager/courses/${courseId}/assign-positions`, { positionIds })
}

/**
 * AI分析课程知识点
 */
export const analyzeKnowledgePoints = (courseId: number) => {
  return request.post(`/api/v1/manager/courses/${courseId}/analyze-knowledge`)
}

/**
 * 获取成长路径配置列表
 */
export const getGrowthPathConfigs = (params: {
  page?: number
  size?: number
  positionId?: number
  status?: string
} = {}) => {
  return request.get<{
    items: GrowthPathConfig[]
    total: number
    page: number
    size: number
  }>('/api/v1/manager/growth-paths', { params })
}

/**
 * 创建成长路径
 */
export const createGrowthPath = (data: {
  positionId: number
  name: string
  description?: string
  courses: Array<{
    courseId: number
    isRequired: boolean
    prerequisites?: number[]
    estimatedDays?: number
  }>
}) => {
  return request.post<GrowthPathConfig>('/api/v1/manager/growth-paths', data)
}

/**
 * 更新成长路径
 */
export const updateGrowthPath = (pathId: number, data: {
  name?: string
  description?: string
  courses?: Array<{
    courseId: number
    isRequired: boolean
    prerequisites?: number[]
    estimatedDays?: number
  }>
}) => {
  return request.put<GrowthPathConfig>(`/api/v1/manager/growth-paths/${pathId}`, data)
}

/**
 * 获取AI陪练场景列表（管理视图）
 */
export const getManagerPracticeScenes = (params: {
  page?: number
  size?: number
  category?: string
  difficulty?: string
  status?: string
  keyword?: string
} = {}) => {
  return request.get<{
    items: PracticeSceneForManager[]
    total: number
    page: number
    size: number
  }>('/api/v1/manager/practice-scenes', { params })
}

/**
 * 创建AI陪练场景
 */
export const createPracticeScene = (data: CreatePracticeSceneRequest) => {
  return request.post<PracticeSceneForManager>('/api/v1/manager/practice-scenes', data)
}

/**
 * 更新AI陪练场景
 */
export const updatePracticeScene = (sceneId: number, data: Partial<CreatePracticeSceneRequest>) => {
  return request.put<PracticeSceneForManager>(`/api/v1/manager/practice-scenes/${sceneId}`, data)
}

/**
 * 删除AI陪练场景
 */
export const deletePracticeScene = (sceneId: number) => {
  return request.delete(`/api/v1/manager/practice-scenes/${sceneId}`)
}

/**
 * 启用/禁用AI陪练场景
 */
export const togglePracticeSceneStatus = (sceneId: number, status: 'active' | 'inactive') => {
  return request.post(`/api/v1/manager/practice-scenes/${sceneId}/toggle-status`, { status })
}

/**
 * 复制AI陪练场景
 */
export const copyPracticeScene = (sceneId: number) => {
  return request.post<PracticeSceneForManager>(`/api/v1/manager/practice-scenes/${sceneId}/copy`)
}

/**
 * 获取学员考试成绩列表
 */
export const getStudentExamScores = (params: {
  page?: number
  size?: number
  studentId?: number
  teamId?: number
  examType?: string
  subject?: string
  startDate?: string
  endDate?: string
  keyword?: string
} = {}) => {
  return request.get<{
    items: StudentExamScore[]
    total: number
    page: number
    size: number
    statistics: {
      averageScore: number
      passRate: number
      totalExams: number
    }
  }>('/api/v1/manager/student-scores', { params })
}

/**
 * 获取学员陪练记录列表
 */
export const getStudentPracticeRecords = (params: {
  page?: number
  size?: number
  studentId?: number
  teamId?: number
  sceneId?: number
  result?: string
  startDate?: string
  endDate?: string
  keyword?: string
} = {}) => {
  return request.get<{
    items: StudentPracticeRecord[]
    total: number
    page: number
    size: number
    statistics: {
      totalSessions: number
      averageScore: number
      averageDuration: number
    }
  }>('/api/v1/manager/student-practice', { params })
}
