<template>
  <div class="course-recommend">
    <div class="course-container">
      <!-- 标题 -->
      <div class="section-title">
        <div class="title-bar"></div>
        <h2 class="title-text">好课推荐</h2>
      </div>
      
      <!-- 分类标签 -->
      <div class="category-tabs">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="category-tab"
          :class="{ active: currentCategory === category.id }"
          @click="switchCategory(category.id)"
        >
          {{ category.name }}
        </div>
      </div>
      
      <!-- 骨架屏加载状态 -->
      <div v-if="loading" class="course-list">
        <div 
          v-for="i in 8" 
          :key="`skeleton-${i}`"
          class="course-item skeleton-item"
        >
          <!-- 封面骨架屏 -->
          <div class="course-cover skeleton-cover">
            <el-skeleton-item variant="image" style="width: 100%; height: 240px; border-radius: 0;" />
          </div>
          
          <!-- 内容骨架屏 -->
          <div class="course-info">
            <el-skeleton-item variant="h3" style="width: 80%; height: 18px; margin-bottom: 8px;" />
            <el-skeleton-item variant="text" style="width: 60px; height: 26px; margin-bottom: 8px;" />
            <div class="user-info">
              <div class="user-left">
                <el-skeleton-item variant="circle" style="width: 28px; height: 28px;" />
                <el-skeleton-item variant="text" style="width: 60px; height: 12px;" />
              </div>
              <el-skeleton-item variant="text" style="width: 68px; height: 26px; border-radius: 4px;" />
            </div>
          </div>
        </div>
      </div>
      
      <!-- 课程列表 -->
      <div v-else class="course-list">
        <div 
          v-for="course in courses" 
          :key="course.id"
          class="course-item"
          @click="handleCourseClick(course)"
        >
          <!-- 视频封面 -->
          <div class="course-cover">
            <img :src="course.cover" :alt="course.title" />
            <!-- 播放时长 -->
            
          </div>
          
          <!-- 课程信息 -->
          <div class="course-info">
            <h3 class="course-title">{{ course.title }}</h3>
            <!-- VIP标签 -->
            <div class="vip-tag" :class="course.vipType">
              <img 
                v-if="course.vipType === 'free'" 
                src="../assets/vip_icon/免费.svg" 
                alt="免费" 
                class="vip-icon"
              />
              <img 
                v-else-if="course.vipType === 'vip'" 
                src="../assets/vip_icon/VIP.svg" 
                alt="VIP" 
                class="vip-icon"
              />
              <img 
                v-else-if="course.vipType === 'svip'" 
                src="../assets/vip_icon/SVIP.svg" 
                alt="SVIP" 
                class="vip-icon"
              />
            </div>
            <div class="user-info">
              <div class="user-left">
                <img :src="course.userAvatar" :alt="course.userName" class="user-avatar" />
                <span class="user-name">{{ course.userName }}</span>
              </div>
              <div class="tag-button">
                <span>{{ course.category }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="showPagination && !loading && courses.length > 0" class="pagination-container">
        <div class="pagination">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            class="page-button"
            :class="{ active: page === pagination.page, ellipsis: page === '...' }"
            @click="page !== '...' && handlePageChange(page)"
            :disabled="page === '...'"
          >
            {{ page }}
          </button>
          <button 
            v-if="pagination.page < pagination.pages"
            class="page-button next-button"
            @click="handlePageChange(pagination.page + 1)"
          >
            &gt;
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { View, Star, ChatDotRound } from '@element-plus/icons-vue'
import { getCourseCategories, getHotCourses, getCategoryCourses } from '../api'
import { useRouter } from 'vue-router'
import { isLoggedIn } from '../utils/auth.js'

// 定义props
const props = defineProps({
  showPagination: {
    type: Boolean,
    default: false
  }
})

// 获取router实例
const router = useRouter()

// 定义emits
const emit = defineEmits(['showLoginModal'])

// 加载状态
const loading = ref(true)

// 当前选中的分类
const currentCategory = ref('hot')

// 分类数据
const categories = ref([])

// 课程数据
const courses = ref([])

// 分页参数
const pagination = ref({
  page: 1,
  size: 32,
  total: 0,
  pages: 0
})

// 是否显示分页
const showPagination = computed(() => {
  return props.showPagination && pagination.value.total > pagination.value.size
})

// 获取分类数据
const loadCategories = async () => {
  try {
    const response = await getCourseCategories()
    if (response.code === 200) {
      categories.value = response.data
      // 默认选中热门推荐
      if (categories.value.length > 0) {
        currentCategory.value = 'hot'
        await loadCourses('hot')
      }
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 加载课程数据
const loadCourses = async (category) => {
  loading.value = true
  try {
    let response
    if (category === 'hot') {
      response = await getHotCourses({
        page: pagination.value.page,
        size: pagination.value.size
      })
    } else {
      response = await getCategoryCourses(category, {
        page: pagination.value.page,
        size: pagination.value.size
      })
    }
    
    if (response.code === 200) {
      courses.value = response.data.records.map(course => ({
        id: course.id,
        title: course.title,
        cover: course.coverUrl,
        vipType: getVipType(course.level, course.isFree),
        duration: course.duration,
        userAvatar: course.creator?.avatarUrl,
        userName: course.creator?.username,
        views: formatNumber(course.viewCount),
        favorites: formatNumber(course.likeCount),
        comments: formatNumber(course.commentCount),
        category: course.category
      }))
      pagination.value.total = response.data.total
      pagination.value.pages = response.data.pages || 0
    }
  } catch (error) {
    console.error('加载课程失败:', error)
  } finally {
    loading.value = false
  }
}

// 根据用户角色和课程level判断vipType
const getVipType = (level, isFree) => {
  if (isFree || level === 0) return 'free'
  if (level === 1) return 'vip'
  if (level === 2) return 'vip'
  if (level === 3) return 'svip'
  return 'free'
}

// 格式化数字
const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 切换分类
const switchCategory = async (categoryId) => {
  currentCategory.value = categoryId
  pagination.value.page = 1
  await loadCourses(categoryId)
}

// 切换页码
const handlePageChange = async (page) => {
  pagination.value.page = page
  await loadCourses(currentCategory.value)
}

// 处理课程卡片点击
const handleCourseClick = (course) => {
  // 检查用户是否已登录
  if (!isLoggedIn()) {
    // 未登录，触发显示登录弹窗事件
    emit('showLoginModal', '请先登录后查看课程详情')
    return
  }
  
  // 数据类型验证 - 确保这是课程数据
  console.log('[CourseRecommend] 点击课程详情:', {
    id: course.id,
    title: course.title,
    type: course.type || 'course',
    dataSource: 'CourseRecommend'
  })
  
  // 强制确保跳转到课程页面
  if (course.type === 'workflow') {
    console.warn('[CourseRecommend] 警告：课程组件中发现工作流数据!', course)
    router.push(`/workflow/${course.id}`)
  } else {
    // 已登录，跳转到课程详情页
    router.push(`/course/${course.id}`)
  }
}

// 生成页码数组
const getPageNumbers = () => {
  const pages = []
  const current = pagination.value.page
  const total = pagination.value.pages
  
  if (total <= 7) {
    // 如果总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 如果总页数大于7，显示部分页码
    if (current <= 4) {
      // 当前页在前4页
      for (let i = 1; i <= 7; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后4页
      pages.push(1)
      pages.push('...')
      for (let i = total - 6; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 2; i <= current + 2; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }
  
  return pages
}

// 组件初始化
onMounted(async () => {
  await loadCategories()
})
</script>

<style scoped>
.course-recommend {
  width: 100%;
  background: white;
  padding: 0px 40px;
  margin: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.course-container {
  width: 100%;
  max-width: 1440px;
  margin: 0 auto;
  box-sizing: border-box;
}

/* 标题样式 */
.section-title {
  width: 312px;

  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 70px;
  margin-bottom: 20px;
}

.title-bar {
  width: 4px;
  height: 24px;
  background: #333;
  border-radius: 2px;
}

.title-text {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 24px;
  line-height: 28px;
  letter-spacing: 0px;
  color: #333;
  margin: 0;
  text-align: left;
}

/* 分类标签样式 */
.category-tabs {
  display: flex;
  gap: 20px;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 2px solid rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
  justify-content: flex-start;
  width: 100%;
}

.category-tab {
  width: 120px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  flex-shrink: 0;
}

.category-tab:hover {
  background: #f5f5f5;
  border-color: #d0d0d0;
}

.category-tab.active {
  background: #333;
  color: white;
  border-color: #333;
}

/* 课程列表样式 */
.course-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  justify-content: start;
  overflow-y: auto;
  padding-bottom: 30px;
  width: 100%;
  box-sizing: border-box;
}

.course-list::-webkit-scrollbar {
  display: none;
}

.course-list {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

/* 课程卡片样式 */
.course-item {
  width: 100%;
  min-height: 394px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

/* 骨架屏样式 */
.skeleton-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.skeleton-cover {
  position: relative;
  width: 100%;
  height: 240px;
  overflow: hidden;
}

.skeleton-item .user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.skeleton-item .user-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式骨架屏标签按钮 */
@media (max-width: 768px) {
  .skeleton-item .user-info .el-skeleton-item:last-child {
    width: 60px !important;
    height: 24px !important;
  }
}

@media (max-width: 480px) {
  .skeleton-item .user-info .el-skeleton-item:last-child {
    width: 52px !important;
    height: 22px !important;
  }
}

.course-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

/* 视频封面样式 */
.course-cover {
  position: relative;
  width: 100%;
  height: 240px;
  overflow: hidden;
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.course-item:hover .course-cover img {
  transform: scale(1.05);
}

/* VIP标签样式 */
.vip-tag {
  display: block;
  margin: 12px 0;
  text-align: left;
}

.vip-icon {
  width: 54px;
  height: 26px;
  object-fit: contain;
}

/* 播放时长样式 */
.duration {
  position: absolute;
  bottom: 12px;
  right: 12px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
}

/* 课程信息样式 */
.course-info {
  padding: 12px;
}

.course-title {
  font-family: Arial, sans-serif;
  font-weight: 400;
  font-size: 18px;
  line-height: 21px;
  letter-spacing: 0px;
  color: #333;
  margin: 0 0 8px 0;
  text-align: left;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.user-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  font-family: Arial, sans-serif;
  font-weight: 400;
  font-size: 12px;
  line-height: 14px;
  letter-spacing: 0px;
  color: #333;
}

.tag-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 68px;
  height: 26px;
  background: #ffffff;
  border: 1px solid rgba(29, 0, 255, 1);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tag-button span {
  font-family: Arial, sans-serif;
  font-size: 12px;
  line-height: 14px;
  letter-spacing: 0px;
  color: rgba(29, 0, 255, 1);
  font-weight: 400;
  text-align: center;
}

.tag-button:hover {
  background: rgba(29, 0, 255, 0.05);
  border-color: rgba(29, 0, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .course-list {
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
  }
  
  .category-tabs {
    gap: 16px;
  }
  
  .category-tab {
    width: 110px;
  }
}

@media (max-width: 1100px) {
  .course-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 18px;
  }
  
  .category-tabs {
    gap: 14px;
  }
  
  .category-tab {
    width: 100px;
    height: 44px;
    font-size: 13px;
  }
  
  .course-recommend {
    padding: 0 30px;
  }
}

@media (max-width: 768px) {
  .course-list {
    grid-template-columns: repeat(1, 1fr);
    gap: 16px;
  }
  
  .category-tabs {
    flex-wrap: wrap;
    gap: 12px;
    justify-content: flex-start;
  }
  
  .category-tab {
    width: 90px;
    height: 40px;
    font-size: 12px;
  }
  
  .course-recommend {
    padding: 0 20px;
  }
  
  .course-item {
    min-height: 320px;
  }
  
  .course-cover {
    height: 180px;
  }
  
  .course-title {
    font-size: 16px;
    line-height: 20px;
  }
  
  .user-info {
    margin-top: 10px;
    padding-top: 10px;
  }
  
  .user-avatar {
    width: 24px;
    height: 24px;
  }
  
  .user-name {
    font-size: 11px;
  }
  
  .tag-button {
    width: 60px;
    height: 24px;
  }
  
  .tag-button span {
    font-size: 11px;
    line-height: 13px;
  }
  
  .section-title {
    margin-top: 50px;
  }
  
  .title-text {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .course-recommend {
    padding: 0 15px;
  }
  
  .category-tabs {
    gap: 10px;
  }
  
  .category-tab {
    width: 80px;
    height: 36px;
    font-size: 11px;
  }
  
  .course-item {
    min-height: 280px;
  }
  
  .course-cover {
    height: 160px;
  }
  
  .course-title {
    font-size: 14px;
    line-height: 18px;
  }
  
  .user-info {
    margin-top: 8px;
    padding-top: 8px;
  }
  
  .user-avatar {
    width: 22px;
    height: 22px;
  }
  
  .user-name {
    font-size: 10px;
  }
  
  .tag-button {
    width: 52px;
    height: 22px;
  }
  
  .tag-button span {
    font-size: 10px;
    line-height: 12px;
  }
  
  .section-title {
    margin-top: 40px;
  }
  
  .title-text {
    font-size: 18px;
  }
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px 0;
}

.pagination {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-button {
  min-width: 40px;
  height: 40px;
  border: 1px solid #e0e0e0;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
}

.page-button:hover:not(.ellipsis):not(:disabled) {
  background: #f5f5f5;
  border-color: #d0d0d0;
}

.page-button.active {
  background: #333;
  color: white;
  border-color: #333;
}

.page-button.ellipsis {
  cursor: default;
  background: white;
  border-color: #e0e0e0;
  color: #999;
}

.page-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.next-button {
  font-weight: bold;
}
</style> 