<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue' // 添加 onUnmounted
import { useRoute, useRouter } from 'vue-router'
import { usePlayerStore } from '../stores/player'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPlaylistById, toggleCollectPlaylist, deletePlaylist as apiDeletePlaylist, isPlaylistCollected, updatePlaylist, playPlaylist } from '../api/playlist'
import { getMusicStatus } from '../api/music'
import { getCommentList, addComment, deleteComment as apiDeleteComment } from '../api/comment'
import { connect, subscribe, unsubscribe, disconnect } from '../utils/websocket' // 导入 WebSocket 工具
import { processImageUrl } from '../utils/imageUtils'
import MusicList from '../components/MusicList.vue'

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

// 歌单ID
const playlistId = computed(() => route.params.id)

// 歌单详情
const playlist = ref(null)

// 评论列表
const comments = ref([])

// 评论内容
const commentContent = ref('')

// 回复内容
const replyContent = ref('')

// 回复对象
const replyTo = ref(null)

// 正在回复的评论
const replyingTo = ref(null)

// 展开的评论
const expandedComments = ref([])

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

// 收藏状态
const isCollected = ref(false)

// 是否是创建者
const isCreator = ref(false)

// 编辑模态框可见性
const editDialogVisible = ref(false)

// 编辑表单数据
const editForm = ref({
  id: null,
  name: '',
  description: '',
  cover: null
})

// 封面预览 URL
const coverPreview = ref('')

// 获取歌单详情
const fetchPlaylistDetail = async () => {
  loading.value = true
  try {
    const res = await getPlaylistById(playlistId.value)
    if (res.code === 200) {
      playlist.value = res.data

      // 处理歌单中的音乐
      if (playlist.value.musics) {
        playlist.value.songs = playlist.value.musics
      } else if (!playlist.value.songs) {
        playlist.value.songs = []
      }

      // 判断是否是创建者
      isCreator.value = playlist.value.creator?.id === userStore.user?.id

      // 如果用户已登录，则检查是否收藏
      if (userStore.isLoggedIn) {
        checkIfCollected()
      }

      // 更新歌单内歌曲的状态
      updateMusicStatuses(playlist.value.songs)
    } else {
      ElMessage.error(res.message || '获取歌单详情失败')
    }
  } catch (error) {
    console.error('获取歌单详情失败:', error)
    ElMessage.error('获取歌单详情失败')
  } finally {
    loading.value = false
  }
}

// 检查是否收藏
const checkIfCollected = async () => {
  try {
    const res = await isPlaylistCollected(playlistId.value)
    if (res.code === 200) {
      isCollected.value = res.data
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 获取评论列表
const fetchComments = async () => {
  try {
    const res = await getCommentList(playlistId.value, 2, 1, 20) // targetType 2 表示歌单
    if (res.code === 200) {
      comments.value = res.data.list || res.data.records || []
      if (playlist.value && res.data.total !== undefined) {
        playlist.value.commentCount = res.data.total
      }
    } else {
      ElMessage.error(res.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  }
}

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

  try {
    // 调用 API 增加播放次数
    await playPlaylist(playlistId.value)

    // 更新前端显示的播放次数
    if (playlist.value) {
      playlist.value.playCount++
    }
  } catch (error) {
    console.error('增加播放次数失败:', error)
    // 即使增加播放次数失败，也继续播放
  }

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

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

  // 播放第一首
  playerStore.setCurrentMusic(playlist.value.songs)

  ElMessage.success('开始播放全部歌曲')
}

// 播放音乐
const playMusic = (song) => {
  playerStore.setCurrentMusic(song)
}

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

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

  try {
    const res = await toggleCollectPlaylist(playlistId.value, isCollected.value)
    if (res.code === 200) {
      isCollected.value = !isCollected.value
      // 更新收藏数
      if (isCollected.value) {
        playlist.value.collectCount++
      } else {
        playlist.value.collectCount--
      }
      ElMessage.success(isCollected.value ? '收藏成功' : '已取消收藏')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await apiDeleteComment(commentId)
    if (res.code === 200) {
      comments.value = comments.value.filter(c => c.id !== commentId)
      // 更新评论数
      playlist.value.commentCount--
      ElMessage.success('评论已删除')
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 切换回复可见性
const toggleReplies = (comment) => {
  const commentId = comment.id;
  const index = expandedComments.value.indexOf(commentId);
  if (index > -1) {
    expandedComments.value.splice(index, 1);
    if (replyingTo.value === commentId) {
      cancelReply();
    }
  } else {
    expandedComments.value.push(commentId);
    setReplyTo(comment);
  }
};

// 设置回复
const setReplyTo = (comment) => {
  replyingTo.value = comment.id;
  replyTo.value = comment;
  if (!expandedComments.value.includes(comment.id)) {
    expandedComments.value.push(comment.id);
  }
}

// 取消回复
const cancelReply = () => {
  replyingTo.value = null
  replyTo.value = null
  replyContent.value = ''
}

// 更新音乐状态
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)
  }
}

// 提交评论
const submitComment = async (isReply = false) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  const content = isReply ? replyContent.value : commentContent.value
  if (!content.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }

  try {
    const res = await addComment({
      targetId: playlistId.value,
      targetType: 2, // 2表示歌单
      content: content,
      parentId: isReply ? replyingTo.value : null
    })

    if (res.code === 200) {
      if (isReply) {
        replyContent.value = ''
      } else {
        commentContent.value = ''
      }
      ElMessage.success('评论已发送')
      // 更新评论数
      playlist.value.commentCount++
    } else {
      ElMessage.error(res.message || '评论失败')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('评论失败，请稍后重试')
  }
}

// 编辑歌单
const editPlaylist = () => {
  if (!isCreator.value) {
    ElMessage.warning('只有创建者才能编辑歌单')
    return
  }

  // 初始化编辑表单
  editForm.value = {
    id: playlist.value.id,
    name: playlist.value.name,
    description: playlist.value.description,
    cover: null
  }
  coverPreview.value = playlist.value.cover
  editDialogVisible.value = true
}

// 处理封面选择
const handleCoverChange = (file) => {
  editForm.value.cover = file.raw
  coverPreview.value = URL.createObjectURL(file.raw)
}

// 提交编辑
const submitEdit = async () => {
  try {
    const res = await updatePlaylist(editForm.value.id, {
      name: editForm.value.name,
      description: editForm.value.description
    }, editForm.value.cover)

    if (res.code === 200) {
      ElMessage.success('歌单更新成功')
      editDialogVisible.value = false
      fetchPlaylistDetail()
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新歌单失败:', error)
    ElMessage.error('更新失败，请稍后重试')
  }
}

// 删除歌单
const deletePlaylist = () => {
  if (!isCreator.value) {
    ElMessage.warning('只有创建者才能删除歌单')
    return
  }

  ElMessageBox.confirm('确定要删除该歌单吗？此操作不可恢复', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await apiDeletePlaylist(playlistId.value)
      if (res.code === 200) {
        ElMessage.success('歌单删除成功')
        router.push('/playlist')
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除歌单失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {})
}

// 格式化时间
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')}`
}

// 格式化评论数
const formattedCommentCount = computed(() => {
  if (!playlist.value || playlist.value.commentCount === undefined) {
    return 0;
  }
  if (playlist.value.commentCount > 99) {
    return '99+';
  }
  return playlist.value.commentCount;
});

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

// 处理下拉菜单命令
const handleCommand = (command, music) => {
  switch (command) {
    case 'addToPlaylist':
      playerStore.addToPlaylist(music)
      ElMessage.success('已添加到播放列表')
      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
  }
}

// 下载文件
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}`)
  })
}

// WebSocket 订阅实例
let commentSubscription = null;

onMounted(() => {
  fetchPlaylistDetail()
  fetchComments()

  // 连接 WebSocket 并订阅评论
  connect(() => {
    const destination = `/topic/comments/2/${playlistId.value}`; // 2 代表歌单类型
    commentSubscription = subscribe(destination, (newComment) => {
      if (newComment && newComment.id) {
        if (newComment.user && newComment.user.avatar) {
          newComment.user.avatar = processImageUrl(newComment.user.avatar);
        }

        if (newComment.parentId) {
          const parentComment = comments.value.find(c => c.id === newComment.parentId);
          if (parentComment) {
            if (!parentComment.children) {
              parentComment.children = [];
            }
            parentComment.children.push(newComment);
          }
        } else {
          if (!comments.value.some(c => c.id === newComment.id)) {
            comments.value.unshift(newComment);
          }
        }
      } else {
        console.warn("Received invalid comment data via WebSocket:", newComment);
      }
    });
  }, (error) => {
      console.error("WebSocket connection error:", error);
      // 可以添加一些错误提示给用户
      // ElMessage.error('评论服务连接失败，实时更新不可用');
  });
})

onUnmounted(() => {
  // 取消订阅并断开连接
  if (commentSubscription) {
    const destination = `/topic/comments/2/${playlistId.value}`;
    unsubscribe(destination);
    commentSubscription = null; // 清理订阅实例
  }
  disconnect();
})
</script>

<template>
  <div class="playlist-detail-container" v-loading="loading">
    <template v-if="playlist">
      <!-- 歌单信息 -->
      <div class="playlist-info">
        <div class="playlist-cover">
          <img :src="playlist.cover" :alt="playlist.name">
        </div>
        <div class="playlist-meta">
          <h1 class="playlist-name">{{ playlist.name }}</h1>
          <div class="playlist-creator">
            <el-avatar :src="playlist.creator.avatar" :size="30" />
            <span>{{ playlist.creator.username }}</span>
          </div>
          <div class="playlist-time">创建时间：{{ playlist.createTime }}</div>
          <div class="playlist-count">播放次数：{{ formatPlayCount(playlist.playCount) }}</div>
          <div class="playlist-stats">
            <span>收藏数：{{ playlist.collectCount }}</span>
            <el-divider direction="vertical" />
            <span>评论数：{{ formattedCommentCount }}</span>
          </div>
          <div class="playlist-desc">{{ playlist.description }}</div>

          <div class="playlist-actions">
            <el-button type="primary" @click="playAll" :disabled="!playlist.songs.length">
              <el-icon><video-play /></el-icon>
              播放全部
            </el-button>

            <el-button
              :type="isCollected ? 'warning' : 'default'"
              @click="toggleCollect"
            >
              <el-icon><star /></el-icon>
              {{ isCollected ? '已收藏' : '收藏' }}
            </el-button>

            <template v-if="isCreator">
              <el-button @click="editPlaylist">
                <el-icon><edit /></el-icon>
                编辑
              </el-button>

              <el-button type="danger" @click="deletePlaylist">
                <el-icon><delete /></el-icon>
                删除
              </el-button>
            </template>
          </div>
        </div>
      </div>

      <!-- 歌曲列表和评论 -->
      <el-tabs class="playlist-tabs">
        <el-tab-pane label="歌曲列表">
          <MusicList
            :list="playlist.songs"
            :loading="loading"
            :show-pagination="false"
            :detail-in-more="true"
          />
        </el-tab-pane>

        <el-tab-pane :label="`评论(${formattedCommentCount})`">
          <!-- 评论输入框 -->
          <div class="comment-input">
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="发表你的评论..."
            />
            <div class="comment-submit-actions">
              <el-button type="primary" @click="submitComment(false)">发表评论</el-button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comment-list">
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <div class="comment-avatar">
                <el-avatar :src="comment.user.avatar" :size="40" />
              </div>
              <div class="comment-content">
                <div class="comment-header">
                  <div class="comment-user">{{ comment.user.username }}</div>
                  <div class="comment-actions">
                    <el-button type="text" size="small" @click="setReplyTo(comment)">回复</el-button>
                    <el-button
                      v-if="userStore.isAdmin || comment.user.id === userStore.user?.id"
                      type="danger"
                      size="small"
                      @click="deleteComment(comment.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-footer">
                  <div class="comment-time">{{ comment.createTime }}</div>
                  <el-button
                    v-if="comment.children && comment.children.length"
                    type="text"
                    size="small"
                    @click="toggleReplies(comment)"
                  >
                    {{ expandedComments.includes(comment.id) ? '收起回复' : `查看 ${comment.children.length} 条回复` }}
                  </el-button>
                </div>

                <!-- 子评论 -->
                <div v-if="expandedComments.includes(comment.id)" class="child-comment-list">
                  <!-- 回复输入框 -->
                  <div v-if="replyingTo === comment.id" class="comment-input child-comment-input">
                    <el-input
                      v-model="replyContent"
                      type="textarea"
                      :rows="2"
                      :placeholder="`回复 @${replyTo.user.username}`"
                    />
                  <div class="comment-submit-actions">
                    <el-button type="primary" @click="submitComment(true)">回复</el-button>
                  </div>
                  </div>
                  <div v-for="child in [...(comment.children || [])].reverse()" :key="child.id" class="comment-item">
                    <div class="comment-avatar">
                      <el-avatar :src="child.user.avatar" :size="30" />
                    </div>
                    <div class="comment-content">
                      <div class="comment-header">
                        <div class="comment-user">{{ child.user.username }}</div>
                        <div class="comment-actions">
                          <el-button
                            v-if="userStore.isAdmin || child.user.id === userStore.user?.id"
                            type="danger"
                            size="small"
                            @click="deleteComment(child.id)"
                          >
                            删除
                          </el-button>
                        </div>
                      </div>
                      <div class="comment-text">{{ child.content }}</div>
                      <div class="comment-time">{{ child.createTime }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>

    <!-- 编辑歌单对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑歌单" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="歌单名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="歌单描述">
          <el-input v-model="editForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            @change="handleCoverChange"
          >
            <img v-if="coverPreview" :src="coverPreview" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.cover-uploader .cover {
  width: 178px;
  height: 178px;
  display: block;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.playlist-detail-container {
  padding: 20px;
  min-height: calc(100vh - 140px);
  background-color: transparent;
  border-radius: 15px;
}

.playlist-info {
  display: flex;
  margin-bottom: 30px;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.playlist-cover {
  width: 220px;
  height: 220px;
  margin-right: 40px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(255, 107, 129, 0.1);
}

.playlist-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

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

.playlist-meta {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.playlist-name {
  font-size: 2.2rem;
  margin: 0 0 15px 0;
  color: #ff6b81;
  font-weight: 600;
}

.playlist-creator {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.playlist-creator span {
  margin-left: 10px;
  color: #666;
}

.playlist-time,
.playlist-count {
  margin-bottom: 10px;
  color: #666;
  font-size: 1rem;
}

.playlist-desc {
  margin-bottom: 20px;
  color: #666;
  font-size: 1rem;
  line-height: 1.6;
  max-height: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}

.playlist-actions {
  margin-top: auto;
  display: flex;
  gap: 15px;
}

.playlist-actions .el-button {
  border-radius: 20px;
  padding: 12px 24px;
}

.playlist-tabs {
  margin: 0 0 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-tabs :deep(.el-tabs__item) {
  font-size: 1rem;
  font-weight: 500;
  color: #666;
}

.playlist-tabs :deep(.el-tabs__item.is-active) {
  color: #ff6b81;
}

.playlist-tabs :deep(.el-tabs__active-bar) {
  background-color: #ff6b81;
}

.playlist-tabs :deep(.el-tabs__nav-wrap::after) {
  background-color: #ffb6c1;
}

.song-cover {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  object-fit: cover;
  transition: transform 0.3s;
}

.song-cover:hover {
  transform: scale(1.1);
}

.comment-input {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: flex-end;
}

.comment-input .el-button {
  background-color: #ff6b81;
  color: white;
  border-radius: 20px;
  padding: 10px 20px;
  transition: all 0.3s;
}

.comment-input .el-button:hover {
  background-color: #ff4757;
  transform: translateY(-2px);
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff9f9;
  border-radius: 12px;
  transition: all 0.3s;
}

.comment-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 129, 0.1);
}

.comment-avatar {
  margin-right: 15px;
}

.comment-content {
  flex: 1;
}

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

.comment-user {
  font-weight: 600;
  color: #ff6b81;
}

.comment-text {
  margin-bottom: 5px;
  color: #333;
  line-height: 1.5;
}

.comment-time {
  font-size: 0.8rem;
  color: #999;
}

.comment-actions .el-button {
  border-radius: 20px;
  padding: 5px 10px;
  transition: all 0.3s;
}

.comment-actions .el-button:hover {
  transform: scale(1.05);
}
</style>
