<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPlaylistTypePage, addPlaylistType, updatePlaylistType, deletePlaylistType } from '../../api/playlistType'

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

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

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 7, // 每页显示7个项目
  total: 0
})

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

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

// 对话框标题
const dialogTitle = ref('添加歌单类型')

// 当前编辑的类型
const currentType = ref(null)

// 表单数据
const form = ref({
  name: '',
  description: ''
})

// 获取类型列表
const fetchTypeList = async () => {
  loading.value = true
  try {
    const { currentPage, pageSize } = pagination.value
    const res = await getPlaylistTypePage(currentPage, pageSize, searchKeyword.value)
    
    console.log('歌单类型列表响应:', res)
    
    if (res.code === 200) {
      // 处理类型列表数据
      const data = res.data
      // 兼容不同的数据结构
      typeList.value = data.records || data.list || []
      pagination.value.total = data.total || 0
    } else {
      ElMessage.error(res.message || '获取歌单类型列表失败')
    }
  } catch (error) {
    console.error('获取歌单类型列表失败:', error)
    ElMessage.error('获取歌单类型列表失败')
  } finally {
    loading.value = false
  }
}

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

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

// 搜索类型
const searchType = () => {
  pagination.value.currentPage = 1
  fetchTypeList()
}

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

// 添加类型
const addType = () => {
  dialogTitle.value = '添加歌单类型'
  currentType.value = null
  form.value = {
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑类型
const editType = (row) => {
  dialogTitle.value = '编辑歌单类型'
  currentType.value = row
  form.value = {
    name: row.name,
    description: row.description || ''
  }
  dialogVisible.value = true
}

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

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!form.value.name) {
    ElMessage.warning('请输入类型名称')
    return
  }
  
  try {
    let res
    const formData = {
      name: form.value.name,
      description: form.value.description
    }
    
    if (currentType.value) {
      // 编辑类型
      res = await updatePlaylistType(currentType.value.id, formData)
    } else {
      // 添加类型
      res = await addPlaylistType(formData)
    }
    
    if (res.code === 200) {
      ElMessage.success(currentType.value ? '编辑成功' : '添加成功')
      dialogVisible.value = false
      fetchTypeList() // 重新加载列表
    } else {
      ElMessage.error(res.message || (currentType.value ? '编辑失败' : '添加失败'))
    }
  } catch (error) {
    console.error(currentType.value ? '编辑歌单类型失败:' : '添加歌单类型失败:', error)
    ElMessage.error(currentType.value ? '编辑失败，请稍后重试' : '添加失败，请稍后重试')
  }
}

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

<template>
  <div class="admin-playlist-type-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入类型名称/描述"
        clearable
        @clear="resetSearch"
        @keyup.enter="searchType"
        class="search-input"
      >
        <template #append>
          <el-button @click="searchType">
            <el-icon><search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
      
      <el-button type="primary" @click="addType">
        <el-icon><plus /></el-icon>
        添加类型
      </el-button>
    </div>
    
    <!-- 类型列表 -->
    <el-table
      :data="typeList"
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      
      <el-table-column prop="name" label="类型名称" min-width="150"></el-table-column>
      
      <el-table-column prop="description" label="描述" min-width="200">
        <template #default="scope">
          <el-tooltip
            :content="scope.row.description"
            placement="top"
            :show-after="500"
          >
            <div class="description-text">{{ scope.row.description || '-' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editType(scope.row)"
          >
            编辑
          </el-button>
          
          <el-button
            size="small"
            type="danger"
            @click="deleteType(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="[7, 14, 21, 28]"
        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="500px"
    >
      <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="描述">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入类型描述" 
          />
        </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-playlist-type-container {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.el-table {
  flex: 1;
  overflow: hidden;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.description-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

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