// 课程相关API接口
import { ApiRequest } from '../request'
import type {
  ApiResponse,
  PaginationResponse,
  Course,
  CourseCategory,
  Chapter,
  Lesson,
  LessonResource,
  CourseSection,
  CourseSectionListResponse,
  BackendCourseSection,
  BackendCourseSectionListResponse,
  Quiz,
  LearningProgress,
  SearchRequest,
  Instructor,
  BackendCourse,
  BackendCourseListResponse,
  CourseListRequest,
} from '../types'

/**
 * 课程API模块
 */
export class CourseApi {

  /**
   * 格式化时间戳为ISO字符串
   */
  private static formatTimestamp(timestamp: number | string | null | undefined): string {
    if (!timestamp) {
      return new Date().toISOString()
    }

    try {
      // 如果是字符串，尝试解析
      if (typeof timestamp === 'string') {
        const date = new Date(timestamp)
        return isNaN(date.getTime()) ? new Date().toISOString() : date.toISOString()
      }

      // 如果是数字时间戳
      if (timestamp <= 0) {
        return new Date().toISOString()
      }

      // 如果时间戳是秒级的，转换为毫秒级
      const ms = timestamp < 10000000000 ? timestamp * 1000 : timestamp
      const date = new Date(ms)

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return new Date().toISOString()
      }

      return date.toISOString()
    } catch (error) {
      console.error('时间戳格式化失败:', error)
      return new Date().toISOString()
    }
  }

  /**
   * 计算课程时长
   */
  private static calculateDuration(startTime: string, endTime: string): string {
    try {
      const start = new Date(startTime)
      const end = new Date(endTime)
      const diffMs = end.getTime() - start.getTime()
      const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24))
      return `${diffDays}天`
    } catch (error) {
      return '待定'
    }
  }
  // 获取课程列表 - 适配后端接口
  static async getCourses(params?: CourseListRequest): Promise<ApiResponse<PaginationResponse<Course>>> {
    try {
      console.log('调用课程列表API，参数:', params)

      // 构建查询参数，根据API文档的参数名称
      const queryParams: any = {}
      if (params?.categoryId) queryParams.categoryId = params.categoryId
      if (params?.difficulty !== undefined) queryParams.difficulty = params.difficulty
      if (params?.subject) queryParams.subject = params.subject
      if (params?.page) queryParams.page = params.page
      if (params?.pageSize) queryParams.pageSize = params.pageSize
      if (params?.keyword) queryParams.keyword = params.keyword

      // 调用后端API
      const response = await ApiRequest.get<BackendCourseListResponse>('/lesson/list', queryParams)
      console.log('课程列表API响应:', response)

      // 适配后端响应格式为前端期望的格式
      const adaptedCourses: Course[] = response.data.list.map((backendCourse: BackendCourse) => ({
        id: backendCourse.id,
        title: backendCourse.name,
        description: backendCourse.description,
        thumbnail: backendCourse.cover,
        coverImage: backendCourse.cover,
        price: parseFloat(backendCourse.price || '0'),
        originalPrice: parseFloat(backendCourse.price || '0'),
        currency: 'CNY',
        rating: 4.5, // 默认评分，后端没有返回
        ratingCount: 0, // 默认评分数量
        studentsCount: 0, // 默认学生数量
        duration: '待定', // 默认时长
        totalLessons: 0, // 默认课程数量
        level: this.mapDifficulty(backendCourse.difficulty || 0),
        language: 'zh-CN',
        category: {
          id: backendCourse.categoryId,
          name: this.getCategoryName(backendCourse.categoryId),
          slug: 'category-' + backendCourse.categoryId
        },
        tags: backendCourse.subject ? [backendCourse.subject] : [],
        skills: [],
        requirements: backendCourse.prerequisite ? [backendCourse.prerequisite] : [],
        objectives: backendCourse.target ? [backendCourse.target] : [],
        instructor: {
          id: backendCourse.teacherId || 0,
          name: backendCourse.school || '未知讲师',
          title: '讲师',
          bio: '',
          avatar: '',
          rating: 4.5,
          studentsCount: 0,
          coursesCount: 0,
          experience: '',
          education: [],
          certifications: []
        },
        status: 'published' as const,
        createdAt: this.formatTimestamp(backendCourse.createdTime),
        updatedAt: this.formatTimestamp(backendCourse.updatedTime),
        publishedAt: this.formatTimestamp(backendCourse.createdTime)
      }))

      const adaptedResponse: ApiResponse<PaginationResponse<Course>> = {
        code: response.code,
        message: response.message,
        data: {
          list: adaptedCourses,
          total: response.data.total,
          page: params?.page || 1,
          pageSize: params?.pageSize || 10,
          totalPages: Math.ceil(response.data.total / (params?.pageSize || 10))
        }
      }

      return adaptedResponse
    } catch (error) {
      throw error
    }
  }

  // 搜索课程
  static searchCourses(params: SearchRequest): Promise<ApiResponse<PaginationResponse<Course>>> {
    return ApiRequest.get('/courses/search', params)
  }

  // 获取热门课程
  static getPopularCourses(limit?: number): Promise<ApiResponse<Course[]>> {
    return ApiRequest.get('/courses/popular', { limit })
  }

  // 获取最新课程
  static getLatestCourses(limit?: number): Promise<ApiResponse<Course[]>> {
    return ApiRequest.get('/courses/latest', { limit })
  }

  // 获取推荐课程
  static getRecommendedCourses(userId?: number, limit?: number): Promise<ApiResponse<Course[]>> {
    return ApiRequest.get('/courses/recommended', { userId, limit })
  }

  // 获取课程详情 - 适配后端接口
  static async getCourseById(id: number): Promise<ApiResponse<Course>> {
    try {
      // 调用后端课程详情接口
      const response = await ApiRequest.get<BackendCourse>('/lesson/detail', { id })

      // 适配数据格式
      const adaptedCourse: Course = {
        id: response.data.id,
        title: response.data.name,
        description: response.data.description,
        content: response.data.outline, // 使用 outline 作为课程内容
        thumbnail: response.data.cover,
        coverImage: response.data.cover,
        price: parseFloat(response.data.price || '0'),
        originalPrice: parseFloat(response.data.price || '0'),
        currency: 'CNY',
        rating: 4.5,
        ratingCount: 0,
        studentsCount: 0,
        duration: this.calculateDuration(response.data.startTime, response.data.endTime),
        totalLessons: 0,
        level: 'beginner' as const,
        language: 'zh-CN',
        category: {
          id: response.data.categoryId,
          name: '未分类',
          slug: 'uncategorized'
        },
        tags: [],
        skills: [],
        requirements: response.data.prerequisite ? [response.data.prerequisite] : [],
        objectives: response.data.target ? [response.data.target] : [],
        instructor: {
          id: response.data.teacherId || 0,
          name: response.data.school || '未知讲师',
          title: '讲师',
          bio: response.data.position || '',
          avatar: '',
          rating: 4.5,
          studentsCount: 0,
          coursesCount: 0,
          experience: response.data.arrangement || '',
          education: [],
          certifications: []
        },
        status: 'published' as const,
        createdAt: this.formatTimestamp(response.data.createdTime),
        updatedAt: this.formatTimestamp(response.data.updatedTime),
        publishedAt: response.data.startTime
      }

      return {
        code: response.code,
        message: response.message,
        data: adaptedCourse
      }
    } catch (error) {
      throw error
    }
  }

  // 获取课程章节
  static getCourseChapters(courseId: number): Promise<ApiResponse<Chapter[]>> {
    return ApiRequest.get(`/courses/${courseId}/chapters`)
  }

  // 获取课程所有课时
  static getCourseLessons(courseId: number): Promise<ApiResponse<Lesson[]>> {
    return ApiRequest.get(`/courses/${courseId}/lessons`)
  }

  // 获取章节详情
  static getChapterById(id: number): Promise<ApiResponse<Chapter>> {
    return ApiRequest.get(`/chapters/${id}`)
  }

  // 获取课时详情
  static getLessonById(id: number): Promise<ApiResponse<Lesson>> {
    return ApiRequest.get(`/lessons/${id}`)
  }

  // 获取课时资源
  static getLessonResources(lessonId: number): Promise<ApiResponse<LessonResource[]>> {
    return ApiRequest.get(`/lessons/${lessonId}/resources`)
  }

  // 获取课程分类
  static getCategories(): Promise<ApiResponse<CourseCategory[]>> {
    return ApiRequest.get('/categories')
  }

  // 获取分类下的课程
  static getCoursesByCategory(categoryId: number, params?: {
    page?: number
    pageSize?: number
    sortBy?: string
  }): Promise<ApiResponse<PaginationResponse<Course>>> {
    return ApiRequest.get(`/categories/${categoryId}/courses`, params)
  }

  // 报名课程
  static enrollCourse(courseId: number): Promise<ApiResponse<{
    enrollmentId: number
    message: string
  }>> {
    return ApiRequest.post(`/courses/${courseId}/enroll`)
  }

  // 取消报名
  static unenrollCourse(courseId: number): Promise<ApiResponse<null>> {
    return ApiRequest.delete(`/courses/${courseId}/enroll`)
  }

  // 获取课程章节列表
  static async getCourseSections(lessonId: number): Promise<ApiResponse<CourseSectionListResponse>> {
    try {
      console.log('尝试从API获取课程章节数据，课程ID:', lessonId)
      console.log('API请求URL: /lesson/section/list')
      console.log('API请求参数:', { lesson_id: lessonId.toString() })

      const backendResponse = await ApiRequest.get<BackendCourseSectionListResponse>('/lesson/section/list', { lesson_id: lessonId.toString() })
      console.log('章节API响应:', backendResponse)
      console.log('响应状态码:', backendResponse.code)
      console.log('响应消息:', backendResponse.message)
      console.log('原始章节数据:', backendResponse.data?.list)
      console.log('章节数据数量:', backendResponse.data?.list?.length || 0)

      // 检查数据是否存在
      if (!backendResponse.data || !backendResponse.data.list) {
        console.warn('API返回的数据结构不正确:', backendResponse.data)
        return {
          code: backendResponse.code,
          message: backendResponse.message,
          data: {
            list: [],
            timestamp: Date.now(),
            traceId: backendResponse.timestamp?.toString() || ''
          },
          timestamp: backendResponse.timestamp?.toString()
        }
      }

      // 适配数据格式
      const adaptedSections: CourseSection[] = backendResponse.data.list.map((section: BackendCourseSection) => ({
        id: section.id,
        lessonId: section.lessonId,
        outline: section.videoUrl, // 将videoUrl映射到outline
        name: section.name,
        parentId: section.parentId,
        sort: section.sortOrder, // 将sortOrder映射到sort
        level: section.level === 0 ? 1 : 0, // 转换level逻辑：API中0=子级，1=父级；前端中0=父级，1=子级
        revision: section.revision,
        createdAt: section.createdTime ? new Date(section.createdTime).getTime() : null,
        updatedAt: section.updatedTime ? new Date(section.updatedTime).getTime() : null,
        deletedAt: null,
        completed: false,
        duration: undefined
      }))

      console.log('适配后的章节数据:', adaptedSections)

      const adaptedResponse: ApiResponse<CourseSectionListResponse> = {
        code: backendResponse.code,
        message: backendResponse.message,
        data: {
          list: adaptedSections,
          timestamp: Date.now(),
          traceId: backendResponse.timestamp?.toString() || ''
        },
        timestamp: backendResponse.timestamp?.toString()
      }

      return adaptedResponse
    } catch (error) {
      console.error('章节API调用失败:', error)
      console.error('错误详情:', {
        message: (error as Error).message,
        stack: (error as Error).stack,
        response: (error as any).response?.data,
        status: (error as any).response?.status,
        statusText: (error as any).response?.statusText
      })

      // 重新抛出错误，不使用模拟数据
      throw error
    }
  }

  // 获取我的课程
  static getMyCourses(params?: {
    page?: number
    pageSize?: number
    status?: 'all' | 'in_progress' | 'completed'
  }): Promise<ApiResponse<PaginationResponse<Course>>> {
    return ApiRequest.get('/my-courses', params)
  }

  // 获取学习进度
  static getLearningProgress(courseId: number): Promise<ApiResponse<LearningProgress>> {
    return ApiRequest.get(`/courses/${courseId}/progress`)
  }

  // 更新学习进度
  static updateLearningProgress(data: {
    courseId: number
    lessonId: number
    progress: number
    timeSpent?: number
  }): Promise<ApiResponse<LearningProgress>> {
    return ApiRequest.post('/learning-progress', data)
  }

  // 标记课时完成
  static markLessonCompleted(lessonId: number): Promise<ApiResponse<null>> {
    return ApiRequest.post(`/lessons/${lessonId}/complete`)
  }

  // 获取课程测验
  static getCourseQuizzes(courseId: number): Promise<ApiResponse<Quiz[]>> {
    return ApiRequest.get(`/courses/${courseId}/quizzes`)
  }

  // 获取测验详情
  static getQuizById(id: number): Promise<ApiResponse<Quiz>> {
    return ApiRequest.get(`/quizzes/${id}`)
  }

  // 提交测验答案
  static submitQuizAnswers(quizId: number, answers: Array<{
    questionId: number
    answer: string | string[]
  }>): Promise<ApiResponse<{
    score: number
    totalScore: number
    passed: boolean
    correctAnswers: number
    totalQuestions: number
    results: Array<{
      questionId: number
      correct: boolean
      userAnswer: string | string[]
      correctAnswer: string | string[]
    }>
  }>> {
    return ApiRequest.post(`/quizzes/${quizId}/submit`, { answers })
  }

  // 获取测验结果
  static getQuizResults(quizId: number): Promise<ApiResponse<{
    attempts: Array<{
      id: number
      score: number
      totalScore: number
      passed: boolean
      submittedAt: string
    }>
    bestScore: number
    averageScore: number
    totalAttempts: number
  }>> {
    return ApiRequest.get(`/quizzes/${quizId}/results`)
  }

  // 下载课程资源
  static downloadResource(resourceId: number): Promise<void> {
    return ApiRequest.download(`/resources/${resourceId}/download`)
  }

  // 获取讲师信息
  static getInstructorById(id: number): Promise<ApiResponse<Instructor>> {
    return ApiRequest.get(`/instructors/${id}`)
  }

  // 获取讲师的课程
  static getInstructorCourses(instructorId: number, params?: {
    page?: number
    pageSize?: number
  }): Promise<ApiResponse<PaginationResponse<Course>>> {
    return ApiRequest.get(`/instructors/${instructorId}/courses`, params)
  }

  // 关注讲师
  static followInstructor(instructorId: number): Promise<ApiResponse<null>> {
    return ApiRequest.post(`/instructors/${instructorId}/follow`)
  }

  // 取消关注讲师
  static unfollowInstructor(instructorId: number): Promise<ApiResponse<null>> {
    return ApiRequest.delete(`/instructors/${instructorId}/follow`)
  }

  // 获取课程统计信息
  static getCourseStats(courseId: number): Promise<ApiResponse<{
    totalStudents: number
    totalLessons: number
    totalDuration: string
    averageRating: number
    completionRate: number
    enrollmentTrend: Array<{
      date: string
      count: number
    }>
  }>> {
    return ApiRequest.get(`/courses/${courseId}/stats`)
  }

  // 预览课程（免费课时）
  static previewCourse(courseId: number): Promise<ApiResponse<{
    freeLessons: Lesson[]
    previewVideo?: string
  }>> {
    return ApiRequest.get(`/courses/${courseId}/preview`)
  }

  // 获取相关课程推荐
  static getRelatedCourses(courseId: number, limit?: number): Promise<ApiResponse<Course[]>> {
    return ApiRequest.get(`/courses/${courseId}/related`, { limit })
  }

  // 检查课程访问权限
  static checkCourseAccess(courseId: number): Promise<ApiResponse<{
    hasAccess: boolean
    reason?: string
    expiresAt?: string
  }>> {
    return ApiRequest.get(`/courses/${courseId}/access`)
  }

  // 辅助方法：映射难度等级
  private static mapDifficulty(difficulty: number): 'beginner' | 'intermediate' | 'advanced' {
    switch (difficulty) {
      case 0:
        return 'beginner'
      case 1:
        return 'intermediate'
      case 2:
        return 'advanced'
      default:
        return 'beginner'
    }
  }

  // 辅助方法：获取分类名称
  private static getCategoryName(categoryId: number): string {
    // 这里可以根据categoryId返回对应的分类名称
    // 暂时返回默认值，后续可以通过分类API获取
    const categoryMap: { [key: number]: string } = {
      1: '信息技术',
      2: '数学',
      3: '物理',
      4: '化学',
      5: '生物'
    }
    return categoryMap[categoryId] || '其他'
  }
}

export default CourseApi
