<template>
  <div class="home-banner">
    <el-carousel :interval="4000" type="card" height="200px" :autoplay="true">
      <el-carousel-item v-for="banner in banners" :key="banner.id">
        <div class="banner-item" @click="handleBannerClick(banner)">
          <ImagePreview
            :src="banner.imageUrl"
            fit="cover"
            class="banner-image"
            :preview-src-list="[]"
          />
          <div class="banner-title" v-if="banner.title">{{ banner.title }}</div>
        </div>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getBannerList } from '../api/banner'
import ImagePreview from './ImagePreview.vue'

const router = useRouter()
const banners = ref([])
const loading = ref(false)

// 获取轮播图列表
const fetchBanners = async () => {
  loading.value = true
  try {
    const res = await getBannerList()
    console.log('获取首页轮播图响应:', res)
    if (res.code === 200) {
      // 适配不同的数据结构
      if (res.data.list) {
        banners.value = res.data.list
      } else {
        banners.value = Array.isArray(res.data) ? res.data : []
      }
      console.log('首页轮播图数据:', banners.value)
    } else {
      ElMessage.error(res.message || '获取轮播图失败')
    }
  } catch (error) {
    console.error('获取轮播图失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理轮播图点击
const handleBannerClick = (banner) => {
  if (banner.linkUrl) {
    // 如果有外部链接，则打开外部链接
    window.open(banner.linkUrl, '_blank')
  } else if (banner.targetId && banner.targetType) {
    // 根据目标类型和ID跳转到相应页面
    switch (banner.targetType) {
      case 1: // 音乐
        router.push(`/music/${banner.targetId}`)
        break
      case 2: // 歌单
        router.push(`/playlist/${banner.targetId}`)
        break
      case 3: // 歌手
        router.push(`/singer/${banner.targetId}`)
        break
      default:
        break
    }
  }
}

// 在组件挂载时获取轮播图数据
onMounted(() => {
  fetchBanners()
})
</script>

<style scoped>
.home-banner {
  width: 100%;
  margin: 0 0 20px 0;
}

.banner-item {
  height: 100%;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.banner-item:hover {
  transform: translateY(-5px);
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 15px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}
</style>
