<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMusicList, addMusic as apiAddMusic, updateMusic as apiUpdateMusic, deleteMusic as apiDeleteMusic, processMusicUrl } from '../../api/music'
import { getMusicTypeList } from '../../api/musicType'

// 音乐列表
const musicList = ref([])

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

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 搜索关键字
const searchKeyword = ref('')

// 类型筛选
const selectedType = ref('')

// 类型列表
const typeList = ref([])

// 添加/编辑对话框
const dialogVisible = ref(false)

// 对话框标题
const dialogTitle = ref('添加音乐')

// 当前编辑的音乐
const currentMusic = ref(null)

// 表单数据
const form = ref({
  name: '',
  singer: '',
  album: '',
  types: [],
  duration: 0,
  file: null,
  cover: null,
  lyric: ''
})

// 获取音乐列表
const fetchMusicList = async () => {
  loading.value = true
  try {
    const { currentPage, pageSize } = pagination.value
    const res = await getMusicList(
      currentPage,
      pageSize,
      searchKeyword.value,
      selectedType.value || null
    )

    console.log('音乐列表响应:', res)

    if (res.code === 200) {
      // 处理音乐列表数据
      const data = res.data
      // 兼容不同的数据结构
      const records = data.records || data.list || []

      musicList.value = records.map(item => {
        // 处理歌手信息
        let singer = ''
        if (item.singers && item.singers.length > 0) {
          singer = item.singers.map(s => s.name).join(', ')
        } else if (item.singerNames && item.singerNames.length > 0) {
          singer = item.singerNames.join(', ')
        } else if (item.singer) {
          singer = item.singer
        }

        // 处理类型信息
        let types = []
        if (item.types && item.types.length > 0) {
          types = item.types.map(t => t.id)
        } else if (item.typeIds && item.typeIds.length > 0) {
          types = item.typeIds
        } else if (item.typeId) {
          types = [item.typeId]
        }

        // 处理时长
        let duration = item.duration || 0

        return {
          ...item,
          // 处理封面URL
          cover: processMusicUrl(item.cover),
          // 处理音乐URL
          url: processMusicUrl(item.url),
          // 设置歌手名称
          singer,
          // 设置类型数组
          types,
          // 设置时长
          duration
        }
      })

      pagination.value.total = data.total || 0
      console.log('处理后的音乐列表:', musicList.value)
    } else {
      ElMessage.error(res.message || '获取音乐列表失败')
    }
  } catch (error) {
    console.error('获取音乐列表失败:', error)
    ElMessage.error('获取音乐列表失败')
  } finally {
    loading.value = false
  }
}

// 获取类型列表
const fetchTypeList = async () => {
  try {
    const res = await getMusicTypeList()
    if (res.code === 200) {
      typeList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取类型列表失败')
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
    ElMessage.error('获取类型列表失败')
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchMusicList()
}

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

// 搜索音乐
const searchMusic = () => {
  pagination.value.currentPage = 1
  fetchMusicList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  selectedType.value = ''
  pagination.value.currentPage = 1
  fetchMusicList()
}

// 添加音乐
const addMusic = () => {
  dialogTitle.value = '添加音乐'
  currentMusic.value = null
  form.value = {
    name: '',
    singer: '',
    album: '',
    types: [],
    duration: 0,
    file: null,
    cover: null,
    lyric: ''
  }
  dialogVisible.value = true
}

// 编辑音乐
const editMusic = (row) => {
  dialogTitle.value = '编辑音乐'
  currentMusic.value = row

  // 获取歌手信息
  let singer = row.singer || ''
  if (!singer && row.singers && row.singers.length > 0) {
    singer = row.singers.map(s => s.name).join(', ')
  } else if (!singer && row.singerNames && row.singerNames.length > 0) {
    singer = row.singerNames.join(', ')
  }

  // 获取类型信息
  let types = row.types || []
  if ((!types || types.length === 0) && row.typeIds && row.typeIds.length > 0) {
    types = row.typeIds
  } else if ((!types || types.length === 0) && row.typeId) {
    types = [row.typeId]
  }

  form.value = {
    name: row.name,
    singer: singer,
    album: row.album || '',
    types: types,
    duration: row.duration || 0,
    file: null,
    cover: null,
    lyric: row.lyric || ''
  }

  console.log('编辑音乐数据:', {
    original: row,
    processed: form.value
  })

  dialogVisible.value = true
}

// 删除音乐
const deleteMusic = (row) => {
  ElMessageBox.confirm(`确定要删除音乐 ${row.name} 吗？此操作不可恢复`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await apiDeleteMusic(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchMusicList() // 重新加载列表
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除音乐失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!form.value.name) {
    ElMessage.warning('请输入音乐名称')
    return
  }

  if (!form.value.singer) {
    ElMessage.warning('请输入歌手名称')
    return
  }

  // 添加音乐时必须上传音乐文件
  if (!currentMusic.value && !form.value.file) {
    ElMessage.warning('请上传音乐文件')
    return
  }

  try {
    let res
    if (currentMusic.value) {
      // 编辑音乐
      res = await apiUpdateMusic(
        currentMusic.value.id,
        {
          name: form.value.name,
          singer: form.value.singer,
          album: form.value.album,
          typeIds: form.value.types,
          lyric: form.value.lyric
        },
        form.value.file,
        form.value.cover
      )
    } else {
      // 添加音乐
      res = await apiAddMusic(
        {
          name: form.value.name,
          singer: form.value.singer,
          album: form.value.album,
          typeIds: form.value.types,
          lyric: form.value.lyric
        },
        form.value.file,
        form.value.cover
      )
    }

    if (res.code === 200) {
      ElMessage.success(currentMusic.value ? '编辑成功' : '添加成功')
      dialogVisible.value = false
      fetchMusicList() // 重新加载列表
    } else {
      ElMessage.error(res.message || (currentMusic.value ? '编辑失败' : '添加失败'))
    }
  } catch (error) {
    console.error(currentMusic.value ? '编辑音乐失败:' : '添加音乐失败:', error)
    ElMessage.error(currentMusic.value ? '编辑失败，请稍后重试' : '添加失败，请稍后重试')
  }
}

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

// 格式化类型
const formatTypes = (types) => {
  if (!types || !types.length) return '-'
  return types.map(typeId => {
    const type = typeList.value.find(t => t.id === typeId)
    return type ? type.name : ''
  }).filter(Boolean).join(', ')
}

// 处理文件上传
const handleFileChange = (file) => {
  if (file && file.raw) {
    // 检查文件类型
    const isAudio = file.raw.type.startsWith('audio/')
    if (!isAudio) {
      ElMessage.error('只能上传音频文件!')
      return
    }

    // 检查文件大小 (100MB)
    const isLt100M = file.raw.size / 1024 / 1024 < 100
    if (!isLt100M) {
      ElMessage.error('音频文件大小不能超过 100MB!')
      return
    }

    form.value.file = file.raw
  }
}

// 处理封面上传
const handleCoverChange = (file) => {
  if (file && file.raw) {
    // 检查文件类型
    const isImage = file.raw.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('只能上传图片文件!')
      return
    }

    // 检查文件大小 (2MB)
    const isLt2M = file.raw.size / 1024 / 1024 < 2
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 2MB!')
      return
    }

    form.value.cover = file.raw
  }
}

// 处理歌词上传
const handleLyricChange = (file) => {
  if (file && file.raw) {
    // 检查文件类型
    const isText = file.raw.type === 'text/plain' || file.raw.name.endsWith('.lrc')
    if (!isText) {
      ElMessage.error('只能上传文本文件或LRC文件!')
      return
    }

    // 检查文件大小 (1MB)
    const isLt1M = file.raw.size / 1024 / 1024 < 1
    if (!isLt1M) {
      ElMessage.error('歌词文件大小不能超过 1MB!')
      return
    }

    // 读取歌词文件内容
    const reader = new FileReader()
    reader.onload = (e) => {
      form.value.lyric = e.target.result
    }
    reader.readAsText(file.raw)
  }
}

onMounted(() => {
  fetchMusicList()
  fetchTypeList()
})
</script>

<template>
  <div class="admin-music-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入音乐名称/歌手/专辑"
        clearable
        @clear="resetSearch"
        @keyup.enter="searchMusic"
        class="search-input"
      >
        <template #append>
          <el-button @click="searchMusic">
            <el-icon><search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>

      <el-select
        v-model="selectedType"
        placeholder="选择类型"
        clearable
        @change="searchMusic"
        class="type-select"
      >
        <el-option
          v-for="type in typeList"
          :key="type.id"
          :label="type.name"
          :value="type.id"
        />
      </el-select>

      <el-button type="primary" @click="addMusic">
        <el-icon><plus /></el-icon>
        添加音乐
      </el-button>
    </div>

    <!-- 音乐列表 -->
    <el-table
      :data="musicList"
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>

      <el-table-column label="封面" width="80" align="center">
        <template #default="scope">
          <el-image
            :src="scope.row.cover || '/default-cover.jpg'"
            :alt="scope.row.name"
            class="music-cover"
            fit="cover"
            :preview-src-list="scope.row.cover ? [scope.row.cover] : []"
            :initial-index="0"
            preview-teleported
          >
            <template #error>
              <div class="image-error">
                <el-icon><picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="音乐名称" min-width="150"></el-table-column>

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

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

      <el-table-column prop="types" label="类型" min-width="120">
        <template #default="scope">
          {{ formatTypes(scope.row.types) }}
        </template>
      </el-table-column>

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

      <el-table-column prop="playCount" label="播放次数" width="100" align="center"></el-table-column>

      <el-table-column prop="createTime" label="上传时间" width="120"></el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editMusic(scope.row)"
          >
            编辑
          </el-button>

          <el-button
            size="small"
            type="danger"
            @click="deleteMusic(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        :model="form"
        label-width="100px"
      >
        <el-form-item label="音乐名称" required>
          <el-input v-model="form.name" placeholder="请输入音乐名称" />
        </el-form-item>

        <el-form-item label="歌手" required>
          <el-input v-model="form.singer" placeholder="请输入歌手名称" />
        </el-form-item>

        <el-form-item label="专辑">
          <el-input v-model="form.album" placeholder="请输入专辑名称" />
        </el-form-item>

        <el-form-item label="类型">
          <el-select
            v-model="form.types"
            multiple
            placeholder="请选择音乐类型"
            style="width: 100%"
          >
            <el-option
              v-for="type in typeList"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="音乐文件">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传mp3/wav文件
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleCoverChange"
            :limit="1"
            list-type="picture-card"
          >
            <el-icon><plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="歌词">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleLyricChange"
            :limit="1"
          >
            <el-button type="primary">选择歌词文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传lrc/txt文件
              </div>
            </template>
          </el-upload>

          <el-input
            v-model="form.lyric"
            type="textarea"
            :rows="5"
            placeholder="或直接输入歌词"
            style="margin-top: 10px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-music-container {
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 300px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #b3e5fc;
  transition: all 0.3s;
}

.search-input :deep(.el-input__inner):focus {
  border-color: #4dd0e1;
  box-shadow: 0 0 0 2px rgba(77, 208, 225, 0.2);
}

.type-select {
  width: 150px;
}

.type-select :deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #b3e5fc;
}

.el-button {
  border-radius: 8px !important;
  font-weight: bold !important;
  transition: all 0.3s !important;
}

.el-button--primary {
  background: linear-gradient(135deg, #4dd0e1 0%, #26c6da 100%) !important;
  border: none !important;
}

.el-button--primary:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 4px 8px rgba(38, 198, 218, 0.3) !important;
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
}

.el-table :deep(th) {
  background-color: #e1f5fe !important;
  color: #0d47a1;
}

.el-table :deep(.el-table__row) {
  transition: all 0.3s;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f5f5f5 !important;
  transform: scale(1.01);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 12px;
}

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

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

.image-error {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
  border-radius: 8px;
}

.el-dialog {
  border-radius: 16px !important;
}

.el-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 100%);
  border-radius: 16px 16px 0 0 !important;
  padding: 15px 20px;
}

.el-dialog :deep(.el-dialog__title) {
  color: #0d47a1;
  font-weight: bold;
}

.el-form-item :deep(.el-form-item__label) {
  color: #4a4a4a;
  font-weight: bold;
}

.el-input :deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #b3e5fc;
}

.el-input :deep(.el-input__inner):focus {
  border-color: #4dd0e1;
  box-shadow: 0 0 0 2px rgba(77, 208, 225, 0.2);
}

.el-upload :deep(.el-upload-dragger) {
  border-radius: 8px;
  border: 1px dashed #b3e5fc;
}

.el-upload :deep(.el-upload-dragger:hover) {
  border-color: #4dd0e1;
}

.el-upload-list :deep(.el-upload-list__item) {
  transition: all 0.3s;
}

.el-upload-list :deep(.el-upload-list__item:hover) {
  background-color: #f5f5f5;
}

.el-table :deep(.el-button) {
  margin-left: 0;
  margin-right: 5px;
  padding: 4px 8px;
  border-radius: 8px !important;
}
</style>
