<template>
  <div class="courses-page">
    <!-- 页面头部横幅 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">课程</h1>
        <p class="page-subtitle">在线教育产品课程体系</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <!-- 分类筛选区域 -->
        <div class="filter-section">
          <!-- 学科分类 -->
          <div class="filter-group">
            <span class="filter-label">类型：</span>
            <div class="filter-tags">
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '全部' }"
                @click="selectSubject('全部')"
              >全部</span>
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '必修课' }"
                @click="selectSubject('必修课')"
              >必修课</span>
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '高分课' }"
                @click="selectSubject('高分课')"
              >高分课</span>
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '名师课堂' }"
                @click="selectSubject('名师课堂')"
              >名师课堂</span>
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '训练营' }"
                @click="selectSubject('训练营')"
              >训练营</span>
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '无考试' }"
                @click="selectSubject('无考试')"
              >无考试</span>
              <span
                class="filter-tag"
                :class="{ active: selectedSubject === '专题讲座' }"
                @click="selectSubject('专题讲座')"
              >专题讲座</span>
            </div>
          </div>

          <!-- 专题分类第一行 -->
          <div class="filter-group">
            <span class="filter-label">专题：</span>
            <div class="filter-tags">
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '全部' }"
                @click="selectMajor('全部')"
              >全部</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '学科教研' }"
                @click="selectMajor('学科教研')"
              >学科教研</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '班级管理' }"
                @click="selectMajor('班级管理')"
              >班级管理</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '通识技能' }"
                @click="selectMajor('通识技能')"
              >通识技能</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '信息素养' }"
                @click="selectMajor('信息素养')"
              >信息素养</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '师风师德' }"
                @click="selectMajor('师风师德')"
              >师风师德</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '专题教育' }"
                @click="selectMajor('专题教育')"
              >专题教育</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '综合实践' }"
                @click="selectMajor('综合实践')"
              >综合实践</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '个人成长' }"
                @click="selectMajor('个人成长')"
              >个人成长</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '教学案例' }"
                @click="selectMajor('教学案例')"
              >教学案例</span>
               <span
                class="filter-tag"
                :class="{ active: selectedMajor === '班级管理' }"
                @click="selectMajor('班级管理')"
              >班级管理</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '通识技能' }"
                @click="selectMajor('通识技能')"
              >通识技能</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '信息素养' }"
                @click="selectMajor('信息素养')"
              >信息素养</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '师风师德' }"
                @click="selectMajor('师风师德')"
              >师风师德</span>
               <span
                class="filter-tag"
                :class="{ active: selectedMajor === '专题教育' }"
                @click="selectMajor('专题教育')"
              >专题教育</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '综合实践' }"
                @click="selectMajor('综合实践')"
              >综合实践</span>
              <span
                class="filter-tag"
                :class="{ active: selectedMajor === '个人成长' }"
                @click="selectMajor('个人成长')"
              >个人成长</span>
            
            </div>
          </div>

    
          <!-- 难度分类 -->
          <div class="filter-group">
            <span class="filter-label">难度：</span>
            <div class="filter-tags">
              <span
                class="filter-tag"
                :class="{ active: selectedDifficulty === '全部' }"
                @click="selectDifficulty('全部')"
              >全部</span>
              <span
                class="filter-tag"
                :class="{ active: selectedDifficulty === '零基础' }"
                @click="selectDifficulty('零基础')"
              >零基础</span>
              <span
                class="filter-tag"
                :class="{ active: selectedDifficulty === '初级' }"
                @click="selectDifficulty('初级')"
              >初级</span>
              <span
                class="filter-tag"
                :class="{ active: selectedDifficulty === '中级' }"
                @click="selectDifficulty('中级')"
              >中级</span>
              <span
                class="filter-tag"
                :class="{ active: selectedDifficulty === '高级' }"
                @click="selectDifficulty('高级')"
              >高级</span>
            </div>
          </div>
        </div>

        <!-- 分隔线 -->
        <div class="divider"></div>

        <!-- 筛选结果提示 -->
        <div class="filter-result" v-if="selectedSubject !== '全部' || selectedMajor !== '全部' || selectedDifficulty !== '全部'">
          <span>筛选结果：找到 {{ total }} 门相关课程</span>
        </div>

        <!-- 排序标签 -->
        <div class="sort-tabs">
          <span class="sort-tab">最新</span>
          <span class="sort-tab">最热</span>
          <span class="sort-tab active">推荐</span>
        </div>

        <!-- 加载状态 -->
        <div class="loading-state" v-if="loading">
          <div class="loading-content">
            <p>正在加载课程...</p>
          </div>
        </div>

        <!-- 课程网格 -->
        <div class="courses-grid" v-else-if="allCourses.length > 0">
          <div class="course-card" v-for="course in allCourses" :key="course.id">
            <div class="course-image">
              <img :src="course.thumbnail" :alt="course.title" />
            </div>
            <div class="course-info">
              <h3 class="course-title">{{ getCourseTitle(course) }}</h3>
              <div class="course-meta">
                <span class="course-duration">📚 {{ course.duration }}</span>
                <span class="course-price">💰 ¥{{ course.price }}</span>
              </div>
              <div class="course-footer">
                <div class="course-stats">
                  <span class="course-students">{{ course.studentsCount }}人已报名</span>
                </div>
                <button class="enroll-btn" @click="goToCourseDetail(course)">去学习</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-else>
          <div class="empty-content">
            <p>暂无符合条件的课程</p>
            <button class="clear-filters-btn" @click="clearAllFilters">清除筛选条件</button>
          </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination">
          <span class="pagination-info">{{ currentPageText }} / 共{{ totalPages }}页 ({{ totalItems }}条数据)</span>
          <span class="pagination-link prev" @click="goToPrevPage" :class="{ disabled: currentPage === 1 }">上一页</span>

          <!-- 第一页 -->
          <button
            v-if="totalPages > 0"
            class="pagination-btn page-num"
            :class="{ active: currentPage === 1 }"
            @click="goToPage(1)"
          >1</button>

          <!-- 左侧省略号 -->
          <span v-if="currentPage > 4" class="pagination-dots">...</span>

          <!-- 当前页附近的页码 -->
          <template v-for="page in visiblePages" :key="page">
            <button
              v-if="page !== 1 && page !== totalPages"
              class="pagination-btn page-num"
              :class="{ active: currentPage === page }"
              @click="goToPage(page)"
            >{{ page }}</button>
          </template>

          <!-- 右侧省略号 -->
          <span v-if="currentPage < totalPages - 3" class="pagination-dots">...</span>

          <!-- 最后一页 -->
          <button
            v-if="totalPages > 1"
            class="pagination-btn page-num"
            :class="{ active: currentPage === totalPages }"
            @click="goToPage(totalPages)"
          >{{ totalPages }}</button>

          <span class="pagination-link next" @click="goToNextPage" :class="{ disabled: currentPage === totalPages }">下一页</span>
          <span class="pagination-link last" @click="goToPage(totalPages)">尾页</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { CourseApi } from '@/api/modules/course'
import type { Course } from '@/api/types'

const router = useRouter()

// 课程数据和加载状态
const courses = ref<Course[]>([])
const loading = ref(false)
const total = ref(0)

// 筛选状态
const selectedSubject = ref('全部')
const selectedMajor = ref('全部')
const selectedDifficulty = ref('全部')

// 分页相关状态
const currentPage = ref(1)
const itemsPerPage = 20
const totalItems = computed(() => total.value)
const totalPages = computed(() => Math.ceil(totalItems.value / itemsPerPage))

// 数字转中文
const numberToChinese = (num: number): string => {
  const chineseNumbers = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  if (num <= 10) {
    return chineseNumbers[num]
  } else if (num < 20) {
    return '十' + chineseNumbers[num - 10]
  } else if (num < 100) {
    const tens = Math.floor(num / 10)
    const ones = num % 10
    return chineseNumbers[tens] + '十' + (ones > 0 ? chineseNumbers[ones] : '')
  }
  return num.toString()
}

// 当前页面文本
const currentPageText = computed(() => {
  if (currentPage.value === 1) {
    return '首页'
  } else {
    return `第${numberToChinese(currentPage.value)}页`
  }
})

// 可见的页码范围
const visiblePages = computed(() => {
  const pages = []
  const current = currentPage.value
  const total = totalPages.value

  // 显示当前页前后2页
  const start = Math.max(2, current - 2)
  const end = Math.min(total - 1, current + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 加载课程数据
const loadCourses = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: itemsPerPage,
      categoryId: selectedSubject.value !== '全部' ? getCategoryIdBySubject(selectedSubject.value) : undefined,
      keyword: selectedMajor.value !== '全部' ? selectedMajor.value : undefined
    }

    const response = await CourseApi.getCourses(params)

    if (response.code === 0 || response.code === 200) {
      courses.value = response.data.list
      total.value = response.data.total
    } else {
      console.error('获取课程列表失败:', response.message)
    }
  } catch (error) {
    console.error('加载课程失败:', error)
  } finally {
    loading.value = false
  }
}

// 根据学科获取分类ID（这里需要根据实际后端分类来映射）
const getCategoryIdBySubject = (subject: string): number | undefined => {
  const categoryMap: Record<string, number> = {
    '必修课': 1,
    '高分课': 2,
    '名师课堂': 3,
    '训练营': 4,
    '无考试': 5,
    '专题讲座': 6
  }
  return categoryMap[subject]
}

// 跳转到指定页面
const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadCourses()
  }
}

// 上一页
const goToPrevPage = () => {
  if (currentPage.value > 1) {
    goToPage(currentPage.value - 1)
  }
}

// 下一页
const goToNextPage = () => {
  if (currentPage.value < totalPages.value) {
    goToPage(currentPage.value + 1)
  }
}

// 清除所有筛选条件
const clearAllFilters = () => {
  selectedSubject.value = '全部'
  selectedMajor.value = '全部'
  selectedDifficulty.value = '全部'
  currentPage.value = 1
  loadCourses()
}

// 筛选功能
const selectSubject = (subject: string) => {
  selectedSubject.value = subject
  currentPage.value = 1 // 重置到第一页
  loadCourses()
}

const selectMajor = (major: string) => {
  selectedMajor.value = major
  currentPage.value = 1 // 重置到第一页
  loadCourses()
}

const selectDifficulty = (difficulty: string) => {
  selectedDifficulty.value = difficulty
  currentPage.value = 1 // 重置到第一页
  loadCourses()
}

// 当前页显示的课程数据（直接使用从API获取的数据）
const allCourses = computed(() => {
  return courses.value
})

// 获取课程标题的函数
const getCourseTitle = (course: Course) => {
  return course.title
}

// 跳转到课程详情页
const goToCourseDetail = (course: Course) => {
  router.push({
    name: 'CourseDetail',
    params: { id: course.id }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadCourses()
})
</script>

<style scoped>
.courses-page {
  min-height: 100vh;
  background: #f8f9fa;
}

.page-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  padding: 60px 0;
  text-align: center;
  color: white;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 100%;
  background: url('/images/header-decoration.png') no-repeat center right;
  background-size: contain;
  opacity: 0.3;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  position: relative;
  z-index: 1;
}

.page-title {
  font-size: 48px;
  font-weight: 600;
  margin: 0 0 16px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-subtitle {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
}

.main-content {
  padding: 40px 0;
}

.container {
  max-width: calc(100vw - 320px);
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.filter-section {
  background: transparent;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: none;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: rgba(128, 128, 128, 0.2);
  margin-bottom: 32px;
}

.filter-result {
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  text-align: center;
}

.loading-content p {
  color: #666;
  font-size: 16px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  text-align: center;
}

.empty-content p {
  color: #999;
  font-size: 16px;
  margin-bottom: 20px;
}

.clear-filters-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.clear-filters-btn:hover {
  background: #40a9ff;
}

.filter-group {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-label {
  font-weight: 500;
  color: #333;
  margin-right: 16px;
  min-width: 60px;
  line-height: 32px;
  flex-shrink: 0;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  flex: 1;
}

.filter-tag {
  padding: 6px 16px;
  background: #f5f5f5;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
  border: 1px solid transparent;
  white-space: nowrap;
}

.filter-tag:hover {
  background: #e6f7ff;
  color: #1890ff;
  border-color: #1890ff;
}

.filter-tag.active {
  background: #e6f7ff;
  color: #1890ff;
  border-color: transparent;
  font-weight: 500;
}

.sort-tabs {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.sort-tab {
  color: #666;
  font-size: 14px;
  cursor: pointer;
  padding: 8px 0;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.sort-tab:hover {
  color: #1890ff;
}

.sort-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: 500;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 40px;
  width: 100%;
  box-sizing: border-box;
}

.course-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.course-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.course-image {
  width: 100%;
  height: 140px;
  overflow: hidden;
  border-radius: 8px 8px 0 0;
}

.course-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.course-info {
  padding: 16px;
}



.course-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-bottom: 16px;
}

.course-duration {
  color: #666;
}

.course-price {
  color: #ff4d4f;
  font-weight: 500;
}

.course-stats {
  display: flex;
  align-items: center;
}

.course-students {
  color: #999;
  font-size: 12px;
}

.course-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.course-tag {
  background: transparent;
  color: #999;
  padding: 0;
  border-radius: 0;
  font-size: 12px;
  white-space: nowrap;
}

.enroll-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s;
  white-space: nowrap;
}

.enroll-btn:hover {
  background: #40a9ff;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  margin-top: 40px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
  margin-right: 20px;
}

.pagination-btn {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  background: white;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  min-width: 40px;
  text-align: center;
  margin: 0 6px;
}

.pagination-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.pagination-btn.active {
  background: #1890ff;
  border-color: #1890ff;
  color: white;
}

/* 移除了 .pagination-btn.last 样式，因为现在尾页是文本链接 */

.pagination-btn:disabled {
  background: #f5f5f5;
  color: #ccc;
  border-color: #e6e6e6;
  cursor: not-allowed;
}

.pagination-btn:disabled:hover {
  background: #f5f5f5;
  color: #ccc;
  border-color: #e6e6e6;
}

.pagination-link {
  color: #666;
  font-size: 14px;
  cursor: pointer;
  padding: 8px 12px;
  margin: 0 6px;
  transition: color 0.2s;
  user-select: none;
}

.pagination-link:hover {
  color: #1890ff;
}

.pagination-link.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.pagination-link.disabled:hover {
  color: #ccc;
}

.pagination-dots {
  color: #999;
  padding: 0 8px;
  font-size: 14px;
  margin: 0 6px;
}

/* 响应式设计 */
@media (min-width: 1600px) {
  .courses-grid {
    grid-template-columns: repeat(5, 1fr);
  }
}

@media (min-width: 1400px) {
  .container {
    max-width: 1200px;
  }
}

@media (max-width: 1400px) {
  .courses-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 1200px) {
  .container {
    max-width: calc(100vw - 160px);
    padding: 0 20px;
  }
}

@media (max-width: 992px) {
  .courses-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .page-title {
    font-size: 36px;
  }
}

@media (max-width: 768px) {
  .container {
    max-width: calc(100vw - 40px);
    padding: 0 20px;
  }

  .page-title {
    font-size: 28px;
  }

  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .filter-label {
    min-width: auto;
    line-height: 1.5;
  }

  .courses-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .pagination {
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
  }

  .pagination-info {
    margin-right: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: center;
  }

  .pagination-btn,
  .pagination-link {
    margin: 4px;
  }
}

@media (max-width: 768px) {
  .container {
    margin: 0 20px;
  }
}

@media (max-width: 480px) {
  .courses-grid {
    grid-template-columns: 1fr;
  }

  .container {
    margin: 0 16px;
  }

  .filter-section {
    padding: 16px;
  }
}
</style>
