<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { Search, Headset } from '@element-plus/icons-vue'
import { getPlaylistList, getHotPlaylist, toggleCollectPlaylist, isPlaylistCollected, uncollectPlaylist, collectPlaylist } from '../api/playlist'
import { getPlaylistTypeList } from '../api/playlistType'

const router = useRouter()
const userStore = useUserStore()

// 歌单类型列表
const playlistTypes = ref([
  { id: null, name: '全部' }
])

// 实际的歌单类型列表
const actualPlaylistTypes = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '流行' },
  { id: 2, name: '摇滚' },
  { id: 3, name: '民谣' },
  { id: 4, name: '电子' },
  { id: 5, name: '古典' },
  { id: 6, name: '嘻哈' },
  { id: 7, name: '爵士' },
  { id: 8, name: '乡村' }
])

// 当前选中的歌单类型
const activeType = ref(null)

// 歌单列表
const playlists = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

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

// 搜索关键词
const keyword = ref('')

// 热门歌单
const hotPlaylists = ref([])
const loadingHot = ref(false)

// 获取歌单类型列表
const fetchPlaylistTypes = async () => {
  try {
    const res = await getPlaylistTypeList()
    if (res.code === 200) {
      // 将获取到的类型添加到列表中
      playlistTypes.value = [
        { id: null, name: '全部' },
        ...res.data
      ]
    } else {
      ElMessage.error(res.message || '获取歌单类型失败')
    }
  } catch (error) {
    console.error('获取歌单类型失败:', error)
    ElMessage.error('获取歌单类型失败')
  }
}

// 切换歌单类型
const changeType = (typeId) => {
  activeType.value = typeId
  currentPage.value = 1
  fetchPlaylists()
}

// 获取歌单列表
const fetchPlaylists = async () => {
  loading.value = true
  try {
    const res = await getPlaylistList(
      currentPage.value,
      pageSize.value,
      keyword.value,
      activeType.value
    )

    if (res.code === 200) {
      playlists.value = res.data.list || res.data.records || []
      total.value = res.data.total || 0
      updatePlaylistStatuses(playlists.value)
    } else {
      ElMessage.error(res.message || '获取歌单列表失败')
    }
  } catch (error) {
    console.error('获取歌单列表失败:', error)
    ElMessage.error('获取歌单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取热门歌单
const fetchHotPlaylists = async () => {
  loadingHot.value = true
  try {
    const res = await getHotPlaylist(8) // 获取8个热门歌单
    if (res.code === 200) {
      hotPlaylists.value = res.data || []
      updatePlaylistStatuses(hotPlaylists.value)
    } else {
      ElMessage.error(res.message || '获取热门歌单失败')
    }
  } catch (error) {
    console.error('获取热门歌单失败:', error)
    ElMessage.error('获取热门歌单失败')
  } finally {
    loadingHot.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPlaylists()
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchPlaylists()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPlaylists()
}

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

// 收藏/取消收藏歌单
const toggleCollect = async (playlist) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    let res
    if (playlist.collected) {
      res = await uncollectPlaylist(playlist.id)
    } else {
      res = await collectPlaylist(playlist.id)
    }

    if (res.code === 200) {
      playlist.collected = !playlist.collected
      ElMessage.success(playlist.collected ? '收藏成功' : '已取消收藏')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 更新歌单收藏状态
const updatePlaylistStatuses = async (list) => {
  if (!userStore.isLoggedIn || !list || list.length === 0) {
    return
  }

  const promises = list.map(playlist => isPlaylistCollected(playlist.id))
  try {
    const results = await Promise.all(promises)
    results.forEach((res, index) => {
      if (res.code === 200) {
        list[index].collected = res.data
      }
    })
  } catch (error) {
    console.error('批量获取歌单收藏状态失败:', error)
  }
}

// 格式化播放次数
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(() => {
  fetchPlaylistTypes()
  fetchPlaylists()
  fetchHotPlaylists()
})
</script>

<template>
  <div class="playlist-container">
    <div class="playlist-header">
      <h1>歌单</h1>
      <div class="search-container">
        <el-input
          v-model="keyword"
          placeholder="搜索歌单"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 歌单类型选择 -->
    <div class="playlist-types">
      <el-radio-group v-model="activeType" @change="changeType">
        <el-radio-button
          v-for="type in playlistTypes"
          :key="type.id"
          :label="type.id"
        >
          {{ type.name }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 热门歌单 -->
    <div class="hot-playlists" v-if="activeType === null && currentPage === 1">
      <h2>热门歌单</h2>
      <div class="playlist-list" v-loading="loadingHot">
        <div
          v-for="playlist in hotPlaylists"
          :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 || 0) }}
              </div>
              <div class="playlist-song-count">
                <el-icon><Headset /></el-icon>
                {{ playlist.musicCount || 0 }}
              </div>
              <div class="playlist-actions">
                <el-button
                  circle
                  :icon="'VideoPlay'"
                  @click.stop="viewPlaylistDetail(playlist.id)"
                ></el-button>
                <el-button
                  circle
                  :icon="playlist.collected ? 'StarFilled' : 'Star'"
                  :type="playlist.collected ? 'warning' : ''"
                  @click.stop="toggleCollect(playlist)"
                ></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-creator">
              <span>by {{ playlist.creator?.username || '未知用户' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 歌单列表 -->
    <div class="all-playlists">
      <h2 v-if="activeType === null && currentPage === 1">全部歌单</h2>
      <div class="playlist-list" v-loading="loading">
        <div
          v-for="playlist in playlists"
          :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 || 0) }}
              </div>
              <div class="playlist-song-count">
                <el-icon><Headset /></el-icon>
                {{ playlist.musicCount || 0 }}
              </div>
              <div class="playlist-actions">
                <el-button
                  circle
                  :icon="'VideoPlay'"
                  @click.stop="viewPlaylistDetail(playlist.id)"
                ></el-button>
                <el-button
                  circle
                  :icon="playlist.collected ? 'StarFilled' : 'Star'"
                  :type="playlist.collected ? 'warning' : ''"
                  @click.stop="toggleCollect(playlist)"
                ></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-creator">
              <span>by {{ playlist.creator?.username || '未知用户' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty
        v-if="playlists.length === 0 && !loading"
        description="暂无歌单"
      ></el-empty>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.playlist-container {
  padding: 20px 20px 80px 20px;
  min-height: calc(100vh - 140px);
  background-color: transparent;
  border-radius: 15px;
}

.playlist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.playlist-header h1 {
  margin: 0;
  font-size: 1.8rem;
  color: #ff6b81;
  font-weight: 600;
}

.search-container {
  width: 300px;
}

.search-container :deep(.el-input__wrapper) {
  border-radius: 20px;
}

.search-container .el-icon {
  color: #ff6b81;
  cursor: pointer;
  transition: all 0.3s;
}

.search-container .el-icon:hover {
  color: #ff4757;
  transform: scale(1.1);
}

.hot-playlists,
.all-playlists {
  margin-top: 30px;
}

.hot-playlists h2,
.all-playlists h2 {
  margin-bottom: 20px;
  font-size: 1.5rem;
  color: #ff6b81;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.pagination :deep(.el-pagination.is-background .btn-next),
.pagination :deep(.el-pagination.is-background .btn-prev),
.pagination :deep(.el-pagination.is-background .el-pager li) {
  background-color: #fff9f9;
  border-radius: 50%;
  margin: 0 5px;
}

.pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ffb6c1;
  color: white;
}

.playlist-types {
  margin-bottom: 30px;
}

.playlist-types :deep(.el-radio-button__inner) {
  border-radius: 20px !important;
  margin-right: 10px;
  border: none;
  background-color: #fff9f9;
  color: #666;
}

.playlist-types :deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #ffb6c1;
  color: white;
  box-shadow: none;
}

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

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

.playlist-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 20px rgba(255, 107, 129, 0.2);
}

.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.1);
}

.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(255, 182, 193, 0.7));
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 5px;
  padding: 15px;
}

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

.playlist-play-count {
  color: white;
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}

.playlist-play-count .el-icon {
  margin-right: 5px;
  font-size: 1rem;
}

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

.playlist-actions .el-button {
  background-color: rgba(255, 255, 255, 0.8);
  color: #ff6b81;
  transition: all 0.3s;
}

.playlist-actions .el-button:hover {
  background-color: white;
  transform: scale(1.1);
}

.playlist-info {
  padding: 15px;
}

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

.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-creator {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: #999;
}
</style>
