<template>
  <div class="course-list-view">
    <!-- 页面标题区域 - 带装饰 -->
    <div class="page-header-wrapper">
      <div class="page-header-decoration">
        <div class="decoration-circle c1"></div>
        <div class="decoration-circle c2"></div>
        <div class="decoration-circle c3"></div>
      </div>
      <div class="page-header-content">
        <div class="icon-wrapper">
          <BookOutlined />
        </div>
        <div class="header-text">
          <h1 class="page-title">课程中心</h1>
          <p class="page-subtitle">发现精彩的绘本课程，开启美妙的阅读之旅</p>
        </div>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <div class="filter-item">
        <span class="filter-label">年级</span>
        <a-select v-model:value="filters.grade" placeholder="全部年级" style="width: 120px;" allowClear
          @change="handleFilterChange">
          <a-select-option value="小班">
            小班
          </a-select-option>
          <a-select-option value="中班">
            中班
          </a-select-option>
          <a-select-option value="大班">
            大班
          </a-select-option>
        </a-select>
      </div>
      <div class="filter-item">
        <span class="filter-label">课程类型</span>
        <a-select v-model:value="filters.lessonType" placeholder="全部类型" style="width: 130px;" allowClear
          @change="handleFilterChange">
          <a-select-option value="INTRODUCTION">导入课</a-select-option>
          <a-select-option value="COLLECTIVE">集体课</a-select-option>
          <a-select-option value="LANGUAGE">语言</a-select-option>
          <a-select-option value="HEALTH">健康</a-select-option>
          <a-select-option value="SCIENCE">科学</a-select-option>
          <a-select-option value="SOCIAL">社会</a-select-option>
          <a-select-option value="ART">艺术</a-select-option>
        </a-select>
      </div>
      <div class="filter-item search-box">
        <a-input-search v-model:value="filters.keyword" placeholder="搜索课程名称..." style="width: 240px;"
          @search="handleFilterChange" />
      </div>
      <div class="filter-item filter-right">
        <a-select v-model:value="filters.sort" style="width: 130px;" @change="handleFilterChange">
          <a-select-option value="popular">
            <FireOutlined /> 最受欢迎
          </a-select-option>
          <a-select-option value="newest">
            <StarOutlined /> 最新发布
          </a-select-option>
          <a-select-option value="rating">
            <StarFilled /> 评分最高
          </a-select-option>
        </a-select>
      </div>
    </div>

    <!-- 课程列表 -->
    <a-spin :spinning="loading">
      <div class="course-grid">
        <div v-for="course in courses" :key="course.id" class="course-card" @click="viewCourseDetail(course)">
          <!-- 封面区域 -->
          <div class="course-cover">
            <img v-if="course.pictureUrl" :src="getImageUrl(course.pictureUrl)" class="cover-image" />
            <div v-else class="cover-placeholder">
              <div class="placeholder-icon">
                <BookFilled />
              </div>
              <div class="placeholder-text">精彩绘本</div>
            </div>
            <!-- 评分徽章 -->
            <div class="rating-badge" v-if="(course.avgRating ?? 0) > 0">
              <span class="rating-star">
                <StarFilled />
              </span>
              <span class="rating-value">{{ (course.avgRating ?? 0).toFixed(1) }}</span>
            </div>
          </div>

          <!-- 卡片内容 -->
          <div class="course-content">
            <h3 class="course-title">{{ course.name }}</h3>
            <p class="course-book" v-if="course.pictureBookName">
              <BookOutlined /> {{ course.pictureBookName }}
            </p>

            <!-- 标签区域：年级 + 领域 + 课程环节（lessonTags） -->
            <div class="course-tags">
              <a-tag v-for="tag in (course.gradeTags || [])" :key="'g-' + tag" size="small"
                :style="getGradeTagStyle(tag)">{{ tag }}</a-tag>
              <a-tag v-for="tag in (course.domainTags || [])" :key="'d-' + tag" size="small"
                :style="getDomainTagStyle(tag)">{{ tag }}</a-tag>
              <a-tag v-for="(lt, idx) in (course.lessonTags || [])" :key="'l-' + idx" size="small"
                :style="getLessonTagStyle(lt.lessonType)">
                {{ getLessonTypeName(lt.lessonType) }}
              </a-tag>
            </div>

            <!-- 底部信息 -->
            <div class="course-meta">
              <span class="meta-item">
                <ClockCircleOutlined />
                {{ course.duration }}分钟
              </span>
              <span class="meta-item">
                <TeamOutlined />
                {{ course.usageCount }}次
              </span>
            </div>

            <!-- 操作按钮 -->
            <button class="prepare-btn" @click.stop="prepareCourse(course)">
              <span class="btn-icon">
                <EditOutlined />
              </span>
              开始备课
            </button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="courses.length === 0 && !loading" class="empty-state">
        <div class="icon-wrapper">
          <InboxOutlined />
        </div>
        <p class="empty-text">暂无符合条件的课程</p>
        <p class="empty-hint">试试调整筛选条件吧</p>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.total > pagination.pageSize">
        <a-pagination v-model:current="pagination.current" v-model:page-size="pagination.pageSize"
          :total="pagination.total" show-less-items @change="handlePageChange" />
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  ClockCircleOutlined,
  TeamOutlined,
  InboxOutlined,
  BookOutlined,
  BookFilled,
  StarOutlined,
  StarFilled,
  FireOutlined,
  EditOutlined,
} from '@ant-design/icons-vue';
import * as teacherApi from '@/api/teacher';
import {
  translateGradeTags,
  translateDomainTags,
  getGradeTagStyle,
  getDomainTagStyle,
} from '@/utils/tagMaps';

const router = useRouter();
const loading = ref(false);

const filters = reactive({
  grade: undefined as string | undefined,
  domain: undefined as string | undefined,
  lessonType: undefined as string | undefined,
  keyword: '',
  sort: 'popular',
});

const pagination = reactive({
  current: 1,
  pageSize: 12,
  total: 0,
});

const courses = ref<any[]>([]);

// 解析标签（与套餐管理 parseGradeLevels 对齐，兼容多种格式）
const parseTags = (val: any): string[] => {
  if (!val) return [];
  if (Array.isArray(val)) {
    if (val.length === 0) return [];
    if (val[0]?.toString().startsWith('[')) {
      try {
        return JSON.parse(val.join(''));
      } catch {
        return [];
      }
    }
    return val;
  }
  if (typeof val === 'string') {
    try {
      const parsed = JSON.parse(val);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  }
  return [];
};

// 获取图片完整URL
const getImageUrl = (path: string) => {
  if (!path) return '';
  if (path.startsWith('http')) return path;
  return `${import.meta.env.VITE_SERVER_BASE_URL || 'http://localhost:3000'}${path}`;
};

const handleFilterChange = () => {
  pagination.current = 1;
  loadCourses();
};

const handlePageChange = () => {
  loadCourses();
};

// 课程环节类型：英文码 -> 中文展示名（兼容 INTRODUCTION/INTRO、DOMAIN_* 等后端格式）
const LESSON_TYPE_NAMES: Record<string, string> = {
  INTRODUCTION: '导入课',
  INTRO: '导入课',
  COLLECTIVE: '集体课',
  LANGUAGE: '语言',
  HEALTH: '健康',
  SCIENCE: '科学',
  SOCIAL: '社会',
  ART: '艺术',
  DOMAIN_HEALTH: '健康',
  DOMAIN_LANGUAGE: '语言',
  DOMAIN_SOCIAL: '社会',
  DOMAIN_SCIENCE: '科学',
  DOMAIN_ART: '艺术',
};
const getLessonTypeName = (type: string) => LESSON_TYPE_NAMES[type] || type;

// 课程环节标签样式（按类型区分颜色）
const getLessonTagStyle = (type: string) => {
  const colors: Record<string, { background: string; color: string }> = {
    INTRODUCTION: { background: '#E8F5E9', color: '#2E7D32' },
    INTRO: { background: '#E8F5E9', color: '#2E7D32' },
    COLLECTIVE: { background: '#E3F2FD', color: '#1565C0' },
    LANGUAGE: { background: '#F3E5F5', color: '#7B1FA2' },
    HEALTH: { background: '#FFEBEE', color: '#C62828' },
    SCIENCE: { background: '#E8F5E9', color: '#388E3C' },
    SOCIAL: { background: '#E0F7FA', color: '#00838F' },
    ART: { background: '#FFF3E0', color: '#E65100' },
    DOMAIN_HEALTH: { background: '#FFEBEE', color: '#C62828' },
    DOMAIN_LANGUAGE: { background: '#F3E5F5', color: '#7B1FA2' },
    DOMAIN_SOCIAL: { background: '#E0F7FA', color: '#00838F' },
    DOMAIN_SCIENCE: { background: '#E8F5E9', color: '#388E3C' },
    DOMAIN_ART: { background: '#FFF3E0', color: '#E65100' },
  };
  const c = colors[type] || { background: '#F5F5F5', color: '#666' };
  return { background: c.background, color: c.color, border: 'none' };
};

// 五大领域：中文 -> 后端 domainTags 存储的英文码（用于筛选）
const DOMAIN_TO_CODE: Record<string, string> = {
  健康: 'HEALTH',
  语言: 'LANGUAGE',
  社会: 'SOCIAL',
  科学: 'SCIENCE',
  艺术: 'ART',
};

const loadCourses = async () => {
  loading.value = true;
  try {
    const params: teacherApi.TeacherCourseQueryParams = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };

    if (filters.keyword?.trim()) {
      params.keyword = filters.keyword.trim();
    }

    // 年级筛选：直接传小班/中班/大班，后端匹配 gradeTags
    if (filters.grade) {
      params.grade = filters.grade;
    }

    // 领域筛选：传英文码，后端匹配 domainTags（五大领域课配置）
    if (filters.domain) {
      params.domain = DOMAIN_TO_CODE[filters.domain] ?? filters.domain;
    }

    // 课程类型筛选：传 lessonType，后端匹配 course_lesson
    if (filters.lessonType) {
      params.lessonType = filters.lessonType;
    }

    const data = await teacherApi.getTeacherCourses(params);
    courses.value = (data.items || []).map((item: any) => {
      const gradeTags = parseTags(item.gradeTags);
      const domainTags = parseTags(item.domainTags);
      return {
        ...item,
        gradeTags: translateGradeTags(gradeTags),
        domainTags: translateDomainTags(domainTags),
        lessonTags: item.lessonTags || [],
        duration: item.duration ?? item.durationMinutes ?? 0,
        usageCount: item.usageCount ?? 0,
        avgRating: item.avgRating ?? 0,
        pictureUrl: item.coverImagePath ?? item.pictureUrl,
      };
    });
    pagination.total = Number(data.total) || 0;
  } catch (error: any) {
    message.error(error.message || '获取课程列表失败');
  } finally {
    loading.value = false;
  }
};

const viewCourseDetail = (course: any) => {
  router.push(`/teacher/courses/${course.id}`);
};

const prepareCourse = (course: any) => {
  const id = course?.id;
  if (id == null || id === 'undefined') {
    message.warning('课程信息异常，无法进入备课');
    return;
  }
  router.push(`/teacher/courses/${id}`);
};

onMounted(() => {
  loadCourses();
});
</script>

<style scoped>
/* 页面整体 */
.course-list-view {
  min-height: calc(100vh - 120px);
  background: linear-gradient(180deg, #FFF8F0 0%, #FFFFFF 100%);
  padding: 24px;
  border-radius: 16px;
}

/* 页面标题区域 */
.page-header-wrapper {
  position: relative;
  background: linear-gradient(135deg, #FF8C42 0%, #FFB347 100%);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  overflow: hidden;
}

.page-header-decoration {
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  height: 100%;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.15;
}

.decoration-circle.c1 {
  width: 120px;
  height: 120px;
  background: #fff;
  top: -30px;
  right: 20px;
}

.decoration-circle.c2 {
  width: 80px;
  height: 80px;
  background: #fff;
  top: 40px;
  right: 80px;
}

.decoration-circle.c3 {
  width: 40px;
  height: 40px;
  background: #fff;
  bottom: 10px;
  right: 40px;
}

.page-header-content {
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
}

.header-icon {
  font-size: 48px;
  margin-right: 16px;
}

.icon-wrapper {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  margin-right: 16px;
}

.header-text {
  color: #fff;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
  color: #fff;
}

.page-subtitle {
  font-size: 14px;
  margin: 4px 0 0;
  opacity: 0.9;
  color: #fff;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  background: #fff;
  padding: 16px 20px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

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

.filter-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.filter-right {
  margin-left: auto;
}

.search-box {
  flex: 1;
  max-width: 300px;
}

/* 课程网格 */
.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

/* 课程卡片 */
.course-card {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 2px solid transparent;
}

.course-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(255, 140, 66, 0.15);
  border-color: #FF8C42;
}

/* 封面区域 */
.course-cover {
  position: relative;
  height: 180px;
  overflow: hidden;
}

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

.course-card:hover .cover-image {
  transform: scale(1.05);
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #FFE4C9 0%, #FFF0E0 100%);
}

.placeholder-icon {
  font-size: 56px;
  margin-bottom: 8px;
  color: #FF8C42;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-text {
  font-size: 14px;
  color: #FF8C42;
  font-weight: 500;
}

/* 评分徽章 */
.rating-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(255, 255, 255, 0.95);
  padding: 4px 10px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.rating-star {
  font-size: 12px;
  color: #FFB347;
  display: flex;
  align-items: center;
}

.rating-value {
  font-size: 13px;
  font-weight: 600;
  color: #FF8C42;
}

/* 卡片内容 */
.course-content {
  padding: 16px;
}

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

.course-book {
  font-size: 13px;
  color: #888;
  margin: 0 0 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 标签 */
.course-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 12px;
}

/* 元信息 */
.course-meta {
  display: flex;
  gap: 16px;
  padding-top: 12px;
  border-top: 1px dashed #EEE;
  margin-bottom: 12px;
}

.meta-item {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 备课按钮 */
.prepare-btn {
  width: 100%;
  padding: 10px 16px;
  border: none;
  border-radius: 24px;
  background: linear-gradient(135deg, #FF8C42 0%, #FFB347 100%);
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.prepare-btn:hover {
  background: linear-gradient(135deg, #E67635 0%, #FF8C42 100%);
  transform: scale(1.02);
}

.btn-icon {
  font-size: 16px;
  display: flex;
  align-items: center;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-state .icon-wrapper {
  width: 72px;
  height: 72px;
  margin: 0 auto 16px;
  border-radius: 50%;
  background: linear-gradient(135deg, #F5F5F5 0%, #FAFAFA 100%);
  font-size: 28px;
  color: #BFBFBF;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin: 0 0 8px;
}

.empty-hint {
  font-size: 14px;
  color: #999;
  margin: 0;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #F0F0F0;
}

/* 响应式 */
@media (max-width: 768px) {
  .course-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }

  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    width: 100%;
  }

  .filter-right {
    margin-left: 0;
  }

  .search-box {
    max-width: none;
  }
}
</style>
