<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserPlaylist, addPlaylist, updatePlaylist, deletePlaylist } from '../../api/playlist'
import { processImageUrl } from '../../utils/imageUtils'
import { useUserStore } from '../../stores/user'

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

// 自建歌单列表
const userPlaylists = ref([])

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

// 创建歌单对话框
const createDialogVisible = ref(false)

// 编辑歌单对话框
const editDialogVisible = ref(false)

// 当前编辑的歌单
const currentPlaylist = ref(null)

// 创建歌单表单
const createForm = reactive({
  name: '',
  description: ''
})

// 编辑歌单表单
const editForm = reactive({
  id: null,
  name: '',
  description: ''
})

// 表单规则
const formRules = {
  name: [
    { required: true, message: '请输入歌单名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在1到50个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 表单引用
const createFormRef = ref(null)
const editFormRef = ref(null)

// 头像上传URL
const coverUploadUrl = ref(`${import.meta.env.VITE_API_BASE_URL || ''}/api/file/upload/image`)

// 头像上传headers
const uploadHeaders = ref({
  [userStore.tokenName]: userStore.token
})

// 获取自建歌单列表
const fetchUserPlaylists = async () => {
  loading.value = true
  try {
    const res = await getUserPlaylist()
    if (res.code === 200) {
      // 处理数据
      const playlists = res.data.records || res.data.list || []

      // 处理歌单数据
      userPlaylists.value = playlists.map(item => ({
        id: item.id,
        name: item.name,
        description: item.description || '暂无描述',
        cover: processImageUrl(item.cover),
        songCount: item.songCount || 0,
        createTime: item.createTime ? new Date(item.createTime).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 openCreateDialog = () => {
  createForm.name = ''
  createForm.description = ''
  createDialogVisible.value = true
}

// 打开编辑歌单对话框
const openEditDialog = (playlist) => {
  currentPlaylist.value = playlist
  editForm.id = playlist.id
  editForm.name = playlist.name
  editForm.description = playlist.description
  editDialogVisible.value = true
}

// 创建歌单
const handleCreatePlaylist = () => {
  createFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await addPlaylist({
          name: createForm.name,
          description: createForm.description
        })

        if (res.code === 200) {
          // 创建成功，重新获取歌单列表
          await fetchUserPlaylists()
          createDialogVisible.value = false
          ElMessage.success('歌单创建成功')
        } else {
          ElMessage.error(res.message || '歌单创建失败')
        }
      } catch (error) {
        console.error('歌单创建失败:', error)
        ElMessage.error('歌单创建失败')
      }
    }
  })
}

// 编辑歌单
const handleUpdatePlaylist = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await updatePlaylist(editForm.id, {
          name: editForm.name,
          description: editForm.description
        })

        if (res.code === 200) {
          // 更新成功，重新获取歌单列表
          await fetchUserPlaylists()
          editDialogVisible.value = false
          ElMessage.success('歌单更新成功')
        } else {
          ElMessage.error(res.message || '歌单更新失败')
        }
      } catch (error) {
        console.error('歌单更新失败:', error)
        ElMessage.error('歌单更新失败')
      }
    }
  })
}

// 删除歌单
const handleDeletePlaylist = (id) => {
  ElMessageBox.confirm('确定要删除该歌单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePlaylist(id)
      if (res.code === 200) {
        // 删除成功，重新获取歌单列表
        await fetchUserPlaylists()
        ElMessage.success('歌单删除成功')
      } else {
        ElMessage.error(res.message || '歌单删除失败')
      }
    } catch (error) {
      console.error('歌单删除失败:', error)
      ElMessage.error('歌单删除失败')
    }
  }).catch(() => {})
}

// 封面上传成功
const handleCoverSuccess = async (response) => {
  if (response.code === 200) {
    // 上传成功，获取图片URL
    const imageUrl = response.data

    try {
      // 更新歌单封面
      const res = await updatePlaylist(currentPlaylist.value.id, {
        ...editForm,
        cover: imageUrl
      })

      if (res.code === 200) {
        // 更新成功，重新获取歌单列表
        await fetchUserPlaylists()
        ElMessage.success('封面上传成功')
      } else {
        ElMessage.error(res.message || '更新歌单封面失败')
      }
    } catch (error) {
      console.error('更新歌单封面失败:', error)
      ElMessage.error('更新歌单封面失败')
    }
  } else {
    ElMessage.error(response.message || '封面上传失败')
  }
}

// 封面上传前的处理
const beforeCoverUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('封面只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('封面大小不能超过2MB!')
    return false
  }
  return true
}

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

<template>
  <div class="user-playlist-container">
    <div class="user-playlist-header">
      <h2>我的歌单</h2>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><plus /></el-icon>
        创建歌单
      </el-button>
    </div>

    <!-- 歌单列表 -->
    <div class="playlist-list" v-loading="loading">
      <div
        v-for="playlist in userPlaylists"
        :key="playlist.id"
        class="playlist-item"
      >
        <div class="playlist-cover" @click="viewPlaylistDetail(playlist.id)">
          <img :src="playlist.cover" :alt="playlist.name">
          <div class="playlist-info-overlay">
            <div class="playlist-song-count">
              <el-icon><headset /></el-icon>
              {{ playlist.songCount }}首歌曲
            </div>
            <div class="playlist-actions">
              <el-button
                circle
                :icon="'VideoPlay'"
                @click.stop="viewPlaylistDetail(playlist.id)"
              ></el-button>
            </div>
          </div>
        </div>
        <div class="playlist-info">
          <div class="playlist-name" @click="viewPlaylistDetail(playlist.id)">{{ playlist.name }}</div>
          <div class="playlist-desc">{{ playlist.description }}</div>
          <div class="playlist-meta">
            <span>创建于 {{ playlist.createTime }}</span>
            <div class="playlist-operations">
              <el-button
                text
                type="primary"
                size="small"
                @click="openEditDialog(playlist)"
              >
                编辑
              </el-button>
              <el-button
                text
                type="danger"
                size="small"
                @click="handleDeletePlaylist(playlist.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="userPlaylists.length === 0 && !loading"
      description="暂无创建的歌单"
    >
      <el-button type="primary" @click="openCreateDialog">创建歌单</el-button>
    </el-empty>

    <!-- 创建歌单对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建歌单"
      width="500px"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="歌单名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入歌单名称" />
        </el-form-item>

        <el-form-item label="歌单描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入歌单描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreatePlaylist">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑歌单对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑歌单"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="封面">
          <el-upload
            class="cover-uploader"
            :action="coverUploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
          >
            <img
              v-if="currentPlaylist"
              :src="currentPlaylist.cover"
              class="cover"
            />
            <el-icon v-else class="cover-uploader-icon"><plus /></el-icon>
            <div class="cover-tip">点击上传</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="歌单名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入歌单名称" />
        </el-form-item>

        <el-form-item label="歌单描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入歌单描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdatePlaylist">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

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

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

.playlist-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 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;
}

.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;
  cursor: pointer;
}

.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-song-count {
  color: white;
  display: flex;
  align-items: center;
  font-size: 0.9rem;
}

.playlist-song-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;
  cursor: pointer;
}

.playlist-name:hover {
  color: #409eff;
}

.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;
  align-items: center;
  font-size: 0.8rem;
  color: #999;
}

.playlist-operations {
  display: flex;
  gap: 10px;
}

.cover-uploader {
  text-align: center;
}

.cover {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.cover-tip {
  margin-top: 5px;
  font-size: 0.8rem;
  color: #999;
}
</style>
