<template>
  <div class="course-center-wrapper">
    <!-- 全屏Loading遮罩（Teleport到body） -->
    <Teleport to="body">
      <div v-if="loading" class="fullscreen-loading-mask">
        <div class="loading-content">
          <el-icon class="loading-icon is-loading">
            <Loading />
          </el-icon>
          <div class="loading-text">{{ loadingText }}</div>
        </div>
      </div>
    </Teleport>
    
    <div class="course-center-container">
    <div class="page-header">
      <h1 class="page-title">课程中心</h1>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程"
          clearable
          style="width: 300px"
          @keyup.enter="handleSearch"
          @input="handleRealTimeSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 分类筛选 -->
    <div class="category-filter">
      <el-radio-group v-model="selectedCategory" @change="handleCategoryChange">
        <el-radio-button label="">全部课程</el-radio-button>
        <el-radio-button label="required">必修课程</el-radio-button>
        <el-radio-button label="optional">选修课程</el-radio-button>
        <el-radio-button label="completed">已完成</el-radio-button>
        <el-radio-button label="ongoing">学习中</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 课程列表 -->
    <div v-if="filteredCourses.length > 0" class="course-grid">
      <div class="course-card" v-for="course in filteredCourses" :key="course.id">
        <!-- 卡片内容区域 -->
        <div class="card-body">
          <!-- 顶部徽章和进度 -->
          <div class="card-header-info">
            <div class="card-badges">
              <span class="badge badge-new" v-if="course.isNew">
                <el-icon><Star /></el-icon>
                NEW
              </span>
              <span class="badge" :class="course.type === '必修' ? 'badge-required' : 'badge-optional'">
                {{ course.type }}
              </span>
            </div>
            <div class="progress-badge" v-if="course.progress > 0">
              <span class="progress-text">{{ course.progress }}%</span>
            </div>
          </div>
          <h3 class="course-title">{{ course.title }}</h3>
          <p class="course-description">{{ course.description }}</p>
          
          <div class="course-stats">
            <div class="stat-item">
              <el-icon><Clock /></el-icon>
              <span>{{ course.duration }}</span>
            </div>
            <div class="stat-item">
              <el-icon><Collection /></el-icon>
              <span>{{ course.lessons }} 课时</span>
            </div>
            <div class="stat-item">
              <el-icon><User /></el-icon>
              <span>{{ course.students }}</span>
            </div>
          </div>
        </div>
        
        <!-- 卡片底部操作区域 -->
        <div class="card-footer">
          <!-- 主要操作按钮 -->
          <button class="action-btn primary-btn" @click="enterCourse(course)">
            <el-icon><VideoPlay /></el-icon>
            <span>{{ course.progress > 0 ? '继续学习' : '开始学习' }}</span>
          </button>
          
          <!-- 次要操作按钮组 -->
          <div class="secondary-actions">
            <!-- 播课功能暂时关闭 -->
            <button v-if="false" class="action-btn secondary-btn" @click="playAudio(course)">
              <el-icon><Headset /></el-icon>
              <span>播课</span>
            </button>
            <button class="action-btn secondary-btn" @click="chatWithCourse(course)">
              <el-icon><ChatDotRound /></el-icon>
              <span>对话</span>
            </button>
            <button 
              class="action-btn exam-btn" 
              @click="startExam(course)"
            >
              <el-icon><DocumentChecked /></el-icon>
              <span>考试</span>
            </button>
            <button 
              class="action-btn practice-btn" 
              @click="startPractice(course)"
            >
              <el-icon><Microphone /></el-icon>
              <span>陪练</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态显示 -->
    <div v-else class="empty-state">
      <el-empty 
        :description="(searchKeyword || selectedCategory) ? '没有符合条件的课程' : '暂无课程数据'"
        :image-size="120"
      >
        <el-button v-if="searchKeyword || selectedCategory" type="primary" @click="clearAllFilters">
          清空筛选条件
        </el-button>
        <el-button v-else type="primary" disabled>
          敬请期待更多课程
        </el-button>
      </el-empty>
    </div>

    <!-- 加载更多 -->
    <div class="load-more" v-if="hasMore && filteredCourses.length > 0">
      <el-button @click="loadMore">加载更多</el-button>
    </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Search, Clock, User, Headset, ChatDotRound, 
  Microphone, Star, VideoPlay, Collection, DocumentChecked,
  Loading
} from '@element-plus/icons-vue'
import { getCourseList, type CourseInfo } from '@/api/trainee'
import { practiceApi } from '@/api/practice'
import { broadcastApi } from '@/api/broadcast'

const router = useRouter()

// 搜索关键词
const searchKeyword = ref('')

// 选中的分类
const selectedCategory = ref('')

// 是否有更多
const hasMore = ref(true)

// 课程列表（展示用）
const courseList = ref<any[]>([])

// Loading状态
const loading = ref(false)
const loadingText = ref('正在加载...')

/**
 * 从后端获取课程列表并映射为页面展示结构
 */
async function fetchCourses(): Promise<void> {
  try {
    const res = await getCourseList({ page: 1, size: 12 })
    const items = res?.data?.items || []

    // 将后端数据映射到当前页面使用的展示结构
    courseList.value = (items as CourseInfo[]).map((c: any, idx) => {
      // 根据后端返回的course_type字段判断课程类型
      // required=必修, optional=选修, 无值表示该课程未分配给用户岗位
      let courseType = '必修'  // 默认为必修
      if (c.course_type === 'optional') {
        courseType = '选修'
      } else if (c.course_type === 'required') {
        courseType = '必修'
      }
      
      return {
        id: c.id,
        title: c.name || c.title || '',  // 优先使用name（数据库字段），兼容title
        description: c.description || '',
        type: courseType,
        isNew: idx < 2,
        duration: formatDuration(c.duration),
        lessons: c.materialCount ?? 0,
        students: 0,
        progress: c.progress ?? 0,
        examPassed: (c.progress ?? 0) >= 80
      }
    })
  } catch (error) {
    ElMessage.error('课程加载失败，请稍后重试')
    // 失败时保持空列表，UI 会显示空状态
    courseList.value = []
  }
}

/**
 * 将分钟数格式化为“X小时Y分”
 */
function formatDuration(minutes?: number): string {
  if (!minutes || minutes <= 0) return '—'
  const h = Math.floor(minutes / 60)
  const m = minutes % 60
  if (h > 0 && m > 0) return `${h}小时${m}分`
  if (h > 0) return `${h}小时`
  return `${m}分`
}

// 过滤后的课程数据
const filteredCourses = computed(() => {
  let filtered = courseList.value

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(course => 
      course.title.toLowerCase().includes(keyword) ||
      course.description.toLowerCase().includes(keyword)
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    switch (selectedCategory.value) {
      case 'required':
        filtered = filtered.filter(course => course.type === '必修')
        break
      case 'optional':
        filtered = filtered.filter(course => course.type === '选修')
        break
      case 'completed':
        filtered = filtered.filter(course => course.progress === 100)
        break
      case 'ongoing':
        filtered = filtered.filter(course => course.progress > 0 && course.progress < 100)
        break
    }
  }

  return filtered
})

onMounted(() => {
  fetchCourses()
})

/**
 * 搜索课程
 */
const handleSearch = () => {
  const count = filteredCourses.value.length
  ElMessage.success('找到 ' + count + ' 门课程')
}

/**
 * 分类切换
 */
const handleCategoryChange = () => {
  const categoryText = getCategoryText(selectedCategory.value)
  const count = filteredCourses.value.length
  ElMessage.success('切换到：' + categoryText + '，找到 ' + count + ' 门课程')
}

/**
 * 获取分类文本
 */
const getCategoryText = (category: string) => {
  const map: Record<string, string> = {
    '': '全部课程',
    'required': '必修课程',
    'optional': '选修课程', 
    'completed': '已完成',
    'ongoing': '学习中'
  }
  return map[category] || '全部课程'
}

/**
 * 实时搜索处理
 */
const handleRealTimeSearch = () => {
  // 筛选逻辑在计算属性中处理
}

/**
 * 清空所有筛选条件
 */
const clearAllFilters = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  ElMessage.success('已清空所有筛选条件')
}

/**
 * 进入课程
 */
const enterCourse = (course: any) => {
  router.push('/trainee/course-detail?id=' + course.id)
}

/**
 * 播放音频
 */
const playAudio = async (course: any) => {
  try {
    const res: any = await broadcastApi.getInfo(course.id)
    // http.ts 返回 AxiosResponse，需要访问 res.data.data
    const code = res.data?.code || res.code
    const data = res.data?.data || res.data
    
    if (code === 200 && data?.has_broadcast && data.mp3_url) {
      router.push({
        name: 'BroadcastCourse',
        query: {
          courseId: course.id,
          courseName: course.title,  // 使用映射后的title字段
          mp3Url: data.mp3_url
        }
      })
    } else {
      ElMessage.warning('该课程暂无播课内容')
    }
  } catch (error) {
    console.error('查询播课信息失败:', error)
    ElMessage.error('查询播课信息失败')
  }
}

/**
 * 与课程对话
 */
const chatWithCourse = (course: any) => {
  router.push('/trainee/chat-course?courseId=' + course.id)
}

/**
 * 开始考试
 */
const startExam = (course: any) => {
  router.push('/trainee/exam?courseId=' + course.id)
}

/**
 * 开始陪练（课程模式）
 * 
 * 流程：
 * 1. 调用Dify工作流提取场景
 * 2. 跳转到陪练对话页面，携带场景数据
 */
const startPractice = async (course: any) => {
  try {
    // 显示全屏Loading
    loading.value = true
    loadingText.value = '正在分析课程内容，生成陪练场景...\n预计需要10-30秒，请稍候'
    
    console.log('🚀 开始提取场景, course_id:', course.id)
    
    // 调用Dify提取场景
    const response: any = await practiceApi.extractScene({ 
      course_id: course.id 
    })
    
    console.log('📦 完整响应:', response)
    console.log('📦 response.data:', response.data)
    
    // http.ts返回AxiosResponse，数据在response.data.data中
    // response -> AxiosResponse
    // response.data -> { code: 200, message: "success", data: {...} }
    // response.data.data -> { scene: {...}, workflow_run_id, task_id }
    const businessData = response.data?.data || response.data || response
    
    console.log('📦 业务数据:', businessData)
    console.log('📦 场景数据:', businessData?.scene)
    
    if (!businessData || !businessData.scene) {
      console.error('❌ 场景数据格式错误:', { response, businessData })
      throw new Error('场景数据格式错误，请查看Console')
    }
    
    // 更新Loading文字
    loadingText.value = '场景生成完成，正在跳转...'
    
    console.log('✅ 场景提取成功:', businessData.scene.name)
    
    // 跳转到陪练对话页面，携带场景数据
    await router.push({
      name: 'AIPractice',
      query: {
        mode: 'course',
        courseId: String(course.id),
        sceneData: JSON.stringify(businessData.scene)
      }
    })
    
    console.log('✅ 跳转完成')
  } catch (error: any) {
    console.error('❌ 场景提取失败:', error)
    ElMessage.error(error.message || '场景提取失败，请稍后重试')
  } finally {
    // 关闭Loading
    loading.value = false
    loadingText.value = '正在加载...'
  }
}

/**
 * 加载更多
 */
const loadMore = () => {
  ElMessage.info('加载更多课程...')
}
</script>

<style lang="scss" scoped>
// 全屏Loading遮罩样式（Teleport到body）
.fullscreen-loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
    
    .loading-icon {
      font-size: 60px;
      color: #ffffff;
      animation: rotating 2s linear infinite;
    }
    
    .loading-text {
      color: #ffffff;
      font-size: 18px;
      font-weight: 600;
      line-height: 1.8;
      white-space: pre-line;
      text-align: center;
      max-width: 400px;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.course-center-wrapper {
  // 包裹容器，无样式
}

.course-center-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;

    .page-title {
      font-size: 28px;
      font-weight: 700;
      color: #1a1a1a;
      letter-spacing: -0.5px;
    }

    .header-actions {
      :deep(.el-input) {
        border-radius: 25px;
        
        .el-input__wrapper {
          border-radius: 25px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
          border: 1px solid #e4e7ed;
          transition: all 0.3s;
          
          &:hover {
            border-color: #667eea;
            box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
          }
        }
      }
    }
  }

  .category-filter {
    margin-bottom: 32px;

    .el-radio-group {
      display: flex;
      gap: 12px;

      :deep(.el-radio-button__inner) {
        border-radius: 25px;
        padding: 10px 24px;
        font-weight: 500;
        border: 2px solid #e4e7ed;
        background: #fff;
        transition: all 0.3s;
        
        &:hover {
          color: #667eea;
          border-color: #667eea;
          background: rgba(102, 126, 234, 0.05);
        }
      }

      :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-color: transparent;
        color: #fff;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
      }
    }
  }

  .course-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
    gap: 28px;
    margin-bottom: 48px;

    .course-card {
      background: #fff;
      border-radius: 20px;
      overflow: hidden;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;

      &:hover {
        transform: translateY(-8px);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);

        .primary-btn {
          transform: translateY(-2px);
          box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }
      }

      .card-body {
        padding: 20px;

        .card-header-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .card-badges {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;

            .badge {
              padding: 4px 10px;
              border-radius: 16px;
              font-size: 11px;
              font-weight: 600;
              display: flex;
              align-items: center;
              gap: 3px;
              
              &.badge-new {
                background: linear-gradient(135deg, #ff4757 0%, #ff6348 100%);
                color: #fff;
                box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3);
              }
              
              &.badge-required {
                background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
                color: #fff;
              }
              
              &.badge-optional {
                background: #f4f4f5;
                color: #606266;
              }
            }
          }

          .progress-badge {
            display: flex;
            align-items: center;
            
            .progress-text {
              padding: 4px 12px;
              border-radius: 16px;
              font-size: 12px;
              font-weight: 600;
              background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
              color: #fff;
              box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
            }
          }
        }

        .course-title {
          font-size: 18px;
          font-weight: 700;
          color: #1a1a1a;
          margin-bottom: 8px;
          line-height: 1.3;
        }

        .course-description {
          font-size: 13px;
          color: #606266;
          line-height: 1.6;
          margin-bottom: 16px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .course-stats {
          display: flex;
          gap: 16px;
          margin-bottom: 16px;

          .stat-item {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            color: #909399;

            .el-icon {
              font-size: 14px;
              color: #667eea;
            }
          }
        }
      }

      .card-footer {
        padding: 0 20px 20px;
        display: flex;
        flex-direction: column;
        gap: 10px;

        .action-btn {
          height: 38px;
          border: none;
          border-radius: 10px;
          font-size: 14px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          
          &.primary-btn {
            width: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            box-shadow: 0 3px 10px rgba(102, 126, 234, 0.25);
            
            &:hover {
              background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
              transform: translateY(-1px);
              box-shadow: 0 5px 15px rgba(102, 126, 234, 0.35);
            }
            
            &:active {
              transform: translateY(0);
            }
          }

          &.secondary-btn {
            flex: 1;
            background: #fff;
            border: 1.5px solid #e4e7ed;
            color: #606266;
            font-size: 13px;
            font-weight: 500;
            
            &:hover {
              border-color: #667eea;
              color: #667eea;
              background: rgba(102, 126, 234, 0.05);
              transform: translateY(-1px);
            }
          }
          
          &.exam-btn {
            flex: 1;
            background: #fff;
            border: 1.5px solid #e6a23c;
            color: #e6a23c;
            font-size: 13px;
            font-weight: 500;
            
            &:hover {
              background: rgba(230, 162, 60, 0.08);
              transform: translateY(-1px);
            }
          }
          
          &.practice-btn {
            flex: 1;
            background: #fff;
            border: 1.5px solid #67c23a;
            color: #67c23a;
            font-size: 13px;
            font-weight: 500;
            
            &:hover {
              background: rgba(103, 194, 58, 0.08);
              transform: translateY(-1px);
            }
          }

          .el-icon {
            font-size: 16px;
          }
          
          span {
            white-space: nowrap;
          }
        }

        .secondary-actions {
          display: flex;
          gap: 8px;
          width: 100%;
        }
      }
    }
  }

  .empty-state {
    padding: 80px 20px;
    text-align: center;
    
    :deep(.el-empty) {
      .el-empty__description {
        font-size: 16px;
        color: #909399;
      }
    }
  }

  .load-more {
    text-align: center;
    margin-bottom: 60px;

    .el-button {
      min-width: 200px;
      height: 44px;
      border-radius: 22px;
      font-size: 15px;
      font-weight: 500;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .course-center-container {
    .course-grid {
      grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
      gap: 20px;
    }
  }
}

@media (max-width: 768px) {
  .course-center-container {
    padding: 0 12px;

    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      margin-bottom: 24px;

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

      .header-actions {
        .el-input {
          width: 100% !important;
        }
      }
    }

    .category-filter {
      margin-bottom: 24px;
      
      .el-radio-group {
        width: 100%;
        overflow-x: auto;
        flex-wrap: nowrap;
        padding-bottom: 8px;
        -webkit-overflow-scrolling: touch;
        gap: 8px;

        &::-webkit-scrollbar {
          display: none; // Hide scrollbar for cleaner look
        }

        :deep(.el-radio-button__inner) {
          padding: 8px 16px;
          font-size: 13px;
        }
      }
    }

    .course-grid {
      grid-template-columns: 1fr;
      gap: 16px;

      .course-card {
        border-radius: 16px;
        
        .card-body {
          padding: 16px;
          
          .course-title {
             font-size: 17px;
          }
        }

        .card-footer {
          padding: 0 16px 16px;
          gap: 12px;

          .action-btn {
            height: 40px;
            font-size: 14px;
            
            .el-icon {
              font-size: 16px;
            }
          }

          .secondary-actions {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px;
            
            .action-btn {
              flex-direction: column;
              height: auto;
              padding: 8px 2px;
              gap: 4px;
              border-radius: 8px;
              
              &.secondary-btn,
              &.exam-btn,
              &.practice-btn {
                font-size: 11px;
                
                span {
                  display: block !important;
                  line-height: 1;
                  transform: scale(0.95);
                }
                
                .el-icon {
                  margin: 0;
                  font-size: 18px;
                  margin-bottom: 2px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
