<template>
  <div class="course-management-container">
    <div class="page-header">
      <h1 class="page-title">课程管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="createCourse">
          <el-icon class="el-icon--left"><Plus /></el-icon>
          新建课程
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="filterForm.keyword" 
            placeholder="搜索课程名称或描述" 
            clearable 
            @input="handleRealTimeSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select 
            v-model="filterForm.category" 
            placeholder="全部分类" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="技术" value="technology" />
            <el-option label="管理" value="management" />
            <el-option label="业务/产品" value="business" />
            <el-option label="通用" value="general" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态">
          <el-select 
            v-model="filterForm.status" 
            placeholder="全部状态" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <el-icon class="el-icon--left"><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 当前筛选条件显示 -->
      <div v-if="hasActiveFilters" class="filter-tags">
        <span class="filter-label">当前筛选：</span>
        <el-tag 
          v-if="filterForm.keyword" 
          closable 
          @close="clearKeyword"
          type="primary"
        >
          关键词：{{ filterForm.keyword }}
        </el-tag>
        <el-tag 
          v-if="filterForm.category" 
          closable 
          @close="clearCategory"
          type="success"
        >
          分类：{{ getCategoryText(filterForm.category) }}
        </el-tag>
        <el-tag 
          v-if="filterForm.status" 
          closable 
          @close="clearStatus"
          type="warning"
        >
          状态：{{ getStatusText(filterForm.status) }}
        </el-tag>
        <el-button 
          link 
          type="danger" 
          size="small" 
          @click="handleReset"
          class="clear-all-btn"
        >
          清空全部
        </el-button>
    </div>

      <!-- 搜索结果统计 -->
      <div class="search-result-info">
        <span class="result-count">
          共找到 <strong>{{ pagination.total }}</strong> 门课程
          <span v-if="hasActiveFilters" class="filter-hint">（已筛选）</span>
        </span>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="course-list-section card">
      <div class="section-header">
        <h3>课程列表</h3>
        <div class="view-controls">
          <el-button-group>
            <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
              <el-icon><Grid /></el-icon>
            </el-button>
            <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
              <el-icon><List /></el-icon>
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'">
        <div v-if="paginatedCourses.length > 0" class="course-grid">
          <div v-for="course in paginatedCourses" :key="course.id" class="course-card">
          <div class="course-info">
            <div class="course-header">
            <h4 class="course-title">{{ course.name }}</h4>
              <el-tag :type="getStatusTagType(course.status)" size="small">
                {{ getStatusText(course.status) }}
            </el-tag>
      </div>
            <p class="course-description">{{ course.description }}</p>
            <div class="course-meta">
                  <span class="meta-item">
                    <el-icon><User /></el-icon>
                {{ course.studentCount || 0 }} 人学习
                  </span>
                  <span class="meta-item">
                <el-icon><Clock /></el-icon>
                {{ course.duration || '待定' }}
              </span>
              <span class="meta-item">
                <el-tag type="info" size="small">{{ getCategoryText(course.category) }}</el-tag>
                  </span>
                </div>
            <div class="course-actions">
              <el-button size="small" @click="viewCourseDetail(course)">查看详情</el-button>
              <el-button size="small" type="primary" @click="editCourse(course)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteCourse(course)">删除</el-button>
            </div>
          </div>
        </div>
        </div>
        
        <!-- 空状态显示 -->
        <div v-else class="empty-state">
          <el-empty 
            :description="hasActiveFilters ? '没有符合条件的课程' : '暂无课程数据'"
            :image-size="120"
          >
            <el-button v-if="hasActiveFilters" type="primary" @click="handleReset">
              清空筛选条件
            </el-button>
            <el-button v-else type="primary" @click="createCourse">
              创建第一门课程
            </el-button>
          </el-empty>
        </div>
      </div>
            
      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'">
        <el-table v-if="paginatedCourses.length > 0" :data="paginatedCourses" style="width: 100%">
          <el-table-column prop="name" label="课程名称" width="200" />
          <el-table-column prop="category" label="分类" width="120">
                <template #default="scope">
            {{ getCategoryText(scope.row.category) }}
                </template>
              </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
                </template>
              </el-table-column>
          <el-table-column prop="studentCount" label="学习人数" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200">
                <template #default="scope">
              <el-button size="small" @click="viewCourseDetail(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="editCourse(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteCourse(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
        <!-- 列表视图空状态显示 -->
        <div v-else class="empty-state">
          <el-empty 
            :description="hasActiveFilters ? '没有符合条件的课程' : '暂无课程数据'"
            :image-size="120"
          >
            <el-button v-if="hasActiveFilters" type="primary" @click="handleReset">
              清空筛选条件
                    </el-button>
            <el-button v-else type="primary" @click="createCourse">
              创建第一门课程
                        </el-button>
          </el-empty>
                      </div>
                        </div>

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

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Grid,
  List,
  User,
  Clock,
  Refresh,
} from '@element-plus/icons-vue'
import { courseApi, type Course } from '@/api/course'

const router = useRouter()

// 响应式数据
const viewMode = ref('grid')
const filterForm = reactive({
  keyword: '',
  category: '',
  status: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 6,
  total: 0
})

// 课程数据（来自真实后端）
const courses = ref<any[]>([])

// 加载课程列表（真实查询后端）
async function fetchCourses() {
  try {
    const params: any = {
      page: pagination.currentPage,
      size: pagination.pageSize,
    }
    if (filterForm.keyword) params.keyword = filterForm.keyword
    if (filterForm.category) params.category = filterForm.category
    if (filterForm.status) params.status = filterForm.status

    const res = await courseApi.list(params)
    if (res.code === 200) {
      const data = res.data
      pagination.total = data.total || 0
      // 映射后端字段到页面展示字段
      courses.value = (data.items || []).map((c: Course) => ({
        id: c.id,
        name: c.name,
        description: c.description || '',
        category: c.category,
        status: c.status,
        // 后端为 duration_hours，这里转为可读
        duration: c.duration_hours ? `${c.duration_hours}小时` : undefined,
        studentCount: c.student_count || 0,
        isNew: c.is_new || false,
        createTime: c.created_at?.replace('T', ' ').substring(0, 19)
      }))
    } else {
      ElMessage.error(res.message || '加载课程失败')
    }
  } catch (error: any) {
    console.error('获取课程列表失败:', error)
    ElMessage.error(error.message || '获取课程列表失败')
  }
}

// 来自服务端分页的当前页数据
const filteredCourses = computed(() => courses.value)

// 当前页显示的课程数据（服务端已分页，直接返回）
const paginatedCourses = computed(() => filteredCourses.value)

// 是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return !!(filterForm.keyword || filterForm.category || filterForm.status)
})

// 方法
/**
 * 创建新课程
 */
const createCourse = () => {
  router.push('/manager/create-course')
}

/**
 * 实时搜索处理
 */
const handleRealTimeSearch = () => {
  pagination.currentPage = 1
  fetchCourses()
}

/**
 * 重置搜索条件
 */
const handleReset = () => {
  filterForm.keyword = ''
  filterForm.category = ''
  filterForm.status = ''
  pagination.currentPage = 1
  ElMessage.success('已重置所有筛选条件')
  fetchCourses()
}

/**
 * 清除关键词筛选
 */
const clearKeyword = () => {
  filterForm.keyword = ''
  pagination.currentPage = 1
  fetchCourses()
}

/**
 * 清除分类筛选
 */
const clearCategory = () => {
  filterForm.category = ''
  pagination.currentPage = 1
  fetchCourses()
}

/**
 * 清除状态筛选
 */
const clearStatus = () => {
  filterForm.status = ''
  pagination.currentPage = 1
  fetchCourses()
}

/**
 * 查看课程详情
 */
const viewCourseDetail = (course: any) => {
  ElMessageBox.alert(
    `
    <div style="text-align: left; line-height: 1.6;">
      <h4 style="margin: 0 0 10px 0; color: #409eff;">${course.name}</h4>
      <p><strong>分类：</strong>${getCategoryText(course.category)}</p>
      <p><strong>状态：</strong>${getStatusText(course.status)}</p>
      <p><strong>学习人数：</strong>${course.studentCount} 人</p>
      <p><strong>课程时长：</strong>${course.duration}</p>
      <p><strong>创建时间：</strong>${course.createTime}</p>
      <p><strong>课程描述：</strong></p>
      <p style="color: #666; margin-left: 10px;">${course.description}</p>
    </div>
    `,
    '课程详情',
    {
      confirmButtonText: '知道了',
      dangerouslyUseHTMLString: true
    }
  )
}

/**
 * 编辑课程
 */
const editCourse = (course: any) => {
  router.push('/manager/edit-course/' + course.id)
}

/**
 * 删除课程
 */
const deleteCourse = (course: any) => {
  ElMessageBox.confirm(
    '确定要删除课程"' + course.name + '"吗？删除后将无法恢复。',
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await courseApi.delete(course.id)
        if (res && res.code === 200 && res.data === true) {
          ElMessage.success('课程"' + course.name + '"已删除')
          if (courses.value.length === 1 && pagination.currentPage > 1) {
            pagination.currentPage -= 1
          }
          fetchCourses()
        } else {
          throw new Error(res?.message || '删除失败')
        }
      } catch (err: any) {
        const msg = err?.message || '删除课程失败'
        ElMessage.error(msg)
      }
    })
    .catch((action: any) => {
      if (action === 'cancel' || action === 'close') {
        ElMessage.info('已取消删除')
      }
    })
}

const getCategoryText = (category: string) => {
  const map: Record<string, string> = {
    technology: '技术',
    management: '管理',
    business: '业务/产品',
    general: '通用'
  }
  return map[category] || '未知'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    published: '已发布',
    draft: '草稿',
    archived: '已归档'
  }
  return map[status] || '未知'
}

const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    published: 'success',
    draft: 'warning',
    archived: 'info'
  }
  return map[status] || 'info'
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  ElMessage.success('每页显示 ' + val + ' 条记录')
  fetchCourses()
}

/**
 * 当前页码改变
 */
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchCourses()
}

// 初始化加载
fetchCourses()
</script>

<style scoped>
.course-management-container {
    padding: 20px;
}

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

    .page-title {
      font-size: 24px;
        font-weight: 600;
        color: #333;
  margin: 0;
}

.card {
        background: #fff;
  border-radius: 8px;
          padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filter-form {
            display: flex;
  flex-wrap: wrap;
            gap: 16px;
  margin-bottom: 0;
}

.filter-tags {
  margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #f0f0f0;
        display: flex;
        align-items: center;
  flex-wrap: wrap;
        gap: 8px;
}

.filter-label {
        color: #666;
    font-size: 14px;
  margin-right: 8px;
}

.clear-all-btn {
  margin-left: 8px;
}

.search-result-info {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.result-count {
            color: #666;
            font-size: 14px;
}

.result-count strong {
            color: #409eff;
      font-weight: 600;
    }
    
.filter-hint {
  color: #e6a23c;
  font-size: 12px;
}

.section-header {
    display: flex;
      justify-content: space-between;
          align-items: center;
      margin-bottom: 20px;
}

.section-header h3 {
          margin: 0;
          font-size: 18px;
          color: #333;
    }

    .course-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
}

      .course-card {
    border: 1px solid #e4e7ed;
      border-radius: 8px;
      overflow: hidden;
  transition: box-shadow 0.3s;
}

.course-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

.course-info {
        padding: 20px;
}

.course-header {
          display: flex;
    justify-content: space-between;
  align-items: flex-start;
      margin-bottom: 12px;
}

.course-title {
      font-size: 16px;
        font-weight: 600;
        color: #333;
          margin: 0 0 8px 0;
        }
        
.course-description {
            color: #666;
          font-size: 14px;
        margin: 0 0 12px 0;
            line-height: 1.4;
          }
          
.course-meta {
            display: flex;
  gap: 16px;
          margin-bottom: 12px;
      }
          
          .meta-item {
      display: flex;
      align-items: center;
            gap: 4px;
          font-size: 12px;
            color: #999;
        }
        
.course-actions {
          display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}
</style>