<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import {
  getMusicTypePage,
  addMusicType,
  updateMusicType,
  deleteMusicType,
  getSingerTypePage,
  addSingerType,
  updateSingerType,
  deleteSingerType,
  getPlaylistTypePage,
  addPlaylistType,
  updatePlaylistType,
  deletePlaylistType
} from '../../api/admin/type'

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

// 音乐类型相关数据
const musicTypeList = ref([])
const musicTypeTotal = ref(0)
const musicTypeLoading = ref(false)
const musicTypeCurrentPage = ref(1)
const musicTypePageSize = ref(5)
const musicTypeKeyword = ref('')

// 歌手类型相关数据
const singerTypeList = ref([])
const singerTypeTotal = ref(0)
const singerTypeLoading = ref(false)
const singerTypeCurrentPage = ref(1)
const singerTypePageSize = ref(5)
const singerTypeKeyword = ref('')

// 歌单类型相关数据
const playlistTypeList = ref([])
const playlistTypeTotal = ref(0)
const playlistTypeLoading = ref(false)
const playlistTypeCurrentPage = ref(1)
const playlistTypePageSize = ref(5)
const playlistTypeKeyword = ref('')

// 对话框相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('') // music, singer, playlist
const dialogAction = ref('') // add, edit
const formData = ref({
  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 formRef = ref(null)

// 获取音乐类型列表
const fetchMusicTypeList = async () => {
  console.log('获取音乐类型列表')
  musicTypeLoading.value = true
  try {
    const res = await getMusicTypePage(
      musicTypeCurrentPage.value,
      musicTypePageSize.value,
      musicTypeKeyword.value
    )
    if (res.code === 200) {
      musicTypeList.value = res.data.list
      musicTypeTotal.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取音乐类型列表失败')
    }
  } catch (error) {
    console.error('获取音乐类型列表失败:', error)
    ElMessage.error('获取音乐类型列表失败，请稍后再试')
  } finally {
    musicTypeLoading.value = false
  }
}

// 获取歌手类型列表
const fetchSingerTypeList = async () => {
  console.log('获取歌手类型列表')
  singerTypeLoading.value = true
  try {
    const res = await getSingerTypePage(
      singerTypeCurrentPage.value,
      singerTypePageSize.value,
      singerTypeKeyword.value
    )
    if (res.code === 200) {
      singerTypeList.value = res.data.list
      singerTypeTotal.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取歌手类型列表失败')
    }
  } catch (error) {
    console.error('获取歌手类型列表失败:', error)
    ElMessage.error('获取歌手类型列表失败，请稍后再试')
  } finally {
    singerTypeLoading.value = false
  }
}

// 获取歌单类型列表
const fetchPlaylistTypeList = async () => {
  console.log('获取歌单类型列表')
  playlistTypeLoading.value = true
  try {
    const res = await getPlaylistTypePage(
      playlistTypeCurrentPage.value,
      playlistTypePageSize.value,
      playlistTypeKeyword.value
    )
    if (res.code === 200) {
      playlistTypeList.value = res.data.list
      playlistTypeTotal.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取歌单类型列表失败')
    }
  } catch (error) {
    console.error('获取歌单类型列表失败:', error)
    ElMessage.error('获取歌单类型列表失败，请稍后再试')
  } finally {
    playlistTypeLoading.value = false
  }
}

// 处理标签页切换
const handleTabChange = (tab) => {
  console.log('切换到标签页:', tab)
  // 如果是从 el-radio-group 传来的，已经是值了
  // 如果是从旧的 el-tabs 传来的，需要获取 tab.props.name
  const tabName = typeof tab === 'object' && tab.props ? tab.props.name : tab

  // 无论如何，都加载对应类型的数据
  if (tabName === 'music') {
    fetchMusicTypeList()
  } else if (tabName === 'singer') {
    fetchSingerTypeList()
  } else if (tabName === 'playlist') {
    fetchPlaylistTypeList()
  }
}

// 处理页码变化
const handleCurrentChange = (page, type) => {
  if (type === 'music') {
    musicTypeCurrentPage.value = page
    fetchMusicTypeList()
  } else if (type === 'singer') {
    singerTypeCurrentPage.value = page
    fetchSingerTypeList()
  } else if (type === 'playlist') {
    playlistTypeCurrentPage.value = page
    fetchPlaylistTypeList()
  }
}

// 处理每页大小变化
const handleSizeChange = (size, type) => {
  if (type === 'music') {
    musicTypePageSize.value = size
    musicTypeCurrentPage.value = 1
    fetchMusicTypeList()
  } else if (type === 'singer') {
    singerTypePageSize.value = size
    singerTypeCurrentPage.value = 1
    fetchSingerTypeList()
  } else if (type === 'playlist') {
    playlistTypePageSize.value = size
    playlistTypeCurrentPage.value = 1
    fetchPlaylistTypeList()
  }
}

// 处理搜索
const handleSearch = (type) => {
  if (type === 'music') {
    musicTypeCurrentPage.value = 1
    fetchMusicTypeList()
  } else if (type === 'singer') {
    singerTypeCurrentPage.value = 1
    fetchSingerTypeList()
  } else if (type === 'playlist') {
    playlistTypeCurrentPage.value = 1
    fetchPlaylistTypeList()
  }
}

// 处理重置搜索
const handleResetSearch = (type) => {
  if (type === 'music') {
    musicTypeKeyword.value = ''
    musicTypeCurrentPage.value = 1
    fetchMusicTypeList()
  } else if (type === 'singer') {
    singerTypeKeyword.value = ''
    singerTypeCurrentPage.value = 1
    fetchSingerTypeList()
  } else if (type === 'playlist') {
    playlistTypeKeyword.value = ''
    playlistTypeCurrentPage.value = 1
    fetchPlaylistTypeList()
  }
}

// 打开添加对话框
const openAddDialog = (type) => {
  dialogType.value = type
  dialogAction.value = 'add'
  dialogTitle.value = type === 'music' ? '添加音乐类型' : type === 'singer' ? '添加歌手类型' : '添加歌单类型'
  formData.value = {
    id: null,
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row, type) => {
  dialogType.value = type
  dialogAction.value = 'edit'
  dialogTitle.value = type === 'music' ? '编辑音乐类型' : type === 'singer' ? '编辑歌手类型' : '编辑歌单类型'
  formData.value = {
    id: row.id,
    name: row.name,
    description: row.description || ''
  }
  dialogVisible.value = true
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (dialogAction.value === 'add') {
          if (dialogType.value === 'music') {
            res = await addMusicType(formData.value)
          } else if (dialogType.value === 'singer') {
            res = await addSingerType(formData.value)
          } else if (dialogType.value === 'playlist') {
            res = await addPlaylistType(formData.value)
          }
        } else if (dialogAction.value === 'edit') {
          if (dialogType.value === 'music') {
            res = await updateMusicType(formData.value.id, formData.value)
          } else if (dialogType.value === 'singer') {
            res = await updateSingerType(formData.value.id, formData.value)
          } else if (dialogType.value === 'playlist') {
            res = await updatePlaylistType(formData.value.id, formData.value)
          }
        }

        if (res.code === 200) {
          ElMessage.success(res.message || '操作成功')
          dialogVisible.value = false

          // 刷新列表
          if (dialogType.value === 'music') {
            fetchMusicTypeList()
          } else if (dialogType.value === 'singer') {
            fetchSingerTypeList()
          } else if (dialogType.value === 'playlist') {
            fetchPlaylistTypeList()
          }
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请稍后再试')
      }
    }
  })
}

// 处理删除
const handleDelete = (id, type) => {
  ElMessageBox.confirm('确定要删除该类型吗？此操作不可逆', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      let res
      if (type === 'music') {
        res = await deleteMusicType(id)
      } else if (type === 'singer') {
        res = await deleteSingerType(id)
      } else if (type === 'playlist') {
        res = await deletePlaylistType(id)
      }

      if (res.code === 200) {
        ElMessage.success(res.message || '删除成功')

        // 刷新列表
        if (type === 'music') {
          fetchMusicTypeList()
        } else if (type === 'singer') {
          fetchSingerTypeList()
        } else if (type === 'playlist') {
          fetchPlaylistTypeList()
        }
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后再试')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 在组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，加载所有类型数据')
  // 加载所有类型的数据
  fetchMusicTypeList()
  fetchSingerTypeList()
  fetchPlaylistTypeList()
})
</script>

<template>
  <div class="type-management">
    <div class="page-header">
      <h2>类型管理</h2>
    </div>

    <!-- 音乐类型标签页 -->
    <div v-if="activeTab === 'music'">
      <div class="tab-header">
        <div class="search-container">
          <el-input
            v-model="musicTypeKeyword"
            placeholder="搜索类型名称"
            clearable
            @keyup.enter="handleSearch('music')"
          >
            <template #append>
              <el-button @click="handleSearch('music')">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch('music')">搜索</el-button>
          <el-button @click="handleResetSearch('music')">重置</el-button>
        </div>
        <el-button type="primary" @click="openAddDialog('music')">
          <el-icon><Plus /></el-icon>添加音乐类型
        </el-button>
      </div>

      <!-- 类型选择器 -->
      <div class="type-selector">
        <el-radio-group v-model="activeTab" @change="handleTabChange">
          <el-radio-button label="music">音乐类型</el-radio-button>
          <el-radio-button label="singer">歌手类型</el-radio-button>
          <el-radio-button label="playlist">歌单类型</el-radio-button>
        </el-radio-group>
      </div>

      <el-table
        :data="musicTypeList"
        border
        stripe
        style="width: 100%"
        v-loading="musicTypeLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="类型名称" width="200" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row, 'music')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id, 'music')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="musicTypeCurrentPage"
          v-model:page-size="musicTypePageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="musicTypeTotal"
          @size-change="(size) => handleSizeChange(size, 'music')"
          @current-change="(page) => handleCurrentChange(page, 'music')"
        />
      </div>
    </div>

    <!-- 歌手类型标签页 -->
    <div v-if="activeTab === 'singer'">
      <div class="tab-header">
        <div class="search-container">
          <el-input
            v-model="singerTypeKeyword"
            placeholder="搜索类型名称"
            clearable
            @keyup.enter="handleSearch('singer')"
          >
            <template #append>
              <el-button @click="handleSearch('singer')">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch('singer')">搜索</el-button>
          <el-button @click="handleResetSearch('singer')">重置</el-button>
        </div>
        <el-button type="primary" @click="openAddDialog('singer')">
          <el-icon><Plus /></el-icon>添加歌手类型
        </el-button>
      </div>

      <!-- 类型选择器 -->
      <div class="type-selector">
        <el-radio-group v-model="activeTab" @change="handleTabChange">
          <el-radio-button label="music">音乐类型</el-radio-button>
          <el-radio-button label="singer">歌手类型</el-radio-button>
          <el-radio-button label="playlist">歌单类型</el-radio-button>
        </el-radio-group>
      </div>

      <el-table
        :data="singerTypeList"
        border
        stripe
        style="width: 100%"
        v-loading="singerTypeLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="类型名称" width="200" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row, 'singer')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id, 'singer')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="singerTypeCurrentPage"
          v-model:page-size="singerTypePageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="singerTypeTotal"
          @size-change="(size) => handleSizeChange(size, 'singer')"
          @current-change="(page) => handleCurrentChange(page, 'singer')"
        />
      </div>
    </div>

    <!-- 歌单类型标签页 -->
    <div v-if="activeTab === 'playlist'">
      <div class="tab-header">
        <div class="search-container">
          <el-input
            v-model="playlistTypeKeyword"
            placeholder="搜索类型名称"
            clearable
            @keyup.enter="handleSearch('playlist')"
          >
            <template #append>
              <el-button @click="handleSearch('playlist')">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch('playlist')">搜索</el-button>
          <el-button @click="handleResetSearch('playlist')">重置</el-button>
        </div>
        <el-button type="primary" @click="openAddDialog('playlist')">
          <el-icon><Plus /></el-icon>添加歌单类型
        </el-button>
      </div>

      <!-- 类型选择器 -->
      <div class="type-selector">
        <el-radio-group v-model="activeTab" @change="handleTabChange">
          <el-radio-button label="music">音乐类型</el-radio-button>
          <el-radio-button label="singer">歌手类型</el-radio-button>
          <el-radio-button label="playlist">歌单类型</el-radio-button>
        </el-radio-group>
      </div>

      <el-table
        :data="playlistTypeList"
        border
        stripe
        style="width: 100%"
        v-loading="playlistTypeLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="类型名称" width="200" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row, 'playlist')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id, 'playlist')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="playlistTypeCurrentPage"
          v-model:page-size="playlistTypePageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="playlistTypeTotal"
          @size-change="(size) => handleSizeChange(size, 'playlist')"
          @current-change="(page) => handleCurrentChange(page, 'playlist')"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.type-management {
  padding: 20px;
  background: linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 100%);
  min-height: 100%;
}

.page-header {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.page-header h2 {
  color: #0d47a1;
  margin: 0;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 12px;
}

.search-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-container .el-input {
  width: 300px;
}

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

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

.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 {
  --el-table-border-color: #b3e5fc;
  --el-table-header-bg-color: #e1f5fe;
  --el-table-row-hover-bg-color: #b3e5fc;
  border-radius: 8px;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.9);
}

.el-table th.el-table__cell {
  background-color: #e1f5fe !important;
  color: #0d47a1 !important;
  font-weight: bold !important;
}

.el-table .el-table__row {
  background-color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s;
}

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

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

.type-selector {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.type-selector .el-radio-group {
  display: flex;
  justify-content: center;
  width: 100%;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 12px;
}

.type-selector .el-radio-button {
  flex: 1;
  max-width: 200px;
}

.type-selector :deep(.el-radio-button__inner) {
  border-radius: 8px !important;
  transition: all 0.3s !important;
}

.type-selector :deep(.el-radio-button__inner:hover) {
  transform: scale(1.05);
}

.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-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #b3e5fc;
}

.el-textarea :deep(.el-textarea__inner):focus {
  border-color: #4dd0e1;
  box-shadow: 0 0 0 2px rgba(77, 208, 225, 0.2);
}
</style>
