<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 轮播图列表
const bannerList = ref([])

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

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

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

// 对话框标题
const dialogTitle = ref('添加轮播图')

// 当前编辑的轮播图
const currentBanner = ref(null)

// 表单数据
const form = ref({
  title: '',
  url: '',
  targetType: 1, // 1-音乐，2-歌单，3-歌手，4-外部链接
  targetId: '',
  orderNum: 0,
  status: 1, // 0-禁用，1-启用
  image: null
})

// 获取轮播图列表
const fetchBannerList = async () => {
  loading.value = true
  try {
    // 实际应用中，这里应该调用API获取轮播图列表
    // 模拟获取轮播图列表
    setTimeout(() => {
      const mockBanners = []
      const total = 20
      const { currentPage, pageSize } = pagination.value
      const start = (currentPage - 1) * pageSize
      const end = Math.min(start + pageSize, total)
      
      for (let i = start + 1; i <= end; i++) {
        mockBanners.push({
          id: i,
          title: `轮播图${i}`,
          url: `https://via.placeholder.com/1200x300?text=Banner${i}`,
          targetType: i % 4 + 1,
          targetId: i * 10,
          orderNum: i,
          status: i % 5 === 0 ? 0 : 1,
          createTime: new Date(Date.now() - i * 86400000).toISOString().split('T')[0]
        })
      }
      
      bannerList.value = mockBanners
      pagination.value.total = total
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('获取轮播图列表失败')
    loading.value = false
  }
}

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

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

// 添加轮播图
const addBanner = () => {
  dialogTitle.value = '添加轮播图'
  currentBanner.value = null
  form.value = {
    title: '',
    url: '',
    targetType: 1,
    targetId: '',
    orderNum: bannerList.value.length + 1,
    status: 1,
    image: null
  }
  dialogVisible.value = true
}

// 编辑轮播图
const editBanner = (row) => {
  dialogTitle.value = '编辑轮播图'
  currentBanner.value = row
  form.value = {
    title: row.title,
    url: row.url,
    targetType: row.targetType,
    targetId: row.targetId,
    orderNum: row.orderNum,
    status: row.status,
    image: null
  }
  dialogVisible.value = true
}

// 删除轮播图
const deleteBanner = (row) => {
  ElMessageBox.confirm(`确定要删除轮播图 ${row.title} 吗？此操作不可恢复`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际应用中，这里应该调用API删除轮播图
    bannerList.value = bannerList.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 更新轮播图状态
const updateBannerStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${statusText}轮播图 ${row.title} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际应用中，这里应该调用API更新轮播图状态
    const index = bannerList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      bannerList.value[index].status = newStatus
      ElMessage.success(`${statusText}成功`)
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  // 实际应用中，这里应该调用API添加/编辑轮播图
  if (currentBanner.value) {
    // 编辑轮播图
    const index = bannerList.value.findIndex(item => item.id === currentBanner.value.id)
    if (index !== -1) {
      bannerList.value[index] = {
        ...bannerList.value[index],
        title: form.value.title,
        targetType: form.value.targetType,
        targetId: form.value.targetId,
        orderNum: form.value.orderNum,
        status: form.value.status
      }
      ElMessage.success('编辑成功')
    }
  } else {
    // 添加轮播图
    const newBanner = {
      id: Date.now(),
      title: form.value.title,
      url: 'https://via.placeholder.com/1200x300?text=NewBanner',
      targetType: form.value.targetType,
      targetId: form.value.targetId,
      orderNum: form.value.orderNum,
      status: form.value.status,
      createTime: new Date().toISOString().split('T')[0]
    }
    bannerList.value.unshift(newBanner)
    ElMessage.success('添加成功')
  }
  
  dialogVisible.value = false
}

// 格式化目标类型
const formatTargetType = (type) => {
  const typeMap = {
    1: '音乐',
    2: '歌单',
    3: '歌手',
    4: '外部链接'
  }
  return typeMap[type] || '未知'
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    0: '禁用',
    1: '启用'
  }
  return statusMap[status] || '未知'
}

// 处理图片上传
const handleImageChange = (file) => {
  form.value.image = file
}

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

<template>
  <div class="admin-banner-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="addBanner">
        <el-icon><plus /></el-icon>
        添加轮播图
      </el-button>
    </div>
    
    <!-- 轮播图列表 -->
    <el-table
      :data="bannerList"
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      
      <el-table-column label="图片" width="200" align="center">
        <template #default="scope">
          <img 
            :src="scope.row.url" 
            :alt="scope.row.title" 
            class="banner-image"
          >
        </template>
      </el-table-column>
      
      <el-table-column prop="title" label="标题" min-width="150"></el-table-column>
      
      <el-table-column prop="targetType" label="目标类型" width="100">
        <template #default="scope">
          {{ formatTargetType(scope.row.targetType) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="targetId" label="目标ID" width="100"></el-table-column>
      
      <el-table-column prop="orderNum" label="排序" width="80" align="center"></el-table-column>
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="120"></el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editBanner(scope.row)"
          >
            编辑
          </el-button>
          
          <el-button
            size="small"
            :type="scope.row.status === 1 ? 'warning' : 'success'"
            @click="updateBannerStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          
          <el-button
            size="small"
            type="danger"
            @click="deleteBanner(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="[10, 20, 50, 100]"
        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.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        
        <el-form-item label="目标类型" required>
          <el-select
            v-model="form.targetType"
            placeholder="请选择目标类型"
            style="width: 100%"
          >
            <el-option :label="'音乐'" :value="1" />
            <el-option :label="'歌单'" :value="2" />
            <el-option :label="'歌手'" :value="3" />
            <el-option :label="'外部链接'" :value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="目标ID" v-if="form.targetType !== 4" required>
          <el-input v-model="form.targetId" placeholder="请输入目标ID" />
        </el-form-item>
        
        <el-form-item label="外部链接" v-if="form.targetType === 4" required>
          <el-input v-model="form.targetId" placeholder="请输入外部链接" />
        </el-form-item>
        
        <el-form-item label="排序" required>
          <el-input-number v-model="form.orderNum" :min="0" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        
        <el-form-item label="图片" required>
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleImageChange"
            :limit="1"
            list-type="picture-card"
          >
            <el-icon><plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            建议尺寸：1200 x 300 像素
          </div>
        </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-banner-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

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

.banner-image {
  width: 180px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

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