<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-option value="混合">混合</a-select-option>
        </a-select>
      </div>
      <div class="filter-item">
        <span class="filter-label">领域</span>
        <a-select
          v-model:value="filters.domain"
          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-option value="科学">科学</a-select-option>
          <a-select-option value="艺术">艺术</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"
        >
          <template #prefix>
            <SearchOutlined style="color: #FF8C42;" />
          </template>
        </a-input-search>
      </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">
              <span class="rating-star"><StarFilled /></span>
              <span class="rating-value">{{ course.avgRating.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>

            <!-- 标签区域 -->
            <div class="course-tags">
              <a-tag
                v-for="tag in course.gradeTags"
                :key="'g-' + tag"
                :style="getGradeTagStyle(tag)"
              >
                {{ tag }}
              </a-tag>
              <a-tag
                v-for="tag in course.domainTags"
                :key="'d-' + tag"
                :style="getDomainTagStyle(tag)"
              >
                {{ tag }}
              </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">
          <SearchOutlined />
        </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,
  SearchOutlined,
  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,
  keyword: '',
  sort: 'popular',
});

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

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

// 年级映射（用于筛选）
const gradeMap: Record<string, string> = {
  SMALL: '小班', small: '小班',
  MIDDLE: '中班', middle: '中班',
  BIG: '大班', big: '大班',
};

// 领域映射（用于筛选）
const domainMap: Record<string, string> = {
  LANGUAGE: '语言', language: '语言', lang_listen: '语言', lang_read: '语言',
  SCIENCE: '科学', science: '科学', science_explore: '科学', math_cog: '数学',
  SOCIAL: '社会', social: '社会', social_interact: '社会', social_adapt: '社会',
  ART: '艺术', art: '艺术', art_music: '艺术', art_create: '艺术',
  HEALTH: '健康', health: '健康', health_motor: '健康', health_hygiene: '健康',
  MATH: '数学', math: '数学',
};

// 获取图片完整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();
};

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

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

    // 年级筛选映射
    if (filters.grade) {
      const gradeKey = Object.keys(gradeMap).find((key) => gradeMap[key] === filters.grade);
      if (gradeKey) {
        params.grade = gradeKey;
      }
    }

    // 领域筛选映射
    if (filters.domain) {
      const domainKey = Object.keys(domainMap).find((key) => domainMap[key] === filters.domain);
      if (domainKey) {
        params.domain = domainKey;
      }
    }

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

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

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

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>
