<template>
  <div class="search-container">
    <div class="search-header">
      <h1>搜索结果: "{{ keyword }}"</h1>
      <div class="search-input">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索音乐、歌单、歌手"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="音乐" name="music">
        <div class="search-result" v-loading="loadingMusic">
          <MusicList
            :list="musicList"
            :loading="loadingMusic"
            :total="musicTotal"
            v-model:current-page="musicPage"
            v-model:page-size="musicPageSize"
            @page-change="fetchMusicList"
            @collect-change="handleCollectChange"
          />

          <el-empty
            v-if="musicList.length === 0 && !loadingMusic"
            description="未找到相关音乐"
          ></el-empty>
        </div>
      </el-tab-pane>

      <el-tab-pane label="歌单" name="playlist">
        <div class="search-result" v-loading="loadingPlaylist">
          <div class="playlist-list">
            <div
              v-for="playlist in playlistList"
              :key="playlist.id"
              class="playlist-item"
              @click="goToPlaylist(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="playlist.collected ? 'StarFilled' : 'Star'"
                      :type="playlist.collected ? 'warning' : ''"
                      @click.stop="handleCollectPlaylist(playlist.id)"
                    ></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>
                  <span>{{ playlist.songCount || 0 }}首歌曲</span>
                </div>
              </div>
            </div>
          </div>

          <el-empty
            v-if="playlistList.length === 0 && !loadingPlaylist"
            description="未找到相关歌单"
          ></el-empty>

          <div class="pagination" v-if="playlistTotal > 0">
            <el-pagination
              v-model:current-page="playlistPage"
              v-model:page-size="playlistPageSize"
              :page-sizes="[12, 24, 36, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="playlistTotal"
              @size-change="handlePlaylistSizeChange"
              @current-change="handlePlaylistPageChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="歌手" name="singer">
        <div class="search-result" v-loading="loadingSinger">
          <div class="singer-list">
            <div
              v-for="singer in singerList"
              :key="singer.id"
              class="singer-item"
              @click="goToSinger(singer.id)"
            >
              <div class="singer-avatar">
                <img :src="singer.avatar" :alt="singer.name">
                <div class="singer-overlay">
                  <el-button
                    circle
                    :icon="singer.collected ? 'StarFilled' : 'Star'"
                    :type="singer.collected ? 'warning' : 'primary'"
                    @click.stop="handleCollectSinger(singer.id, $event)"
                  ></el-button>
                </div>
              </div>
              <div class="singer-info">
                <div class="singer-name">{{ singer.name }}</div>
                <div class="singer-stats">
                  <span>{{ singer.musicCount || 0 }}首歌曲</span>

                  <span>{{ formatFans(singer.fansCount || 0) }}粉丝</span>
                </div>
              </div>
            </div>
          </div>

          <el-empty
            v-if="singerList.length === 0 && !loadingSinger"
            description="未找到相关歌手"
          ></el-empty>

          <div class="pagination" v-if="singerTotal > 0">
            <el-pagination
              v-model:current-page="singerPage"
              v-model:page-size="singerPageSize"
              :page-sizes="[20, 40, 60, 80]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="singerTotal"
              @size-change="handleSingerSizeChange"
              @current-change="handleSingerPageChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { searchMusic, toggleCollectMusic, getMusicStatus } from '../api/music'
import { searchPlaylist, toggleCollectPlaylist } from '../api/playlist'
import { searchSinger, toggleCollectSinger } from '../api/singer'
import { processImageUrl } from '../utils/imageUtils'
import { processMusicUrl } from '../api/music'
import MusicList from '../components/MusicList.vue'

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

// 搜索关键词
const keyword = computed(() => route.query.keyword || '')
const searchKeyword = ref(keyword.value)

// 当前激活的标签页
const activeTab = ref('music')

// 音乐搜索结果
const musicList = ref([])
const musicPage = ref(1)
const musicPageSize = ref(10)
const musicTotal = ref(0)
const loadingMusic = ref(false)

// 歌单搜索结果
const playlistList = ref([])
const playlistPage = ref(1)
const playlistPageSize = ref(12)
const playlistTotal = ref(0)
const loadingPlaylist = ref(false)

// 歌手搜索结果
const singerList = ref([])
const singerPage = ref(1)
const singerPageSize = ref(20)
const singerTotal = ref(0)
const loadingSinger = ref(false)

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  router.push({
    path: '/search',
    query: { keyword: searchKeyword.value }
  })
}

// 获取音乐搜索结果
const fetchMusicList = async () => {
  if (!keyword.value) return

  loadingMusic.value = true
  try {
    const res = await searchMusic(keyword.value, musicPage.value, musicPageSize.value)
    if (res.code === 200) {
      musicList.value = res.data.list || res.data.records || []
      musicTotal.value = res.data.total || 0

      // 处理音乐URL和封面URL
      musicList.value = musicList.value.map(item => ({
        ...item,
        cover: processMusicUrl(item.cover),
        url: processMusicUrl(item.url)
      }))

      // 更新音乐状态
      updateMusicStatuses(musicList.value)
    } else {
      ElMessage.error(res.message || '搜索音乐失败')
    }
  } catch (error) {
    console.error('搜索音乐失败:', error)
    ElMessage.error('搜索音乐失败')
  } finally {
    loadingMusic.value = false
  }
}

// 获取歌单搜索结果
const fetchPlaylistList = async () => {
  if (!keyword.value) return

  loadingPlaylist.value = true
  try {
    const res = await searchPlaylist(keyword.value, playlistPage.value, playlistPageSize.value)
    if (res.code === 200) {
      playlistList.value = res.data.list || res.data.records || []
      playlistTotal.value = res.data.total || 0

      // 处理封面URL
      playlistList.value = playlistList.value.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))
    } else {
      ElMessage.error(res.message || '搜索歌单失败')
    }
  } catch (error) {
    console.error('搜索歌单失败:', error)
    ElMessage.error('搜索歌单失败')
  } finally {
    loadingPlaylist.value = false
  }
}

// 获取歌手搜索结果
const fetchSingerList = async () => {
  if (!keyword.value) return

  loadingSinger.value = true
  try {
    const res = await searchSinger(keyword.value, singerPage.value, singerPageSize.value)
    if (res.code === 200) {
      singerList.value = res.data.list || res.data.records || []
      singerTotal.value = res.data.total || 0

      // 处理头像URL
      singerList.value = singerList.value.map(item => ({
        ...item,
        avatar: processImageUrl(item.avatar)
      }))
    } else {
      ElMessage.error(res.message || '搜索歌手失败')
    }
  } catch (error) {
    console.error('搜索歌手失败:', error)
    ElMessage.error('搜索歌手失败')
  } finally {
    loadingSinger.value = false
  }
}

// 处理标签页切换
const handleTabChange = () => {
  // 无论列表是否为空，都加载对应标签页的数据
  if (activeTab.value === 'music') {
    fetchMusicList()
  } else if (activeTab.value === 'playlist') {
    fetchPlaylistList()
  } else if (activeTab.value === 'singer') {
    fetchSingerList()
  }
}

// 处理音乐分页变化
const handleMusicPageChange = (page) => {
  musicPage.value = page
  fetchMusicList()
}

// 处理音乐每页数量变化
const handleMusicSizeChange = (size) => {
  musicPageSize.value = size
  musicPage.value = 1
  fetchMusicList()
}

// 处理歌单分页变化
const handlePlaylistPageChange = (page) => {
  playlistPage.value = page
  fetchPlaylistList()
}

// 处理歌单每页数量变化
const handlePlaylistSizeChange = (size) => {
  playlistPageSize.value = size
  playlistPage.value = 1
  fetchPlaylistList()
}

// 处理歌手分页变化
const handleSingerPageChange = (page) => {
  singerPage.value = page
  fetchSingerList()
}

// 处理歌手每页数量变化
const handleSingerSizeChange = (size) => {
  singerPageSize.value = size
  singerPage.value = 1
  fetchSingerList()
}

// 收藏/取消收藏音乐
const handleCollectChange = async (id) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    const res = await toggleCollectMusic(id)
    if (res.code === 200) {
      const music = musicList.value.find(m => m.id === id)
      if (music) {
        music.collected = !music.collected
        ElMessage.success(music.collected ? '收藏成功' : '已取消收藏')
      }
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

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

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

// 收藏/取消收藏歌手
const handleCollectSinger = async (id, event) => {
  if (event) event.stopPropagation()

  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    const res = await toggleCollectSinger(id)
    if (res.code === 200) {
      const singer = singerList.value.find(s => s.id === id)
      if (singer) {
        singer.collected = !singer.collected
        ElMessage.success(singer.collected ? '收藏成功' : '已取消收藏')
      }
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 跳转到歌单详情
const goToPlaylist = (id) => {
  router.push(`/playlist/${id}`)
}

// 跳转到歌手详情
const goToSinger = (id) => {
  router.push(`/singer/${id}`)
}

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

// 格式化粉丝数
const formatFans = (count) => {
  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

// 更新音乐状态
const updateMusicStatuses = async (list) => {
  if (!userStore.isLoggedIn || !list || list.length === 0) {
    return
  }

  // 为列表中的每首歌曲获取状态
  const promises = list.map(music => getMusicStatus(music.id))
  try {
    const results = await Promise.all(promises)
    results.forEach((res, index) => {
      if (res.code === 200 && res.data) {
        list[index].collected = res.data.collected
        list[index].liked = res.data.liked
      }
    })
  } catch (error) {
    console.error('批量获取音乐状态失败:', error)
  }
}

// 监听关键词变化
watch(() => route.query.keyword, (newKeyword) => {
  searchKeyword.value = newKeyword

  // 重置分页
  musicPage.value = 1
  playlistPage.value = 1
  singerPage.value = 1

  // 无论当前标签页是什么，都获取所有类型的搜索结果
  fetchMusicList()
  fetchPlaylistList()
  fetchSingerList()
}, { immediate: true })

onMounted(() => {
  // 初始获取所有类型的搜索结果
  if (keyword.value) {
    // 预加载所有标签页的数据
    fetchMusicList()
    fetchPlaylistList()
    fetchSingerList()
  }
})
</script>

<style scoped>
.search-container {
  padding: 20px 20px 100px 20px; /* 增加底部填充，为播放器留出空间 */
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-header h1 {
  margin: 0;
  font-size: 1.8rem;
  color: #333;
}

.search-input {
  width: 300px;
}

.search-result {
  margin-top: 20px;
  min-height: 300px;
}

.el-tabs {
  margin-bottom: 20px;
}

/* 歌单列表样式 */
.playlist-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 15px;
  padding: 0 20px;
}

.playlist-item {
  cursor: pointer;
  transition: all 0.3s;
}

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

.playlist-cover {
  position: relative;
  width: 100%;
  padding-top: 100%;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 10px;
}

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

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

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

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

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

.playlist-actions {
  display: flex;
  justify-content: center;
}

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

.playlist-desc {
  font-size: 0.8rem;
  color: #666;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-creator {
  font-size: 0.8rem;
  color: #999;
  display: flex;
  justify-content: space-between;
}

/* 歌手列表样式 */
.singer-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 20px;
}

.singer-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;
}

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

.singer-avatar {
  position: relative;
  width: 100%;
  padding-top: 100%;
  overflow: hidden;
}

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

.singer-item:hover .singer-avatar img {
  transform: scale(1.05);
}

.singer-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;
  align-items: center;
  justify-content: center;
}

.singer-item:hover .singer-overlay {
  opacity: 1;
}

.singer-info {
  padding: 15px;
}

.singer-name {
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
}

.singer-stats {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 0.8rem;
  color: #999;
}

.singer-stats span {
  white-space: nowrap;
}

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