<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCollectedPlaylist, toggleCollectPlaylist } from '../../api/playlist'
import { processImageUrl } from '../../utils/imageUtils'

const router = useRouter()

// 收藏的歌单列表
const collectPlaylists = ref([])

// 加载状态
const loading = ref(false)

// 获取收藏的歌单列表
const fetchCollectPlaylists = async () => {
  loading.value = true
  try {
    const res = await getCollectedPlaylist()
    if (res.code === 200) {
      // 处理数据
      const playlists = res.data.records || res.data.list || []

      // 处理歌单数据
      collectPlaylists.value = playlists.map(item => ({
        id: item.id,
        name: item.name,
        description: item.description || '暂无描述',
        creator: item.creatorName || '未知用户',
        cover: processImageUrl(item.cover),
        songCount: item.songCount || 0,
        playCount: item.playCount || 0,
        collectTime: item.collectTime ? new Date(item.collectTime).toLocaleDateString() : '未知'
      }))
    } else {
      ElMessage.error(res.message || '获取收藏的歌单列表失败')
    }
  } catch (error) {
    console.error('获取收藏的歌单列表失败:', error)
    ElMessage.error('获取收藏的歌单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看歌单详情
const viewPlaylistDetail = (id) => {
  router.push(`/playlist/${id}`)
}

// 取消收藏歌单
const cancelCollect = (id, event) => {
  event.stopPropagation()

  ElMessageBox.confirm('确定要取消收藏该歌单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await toggleCollectPlaylist(id)
      if (res.code === 200) {
        // 从列表中移除该歌单
        collectPlaylists.value = collectPlaylists.value.filter(item => item.id !== id)
        ElMessage.success('已取消收藏')
      } else {
        ElMessage.error(res.message || '取消收藏失败')
      }
    } catch (error) {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  }).catch(() => {})
}

// 格式化播放次数
const formatPlayCount = (count) => {
  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

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

<template>
  <div class="collect-playlist-container">
    <div class="collect-playlist-header">
      <h2>我收藏的歌单</h2>
    </div>

    <!-- 歌单列表 -->
    <div class="playlist-list" v-loading="loading">
      <div
        v-for="playlist in collectPlaylists"
        :key="playlist.id"
        class="playlist-item"
        @click="viewPlaylistDetail(playlist.id)"
      >
        <div class="playlist-cover">
          <img :src="playlist.cover" :alt="playlist.name">
          <div class="playlist-info-overlay">
            <div class="playlist-play-count">
              <el-icon><video-play /></el-icon>
              {{ formatPlayCount(playlist.playCount) }}
            </div>
            <div class="playlist-actions">
              <el-button
                circle
                :icon="'VideoPlay'"
                @click.stop="viewPlaylistDetail(playlist.id)"
              ></el-button>
              <el-button
                circle
                :icon="'Delete'"
                type="danger"
                @click.stop="cancelCollect(playlist.id, $event)"
              ></el-button>
            </div>
          </div>
        </div>
        <div class="playlist-info">
          <div class="playlist-name">{{ playlist.name }}</div>
          <div class="playlist-desc">{{ playlist.description }}</div>
          <div class="playlist-meta">
            <span>{{ playlist.songCount }}首歌曲</span>
            <span>收藏于 {{ playlist.collectTime }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="collectPlaylists.length === 0 && !loading"
      description="暂无收藏的歌单"
    ></el-empty>
  </div>
</template>

<style scoped>
.collect-playlist-container {
  padding: 0;
}

.collect-playlist-header {
  margin-bottom: 20px;
}

.collect-playlist-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.playlist-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.playlist-item {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
}

.playlist-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px 0 rgba(0, 0, 0, 0.1);
}

.playlist-cover {
  position: relative;
  width: 100%;
  padding-top: 100%;
  overflow: hidden;
}

.playlist-cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.playlist-item:hover .playlist-cover img {
  transform: scale(1.05);
}

.playlist-info-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.7));
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px;
}

.playlist-item:hover .playlist-info-overlay {
  opacity: 1;
}

.playlist-play-count {
  color: white;
  display: flex;
  align-items: center;
  font-size: 0.9rem;
}

.playlist-play-count .el-icon {
  margin-right: 5px;
}

.playlist-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 10px;
}

.playlist-info {
  padding: 15px;
}

.playlist-name {
  font-weight: bold;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-desc {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 40px;
}

.playlist-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: #999;
}
</style>
