<template>
  <div class="banner-carousel">
    <!-- 骨架屏 -->
    <div v-if="loading" class="banner-skeleton">
      <el-skeleton :rows="3" animated />
      <div class="skeleton-content">
        <el-skeleton-item variant="h1" style="width: 60%; height: 40px; margin-bottom: 20px;" />
        <el-skeleton-item variant="text" style="width: 80%; height: 20px; margin-bottom: 15px;" />
        <el-skeleton-item variant="text" style="width: 60%; height: 20px; margin-bottom: 30px;" />
        <el-skeleton-item variant="button" style="width: 120px; height: 40px;" />
      </div>
    </div>
    
    <!-- 轮播图 -->
    <el-carousel 
      v-else
      ref="carouselRef"
      :interval="4000" 
      height="400px"
      indicator-position="none"
      arrow="never"
      class="banner-carousel-container"
      @change="handleCarouselChange"
    >
      <el-carousel-item v-for="(item, index) in bannerList" :key="index">
        <div 
          class="banner-item" 
          :style="{ backgroundImage: `url(${item.image})` }"
          @click="handleBannerClick(item, $event)"
        >
          <div class="banner-content">
           
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
    
    <!-- 自定义指示器 -->
    <div v-if="!loading" class="custom-indicators">
      <div 
        v-for="(item, index) in bannerList" 
        :key="index"
        class="indicator-item"
        :class="{ active: currentIndex === index }"
        @click="goToSlide(index)"
      >
        <el-icon class="indicator-icon">
          <CaretRight />
        </el-icon>
        <span class="indicator-text">{{ item.title }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { CaretRight } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getBannerList } from '@/api/banner'

// 路由实例
const router = useRouter()

// 加载状态
const loading = ref(true)
// 当前轮播图索引
const currentIndex = ref(0)
// 轮播图引用
const carouselRef = ref(null)

// Banner数据
const bannerList = ref([])

// 获取Banner列表
const fetchBannerList = async () => {
  console.log('触发获取Banner列表')
  
  try {
    const res = await getBannerList()

    bannerList.value = res.data
    // 数据加载完成后预加载图片
    console.log('获取Banner列表完成', bannerList.value)
    preloadImages()
  } catch (error) {
    console.error('获取Banner列表失败:', error)
    // 即使API失败，也要隐藏loading状态
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
}

// 预加载图片
const preloadImages = () => {
  if (bannerList.value.length === 0) {
    loading.value = false
    return
  }
  
  const imagePromises = bannerList.value.map(item => {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = () => resolve()
      img.onerror = () => reject()
      img.src = item.image
    })
  })
  
  Promise.all(imagePromises)
    .then(() => {
      // 所有图片加载完成后，延迟一点时间让骨架屏动画更自然
      setTimeout(() => {
        loading.value = false
      }, 500)
    })
    .catch(() => {
      // 即使有图片加载失败，也要显示轮播图
      setTimeout(() => {
        loading.value = false
      }, 500)
    })
}

// 轮播图切换处理
const handleCarouselChange = (index) => {
  currentIndex.value = index
}

// 跳转到指定轮播图
const goToSlide = (index) => {
  if (carouselRef.value) {
    carouselRef.value.setActiveItem(index)
  }
}

// Banner点击跳转处理
const handleBannerClick = (item, event) => {
  // 阻止事件冒泡，避免影响轮播图的其他交互
  event.stopPropagation()
  
  if (!item.link) return
  
  if (item.linkType === 'internal') {
    // 链接验证和类型检查
    console.log('[BannerCarousel] Banner点击跳转:', {
      title: item.title,
      link: item.link,
      contentType: item.contentType,
      dataSource: 'BannerCarousel'
    })
    
    // 验证链接格式是否正确
    const courseMatch = item.link.match(/^\/course\/(\d+)$/)
    const workflowMatch = item.link.match(/^\/workflow\/(\d+)$/)
    
    if (courseMatch || workflowMatch) {
      // 链接格式正确，直接跳转
      router.push(item.link)
    } else if (item.contentType === 'course' && !courseMatch) {
      // Banner标注为课程，但链接格式不正确
      console.warn('[BannerCarousel] 警告：课程Banner链接格式错误!', item)
      // 尝试从链接中提取ID并修正
      const idMatch = item.link.match(/\/(\d+)$/)
      if (idMatch) {
        const correctedLink = `/course/${idMatch[1]}`
        console.log('[BannerCarousel] 自动修正链接:', item.link, '->', correctedLink)
        router.push(correctedLink)
      } else {
        router.push(item.link)
      }
    } else if (item.contentType === 'workflow' && !workflowMatch) {
      // Banner标注为工作流，但链接格式不正确
      console.warn('[BannerCarousel] 警告：工作流Banner链接格式错误!', item)
      // 尝试从链接中提取ID并修正
      const idMatch = item.link.match(/\/(\d+)$/)
      if (idMatch) {
        const correctedLink = `/workflow/${idMatch[1]}`
        console.log('[BannerCarousel] 自动修正链接:', item.link, '->', correctedLink)
        router.push(correctedLink)
      } else {
        router.push(item.link)
      }
    } else {
      // 内部路由跳转
      router.push(item.link)
    }
  } else if (item.linkType === 'external') {
    // 外部链接跳转，新窗口打开
    window.open(item.link, '_blank', 'noopener,noreferrer')
  }
}

onMounted(() => {
  fetchBannerList()
})
</script>

<style scoped>
.banner-carousel {
  width: 100%;
  height: 400px;
  overflow: hidden;
  margin: 0;
  padding: 0;
  position: relative;
  display: block;
  clear: both;
}

.banner-skeleton {
  width: 100%;
  height: 400px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.skeleton-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  width: 80%;
  max-width: 600px;
}

.banner-carousel-container {
  width: 100%;
  height: 100%;
}

.banner-item {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.3s ease, filter 0.3s ease;
}

.banner-item:hover {
  transform: scale(1.02);
  filter: brightness(1.1);
}

.banner-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.1) 100%);
  z-index: 1;
}

.banner-content {
  position: relative;
  z-index: 2;
  text-align: center;
  color: white;
  max-width: 600px;
  padding: 0 20px;
}

.banner-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 1rem;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}

.banner-description {
  font-size: 1.2rem;
  margin-bottom: 2rem;
  line-height: 1.6;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}

.banner-button {
  font-size: 1.1rem;
  padding: 12px 30px;
  font-style: oblique;
  border-radius: 25px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
  transition: all 0.3s ease;
  background-color: #E13F38;
  border-color: #E13F38;
 
}

.banner-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}

/* 自定义指示器样式 */
.custom-indicators {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  background: transparent;
  z-index: 10;
}

.indicator-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 130px;
  height: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: transparent;
  border: none;
  padding: 0;
  gap: 4px;
}

.indicator-item:hover {
  transform: translateY(-1px);
}

.indicator-item.active {
  background: transparent;
}

.indicator-icon {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  padding: 0;
  transition: all 0.3s ease;
}

.indicator-item.active .indicator-icon {
  color:rgba(0, 239, 255, 1);
}

.indicator-text {
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  letter-spacing: 0px;
  color: rgba(255, 255, 255, 0.9);
  transition: all 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.indicator-item.active .indicator-text {
  color: rgba(0, 239, 255, 1);
}

/* Element Plus 轮播组件样式覆盖 */
:deep(.el-carousel__item) {
  overflow: hidden;
}

:deep(.el-carousel__indicators) {
  bottom: 20px;
}

:deep(.el-carousel__indicator) {
  background-color: rgba(255,255,255,0.5);
}

:deep(.el-carousel__indicator.is-active) {
  background-color: #fff;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(255,255,255,0.8);
  color: #333;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  font-size: 18px;
}

:deep(.el-carousel__arrow:hover) {
  background-color: #fff;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .custom-indicators {
    gap: 15px;
  }
  
  .indicator-item {
    width: 110px;
  }
  
  .indicator-text {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .banner-title {
    font-size: 1.8rem;
  }
  
  .banner-description {
    font-size: 1rem;
  }
  
  .banner-button {
    font-size: 1rem;
    padding: 10px 25px;
  }
  
  .custom-indicators {
    gap: 10px;
    height: 40px;
  }
  
  .indicator-item {
    width: auto;
    min-width: 30px;
    height: 30px;
  }
  
  /* 在平板尺寸仍显示文字但缩小 */
  .indicator-text {
    font-size: 12px;
    max-width: 80px;
  }
}

@media (max-width: 640px) {
  /* 小屏幕隐藏指示器文字，只保留图标 */
  .indicator-text {
    display: none;
  }
  
  .indicator-item {
    width: 24px;
    height: 24px;
    justify-content: center;
    gap: 0;
  }
  
  .indicator-icon {
    font-size: 14px;
  }
  
  .custom-indicators {
    gap: 8px;
    height: 35px;
  }
}

@media (max-width: 480px) {
  .banner-title {
    font-size: 1.5rem;
  }
  
  .banner-description {
    font-size: 0.9rem;
  }
  
  .banner-carousel {
    height: 300px;
  }
  
  .banner-skeleton {
    height: 300px;
  }
  
  /* 极小屏幕进一步缩小指示器 */
  .indicator-item {
    width: 20px;
    height: 20px;
  }
  
  .indicator-icon {
    font-size: 12px;
  }
  
  .custom-indicators {
    gap: 6px;
    height: 30px;
  }
}

@media (max-width: 360px) {
  /* 超小屏幕完全隐藏指示器 */
  .custom-indicators {
    display: none;
  }
  
  .banner-carousel {
    height: 250px;
  }
  
  .banner-skeleton {
    height: 250px;
  }
}
</style> 