<template>
  <StudyPlanLayout category-name="课程中心">
    <!-- 主要内容区 -->
    <div class="main-content">
      <div class="container">
        <!-- 页面标题 -->
        <h2 class="page-title">课程列表</h2>

        <!-- 搜索和筛选 -->
        <div class="search-filter-bar">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索思政资源"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #suffix>
                <el-button
                  type="danger"
                  circle
                  @click="handleSearch"
                  class="search-button"
                >
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>

        <!-- 课程列表 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="6" animated />
        </div>

        <div v-else-if="courseList.length > 0" class="course-grid">
          <div
            v-for="course in courseList"
            :key="course.courseID"
            class="course-card"
            @click="handleCourseClick(course.courseID || '')"
          >
            <!-- 课程封面 -->
            <div class="course-cover">
              <img
                :src="course.coverImage ? FILE_DOWNLOAD_URL + course.coverImage : defaultCover"
                :alt="course.name"
                class="cover-image"
              />
              <!-- 课程类型标签 -->
              <div class="course-type-tag">
                <el-icon><VideoPlay /></el-icon>
                <span>视频课程</span>
              </div>
              <!-- 分类标签 -->
              <div class="category-tag">
                {{ getCategoryName() }}
              </div>
            </div>

            <!-- 课程信息 -->
            <div class="course-info">
              <div class="view-count">
                {{ formatViewCount(course.viewCount) }}次浏览
              </div>
              <h3 class="course-title">{{ course.name }}</h3>
              <p class="course-desc">
                {{ course.description || '暂无描述' }}
              </p>
            </div>
          </div>
        </div>

        <div v-else class="empty-state">
          <el-empty description="暂无课程" />
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="pageParam.page"
            v-model:page-size="pageParam.size"
            :total="total"
            :page-sizes="[6, 12, 24, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </StudyPlanLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Search, VideoPlay } from '@element-plus/icons-vue';
import { courseApi } from '@/apis/study';
import type { Course, PageParam } from '@/types';
import { StudyPlanLayout } from '@/views/study-plan';
import defaultCover from '@/assets/imgs/default-course-bg.png'
import { FILE_DOWNLOAD_URL } from '@/config';

defineOptions({
  name: 'CourseCenterView'
});

const router = useRouter();
const loading = ref(false);
const searchKeyword = ref('');
const courseList = ref<Course[]>([]);
const total = ref(0);

// 分页参数
const pageParam = ref<PageParam>({
  page: 1,
  size: 6
});

onMounted(() => {
  loadCourseList();
});

// 加载课程列表
async function loadCourseList() {
  loading.value = true;
  try {
    const filter: Course = {
      status: 1 // 只显示已上线的课程
    };
    
    if (searchKeyword.value) {
      filter.name = searchKeyword.value;
    }
    
    const res = await courseApi.getCoursePage(pageParam.value, filter);
    
    if (res.success) {
      courseList.value = res.dataList || [];
      total.value = res.pageParam?.totalElements || 0;
    } else {
      ElMessage.error('加载课程列表失败');
    }
  } catch (error) {
    console.error('加载课程列表失败:', error);
    ElMessage.error('加载课程列表失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  pageParam.value.page = 1;
  loadCourseList();
}

// 分页大小改变
function handleSizeChange() {
  loadCourseList();
}

// 当前页改变
function handleCurrentChange() {
  loadCourseList();
}

// 点击课程卡片 - 跳转到课程详情路由
function handleCourseClick(courseId: string) {
  console.log('handleCourseClick', courseId);
  console.log('router', router.getRoutes());
  router.push({
    path: '/study-plan/course-detail',
    query: { courseId }
  });
}

// 格式化浏览次数
function formatViewCount(count?: number): string {
  if (!count) return '0';
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + 'w';
  }
  return count.toString();
}

// 获取分类名称（这里简化处理，实际应该从课程标签中获取）
function getCategoryName(): string {
  // TODO: 从 courseTags 中获取第一个标签作为分类
  return '党史学习';
}
</script>

<style lang="scss" scoped>
.main-content {
  padding: 40px 0 80px;
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 24px;
  }
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #141F38;
  margin: 0 0 32px 0;
}

.search-filter-bar {
  margin-bottom: 40px;
  
  .search-box {
    max-width: 400px;
    
    .search-input {
      :deep(.el-input__wrapper) {
        border-radius: 30px;
        padding-right: 4px;
      }
      
      .search-button {
        width: 36px;
        height: 36px;
        background: #C62828;
        border: none;
        
        &:hover {
          background: #A82020;
        }
      }
    }
  }
}

.loading-container {
  padding: 40px 0;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-bottom: 40px;
  
  @media (max-width: 1024px) {
    grid-template-columns: repeat(2, 1fr);
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.course-card {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 20px rgba(164, 182, 199, 0.2);
    border-color: rgba(0, 0, 0, 0.1);
  }
  
  .course-cover {
    position: relative;
    width: 100%;
    height: 221px;
    overflow: hidden;
    
    .cover-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
    }
    
    .course-type-tag {
      position: absolute;
      top: 12px;
      left: 12px;
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 4px 10px;
      background: rgba(198, 40, 40, 0.9);
      color: #fff;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
      
      .el-icon {
        font-size: 16px;
      }
    }
    
    .category-tag {
      position: absolute;
      bottom: -1px;
      right: -2px;
      padding: 3px 26px;
      background: #D1AD79;
      color: #fff;
      font-size: 14px;
      font-weight: 600;
      border-radius: 0 0 10px 0;
    }
  }
  
  &:hover .cover-image {
    transform: scale(1.05);
  }
  
  .course-info {
    padding: 22px;
    
    .view-count {
      position: absolute;
      top: 232px;
      right: 22px;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.3);
      margin-bottom: 8px;
    }
    
    .course-title {
      font-size: 20px;
      font-weight: 600;
      color: #141F38;
      margin: 0 0 8px 0;
      line-height: 1.4;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .course-desc {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.3);
      line-height: 1.6;
      margin: 0;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 4;
      line-clamp: 4;
      overflow: hidden;
      text-overflow: ellipsis;
      min-height: 88px;
    }
  }
}

.empty-state {
  padding: 80px 0;
  text-align: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>
