<script setup>
import { ref, onMounted } from 'vue'
import { usePlayerStore } from '../../stores/player'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCollectedMusic, toggleCollectMusic } from '../../api/music'
import { processImageUrl } from '../../utils/imageUtils'

const playerStore = usePlayerStore()

// 收藏的音乐列表
const collectMusicList = ref([])

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

// 获取收藏的音乐列表
const fetchCollectMusic = async () => {
  loading.value = true
  try {
    const res = await getCollectedMusic()
    if (res.code === 200) {
      // 处理数据
      const musicList = res.data.records || res.data.list || []

      // 处理音乐数据
      collectMusicList.value = musicList.map(item => ({
        id: item.id,
        name: item.name,
        singer: item.singerNames || item.singer || '未知歌手',
        album: item.album || '未知专辑',
        duration: item.duration || 0,
        cover: processImageUrl(item.cover),
        url: item.url,
        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 playMusic = (music) => {
  playerStore.setCurrentMusic(music)
}

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

// 添加到播放列表
const addToPlaylist = (music) => {
  playerStore.addToPlaylist(music)
  ElMessage.success('已添加到播放列表')
}

// 播放全部
const playAll = () => {
  if (collectMusicList.value.length === 0) {
    ElMessage.warning('没有可播放的音乐')
    return
  }

  // 清空当前播放列表
  playerStore.clearPlaylist()

  // 添加所有音乐到播放列表
  collectMusicList.value.forEach(music => {
    playerStore.addToPlaylist(music)
  })

  // 播放第一首
  playerStore.setCurrentMusic(collectMusicList.value[0])

  ElMessage.success('开始播放全部收藏音乐')
}

// 处理下拉菜单命令
const handleCommand = (command, music) => {
  switch (command) {
    case 'addToPlaylist':
      addToPlaylist(music)
      break
    case 'playNext':
      const currentIndex = playerStore.getCurrentIndex
      if (currentIndex !== -1) {
        const playlist = [...playerStore.getPlaylist]
        const existingIndex = playlist.findIndex(item => item.id === music.id)
        if (existingIndex !== -1) {
          playlist.splice(existingIndex, 1)
        }
        playlist.splice(currentIndex + 1, 0, music)
        playerStore.$patch({ playlist })
        ElMessage.success('已添加到下一首播放')
      } else {
        playerStore.addToPlaylist(music)
        ElMessage.success('已添加到播放列表')
      }
      break
    case 'downloadMusic':
      downloadFile('music', music)
      break
    case 'downloadLyric':
      downloadFile('lyric', music)
      break
    case 'cancelCollect':
      cancelCollect(music.id)
      break
  }
}

// 下载文件
const downloadFile = (type, music) => {
  const typeName = type === 'music' ? '音乐' : '歌词'
  ElMessageBox.confirm(`确定要下载《${music.name}》的${typeName}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    const url = `/api/file/download/${type}/${music.id}`
    window.open(url, '_blank')
    ElMessage.success(`${typeName}开始下载...`)
  }).catch(() => {
    ElMessage.info(`已取消下载${typeName}`)
  })
}

// 格式化时间
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

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

<template>
  <div class="collect-music-container">
    <div class="collect-music-header">
      <h2>我收藏的音乐</h2>
      <el-button type="primary" @click="playAll" :disabled="collectMusicList.length === 0">
        <el-icon><video-play /></el-icon>
        播放全部
      </el-button>
    </div>

    <!-- 音乐列表 -->
    <div class="music-list-container">
      <el-table
        v-loading="loading"
        :data="collectMusicList"
        stripe
        style="width: 100%"
        @row-dblclick="playMusic"
      >
        <el-table-column width="80" align="center">
          <template #default="scope">
            <el-button
              circle
              :icon="'VideoPlay'"
              size="small"
              @click="playMusic(scope.row)"
            ></el-button>
          </template>
        </el-table-column>

        <el-table-column label="封面" width="80" align="center">
          <template #default="scope">
            <img
              :src="scope.row.cover"
              :alt="scope.row.name"
              class="music-cover"
            >
          </template>
        </el-table-column>

        <el-table-column prop="name" label="歌曲名" min-width="200"></el-table-column>

        <el-table-column prop="singer" label="歌手" min-width="150"></el-table-column>

        <el-table-column prop="album" label="专辑" min-width="150"></el-table-column>

        <el-table-column prop="duration" label="时长" width="100" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.duration) }}
          </template>
        </el-table-column>

        <el-table-column prop="collectTime" label="收藏时间" width="120" align="center"></el-table-column>

        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-dropdown trigger="click" @command="handleCommand($event, scope.row)">
              <el-button circle size="small">
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="addToPlaylist">添加到播放列表</el-dropdown-item>
                  <el-dropdown-item command="playNext">下一首播放</el-dropdown-item>
                  <el-dropdown-item command="downloadMusic">下载音乐</el-dropdown-item>
                  <el-dropdown-item command="downloadLyric">下载歌词</el-dropdown-item>
                  <el-dropdown-item command="cancelCollect" divided>取消收藏</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

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

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

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

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

.music-list-container {
  background-color: #fff;
  border-radius: 8px;
}

.music-cover {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
}
</style>
