import { request } from '../request'

// 课程相关接口
export interface Course {
  id: number
  name: string
  description?: string
  category: string
  status: string
  cover_image?: string
  duration_hours?: number
  difficulty_level?: number
  tags?: string[]
  is_featured: boolean
  student_count?: number
  is_new?: boolean
  created_at: string
  updated_at: string
}

export interface CourseCreate {
  name: string
  description?: string
  category: string
  status?: string
  cover_image?: string
  duration_hours?: number
  difficulty_level?: number
  tags?: string[]
  is_featured?: boolean
}

export interface CourseUpdate extends Partial<CourseCreate> {}

// 考试设置接口
export interface CourseExamSettings {
  id: number
  course_id: number
  single_choice_count: number
  multiple_choice_count: number
  true_false_count: number
  fill_blank_count: number
  essay_count: number
  duration_minutes: number
  difficulty_level: number
  passing_score: number
  is_enabled: boolean
  show_answer_immediately: boolean
  allow_retake: boolean
  max_retake_times?: number
}

export interface CourseExamSettingsUpdate extends Partial<Omit<CourseExamSettings, 'id' | 'course_id'>> {}

// 岗位分配接口
export interface CoursePositionAssignment {
  position_id: number
  course_type: 'required' | 'optional'
  priority?: number
}

export interface CoursePositionAssignmentInDB extends CoursePositionAssignment {
  id: number
  course_id: number
  position_name?: string
  position_description?: string
  member_count?: number
}

// 课程资料接口
export interface CourseMaterial {
  id: number
  course_id: number
  name: string
  description?: string
  file_url: string
  file_type: string
  file_size: number
  sort_order: number
  created_at: string
}

export interface CourseMaterialCreate {
  name: string
  description?: string
  file_url: string
  file_type: string
  file_size: number
}

// 知识点接口
export interface KnowledgePoint {
  id: number
  course_id: number
  material_id?: number
  name: string
  description?: string
  type: string
  source: number
  topic_relation?: string
  created_at: string
}

export interface KnowledgePointCreate {
  name: string
  description?: string
  type: string
  source: number
  topic_relation?: string
  material_id?: number
}

export interface KnowledgePointUpdate extends Partial<KnowledgePointCreate> {}

/**
 * 课程管理API
 */
export const courseApi = {
  // 基本CRUD操作
  /**
   * 获取课程列表
   */
  list: (params?: {
    page?: number
    size?: number
    status?: string
    category?: string
    is_featured?: boolean
    keyword?: string
  }) => {
    return request.get<{
      items: Course[]
      total: number
      page: number
      page_size: number
      pages: number
    }>('/api/v1/courses', { params })
  },

  /**
   * 获取课程详情
   */
  get: (id: number) => {
    return request.get<Course>(`/api/v1/courses/${id}`)
  },

  /**
   * 创建课程
   */
  create: (data: CourseCreate) => {
    return request.post<Course>('/api/v1/courses', data)
  },

  /**
   * 更新课程
   */
  update: (id: number, data: CourseUpdate) => {
    return request.put<Course>(`/api/v1/courses/${id}`, data)
  },

  /**
   * 删除课程
   */
  delete: (id: number) => {
    return request.delete<boolean>(`/api/v1/courses/${id}`)
  },

  // 考试设置相关
  /**
   * 获取课程考试设置
   */
  getExamSettings: (courseId: number) => {
    return request.get<CourseExamSettings | null>(`/api/v1/courses/${courseId}/exam-settings`)
  },

  /**
   * 创建或更新课程考试设置
   */
  saveExamSettings: (courseId: number, data: CourseExamSettingsUpdate) => {
    return request.post<CourseExamSettings>(`/api/v1/courses/${courseId}/exam-settings`, data)
  },

  /**
   * 更新课程考试设置
   */
  updateExamSettings: (courseId: number, data: CourseExamSettingsUpdate) => {
    return request.put<CourseExamSettings>(`/api/v1/courses/${courseId}/exam-settings`, data)
  },

  // 岗位分配相关
  /**
   * 获取课程的岗位分配列表
   */
  getPositions: (courseId: number, courseType?: 'required' | 'optional') => {
    return request.get<CoursePositionAssignmentInDB[]>(`/api/v1/courses/${courseId}/positions`, {
      params: { course_type: courseType }
    })
  },

  /**
   * 批量分配课程到岗位
   */
  assignPositions: (courseId: number, assignments: CoursePositionAssignment[]) => {
    return request.post<CoursePositionAssignmentInDB[]>(`/api/v1/courses/${courseId}/positions`, assignments)
  },

  /**
   * 移除课程的岗位分配
   */
  removePosition: (courseId: number, positionId: number) => {
    return request.delete<boolean>(`/api/v1/courses/${courseId}/positions/${positionId}`)
  },

  // 课程资料相关
  /**
   * 添加课程资料
   */
  addMaterial: (courseId: number, data: CourseMaterialCreate) => {
    return request.post<CourseMaterial>(`/api/v1/courses/${courseId}/materials`, data)
  },

  /**
   * 获取课程资料列表
   */
  getMaterials: (courseId: number) => {
    return request.get<CourseMaterial[]>(`/api/v1/courses/${courseId}/materials`)
  },

  /**
   * 删除课程资料
   */
  deleteMaterial: (courseId: number, materialId: number) => {
    return request.delete<boolean>(`/api/v1/courses/${courseId}/materials/${materialId}`)
  },

  // 知识点相关
  /**
   * 获取课程的知识点列表
   */
  getKnowledgePoints: (courseId: number, materialId?: number) => {
    const params: Record<string, any> = {}
    if (materialId !== undefined) {
      params.material_id = materialId
    }
    return request.get<KnowledgePoint[]>(`/api/v1/courses/${courseId}/knowledge-points`, { params })
  },

  /**
   * 创建知识点
   */
  createKnowledgePoint: (courseId: number, data: KnowledgePointCreate) => {
    return request.post<KnowledgePoint>(`/api/v1/courses/${courseId}/knowledge-points`, data)
  },

  /**
   * 更新知识点
   */
  updateKnowledgePoint: (pointId: number, data: KnowledgePointUpdate) => {
    return request.put<KnowledgePoint>(`/api/v1/courses/knowledge-points/${pointId}`, data)
  },

  /**
   * 删除知识点
   */
  deleteKnowledgePoint: (pointId: number) => {
    return request.delete<boolean>(`/api/v1/courses/knowledge-points/${pointId}`)
  },

  // 资料知识点关联API（已废弃，使用getKnowledgePoints替代）
  /**
   * 获取资料关联的知识点列表（通过课程知识点API筛选）
   */
  getMaterialKnowledgePoints: (materialId: number, courseId?: number) => {
    if (courseId) {
      return courseApi.getKnowledgePoints(courseId, materialId)
    } else {
      // 如果没有courseId，直接调用资料知识点API
      return request.get<KnowledgePoint[]>(`/api/v1/courses/materials/${materialId}/knowledge-points`)
    }
  },

  /**
   * 移除资料与知识点的关联
   */
  removeMaterialKnowledgePoint: (materialId: number, knowledgePointId: number) => {
    return request.delete(`/api/v1/courses/materials/${materialId}/knowledge-points/${knowledgePointId}`)
  }
}

// 岗位API（获取可分配的岗位列表）
export const positionApi = {
  /**
   * 获取所有岗位列表（用于课程分配）
   */
  list: (params?: { page?: number; size?: number }) => {
    // 转换参数名：前端用size，后端用page_size
    const apiParams: { page?: number; page_size?: number } = {}
    if (params?.page) apiParams.page = params.page
    if (params?.size) apiParams.page_size = params.size
    
    return request.get<{
      items: Array<{
        id: number
        name: string
        description?: string
        parent_id?: number
        member_count?: number
        parent_name?: string
      }>
      total: number
      page: number
      page_size: number
      pages: number
    }>('/api/v1/admin/positions', { params: apiParams })
  }
}
