<template>
  <div class="lesson-resources-content">
    <!-- 核心资源列表 -->
    <div v-if="hasResources" class="resources-grid">
      <!-- 图片资源 -->
      <div v-if="lesson.images?.length" class="resource-category">
        <div class="category-header">
          <PictureOutlined /> 图片资源 ({{ lesson.images.length }})
        </div>
        <div class="resource-list">
          <div
            v-for="(image, idx) in lesson.images"
            :key="idx"
            class="resource-item image-item"
            @click="handlePreview('image', image)"
          >
            <div class="image-wrapper">
              <a-spin :spinning="imageLoadingStates[idx] === 'loading'" :indicator="null">
                <img
                  :src="getFileUrl(image.path)"
                  :alt="image.name || `图片${idx + 1}`"
                  :style="{ display: imageLoadingStates[idx] === 'loaded' ? 'block' : 'none' }"
                  @load="imageLoadingStates[idx] = 'loaded'"
                  @error="imageLoadingStates[idx] = 'error'"
                />
              </a-spin>
              <!-- 加载失败占位图 -->
              <div v-if="imageLoadingStates[idx] === 'error'" class="error-placeholder">
                <PictureOutlined style="font-size: 32px; color: #999;" />
                <span>加载失败</span>
              </div>
            </div>
            <div class="resource-info">
              <div class="resource-name">{{ image.name || `图片${idx + 1}` }}</div>
              <div class="resource-action">点击预览</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 视频资源 -->
      <div v-if="lesson.videos?.length" class="resource-category">
        <div class="category-header">
          <VideoCameraOutlined /> 视频资源 ({{ lesson.videos.length }})
        </div>
        <div class="resource-list">
          <div
            v-for="(video, idx) in lesson.videos"
            :key="idx"
            class="resource-item video-item"
            @click="handlePreview('video', video)"
          >
            <VideoCameraOutlined class="resource-icon" />
            <div class="resource-info">
              <div class="resource-name">{{ video.name || `视频${idx + 1}` }}</div>
              <div class="resource-action">点击播放</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 音频资源 -->
      <div v-if="lesson.audioList?.length" class="resource-category">
        <div class="category-header">
          <AudioOutlined /> 音频资源 ({{ lesson.audioList.length }})
        </div>
        <div class="resource-list">
          <div
            v-for="(audio, idx) in lesson.audioList"
            :key="idx"
            class="resource-item audio-item"
            @click="handlePreview('audio', audio)"
          >
            <AudioOutlined class="resource-icon" />
            <div class="resource-info">
              <div class="resource-name">{{ audio.name || `音频${idx + 1}` }}</div>
              <div class="resource-action">点击播放</div>
            </div>
          </div>
        </div>
      </div>

      <!-- PPT资源 -->
      <div v-if="lesson.pptFiles?.length" class="resource-category">
        <div class="category-header">
          <FilePptOutlined /> 课件资源 ({{ lesson.pptFiles.length }})
        </div>
        <div class="resource-list">
          <div
            v-for="(ppt, idx) in lesson.pptFiles"
            :key="idx"
            class="resource-item ppt-item"
            @click="handlePreview('ppt', ppt)"
          >
            <FilePptOutlined class="resource-icon" />
            <div class="resource-info">
              <div class="resource-name">{{ ppt.name || `课件${idx + 1}` }}</div>
              <div class="resource-action">点击预览</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 文档资源 -->
      <div v-if="lesson.documents?.length" class="resource-category">
        <div class="category-header">
          <FileTextOutlined /> 文档资源 ({{ lesson.documents.length }})
        </div>
        <div class="resource-list">
          <div
            v-for="(doc, idx) in lesson.documents"
            :key="idx"
            class="resource-item doc-item"
            @click="handlePreview('pdf', doc)"
          >
            <FileTextOutlined class="resource-icon" />
            <div class="resource-info">
              <div class="resource-name">{{ doc.name || `文档${idx + 1}` }}</div>
              <div class="resource-action">点击预览</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <a-empty v-else description="暂无核心资源" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import {
  PictureOutlined, VideoCameraOutlined, AudioOutlined,
  FilePptOutlined, FileTextOutlined,
} from '@ant-design/icons-vue';

const props = defineProps<{
  lesson: any;
}>();

const emit = defineEmits<{
  'preview-resource': [type: string, resource: any];
}>();

// 图片加载状态管理：'loading' | 'loaded' | 'error'
const imageLoadingStates = ref<Record<number, 'loading' | 'loaded' | 'error'>>({});

// 监听 lesson.images 变化，重置加载状态
watch(() => props.lesson?.images, (newImages) => {
  if (!newImages) {
    imageLoadingStates.value = {};
    return;
  }

  // 重置所有图片的加载状态为 'loading'
  const newStates: Record<number, 'loading' | 'loaded' | 'error'> = {};
  newImages.forEach((_: any, idx: number) => {
    newStates[idx] = 'loading';
  });
  imageLoadingStates.value = newStates;
}, { immediate: true, deep: true });

const hasResources = computed(() => {
  const l = props.lesson;
  return (l.images?.length || 0) +
    (l.videos?.length || 0) +
    (l.audioList?.length || 0) +
    (l.pptFiles?.length || 0) +
    (l.documents?.length || 0) > 0;
});

const getFileUrl = (filePath: string | null | undefined): string => {
  if (!filePath) return '';
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath;
  }
  if (filePath.startsWith('/uploads')) {
    const SERVER_BASE = import.meta.env.VITE_SERVER_BASE_URL || 'http://localhost:3000';
    return `${SERVER_BASE}${filePath}`;
  }
  if (filePath.includes('/uploads/')) {
    const SERVER_BASE = import.meta.env.VITE_SERVER_BASE_URL || 'http://localhost:3000';
    return `${SERVER_BASE}${filePath}`;
  }
  const SERVER_BASE = import.meta.env.VITE_SERVER_BASE_URL || 'http://localhost:3000';
  return `${SERVER_BASE}/uploads/${filePath}`;
};

const handlePreview = (type: string, resource: any) => {
  const url = getFileUrl(resource.path);
  if (!url) {
    message.warning('资源文件不存在');
    return;
  }

  // 只发送预览事件到父组件，让弹窗处理预览
  emit('preview-resource', type, { ...resource, url });
};
</script>

<style scoped>
.lesson-resources-content {
  min-height: 400px;
}

.resources-grid {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.resource-category {
  background: white;
}

.category-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.resource-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
}

.resource-item {
  background: #FAFAFA;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
  transition: all 0.2s;
  cursor: pointer;
}

.resource-item:hover {
  border-color: #FF8C42;
  background: #FFF9F5;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 140, 66, 0.15);
}

.image-item {
  padding: 8px;
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 6px;
  margin-bottom: 8px;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.image-wrapper :deep(.ant-spin) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #999;
  font-size: 12px;
}

.resource-icon {
  font-size: 32px;
  color: #FF8C42;
  margin-bottom: 8px;
}

.resource-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.resource-name {
  font-size: 12px;
  color: #666;
  text-align: center;
  word-break: break-word;
  margin-bottom: 4px;
}

.resource-action {
  font-size: 11px;
  color: #FF8C42;
  text-align: center;
}
</style>
