<template>
  <div class="banner-management">
    <div class="page-header">
      <h2>轮播图管理</h2>
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon>添加轮播图
      </el-button>
    </div>

    <el-table
      :data="bannerList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="图片" width="180">
        <template #default="scope">
          <div>
            <ImagePreview
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              :width="120"
              :height="60"
              fit="cover"
              :preview-src-list="scope.row.imageUrl ? [scope.row.imageUrl] : []"
              :z-index="3000"
              @error="() => console.error('图片加载失败:', scope.row.imageUrl)"
            />
            <div v-else class="no-image">无图片</div>
            <div class="image-url-debug">
              <el-tooltip :content="scope.row.imageUrl || '无图片URL'" placement="top">
                <small>{{ scope.row.imageUrl ? scope.row.imageUrl.substring(0, 20) + '...' : '无图片URL' }}</small>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column label="目标类型" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.targetType === 1" type="success">音乐</el-tag>
          <el-tag v-else-if="scope.row.targetType === 2" type="warning">歌单</el-tag>
          <el-tag v-else-if="scope.row.targetType === 3" type="info">歌手</el-tag>
          <el-tag v-else type="danger">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="targetId" label="目标ID" width="100" />
      <el-table-column prop="orderNum" label="排序" width="80" sortable />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 12]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑轮播图对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑轮播图' : '添加轮播图'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="banner-upload"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <ImagePreview
              v-if="imageUrl"
              :src="imageUrl"
              :width="400"
              :height="150"
              fit="cover"
              :preview-src-list="imageUrl ? [imageUrl] : []"
              :z-index="3000"
              class="banner-image"
            />
            <div v-else class="banner-upload-placeholder">
              <el-icon><Plus /></el-icon>
              <div class="el-upload__text">点击上传图片</div>
            </div>
          </el-upload>
          <div class="upload-tip">建议尺寸：1200 x 400 像素，JPG/PNG 格式</div>
        </el-form-item>
        <el-form-item label="目标类型" prop="targetType">
          <el-select v-model="form.targetType" placeholder="请选择目标类型">
            <el-option label="音乐" :value="1" />
            <el-option label="歌单" :value="2" />
            <el-option label="歌手" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标ID" prop="targetId">
          <el-input v-model.number="form.targetId" placeholder="请输入目标ID" />
        </el-form-item>
        <el-form-item label="外部链接" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入外部链接（可选）" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, Search } from '@element-plus/icons-vue'
import ImagePreview from '../../components/ImagePreview.vue'
import {
  getBannerPage,
  getBannerById,
  addBanner,
  updateBanner,
  deleteBanner,
  updateBannerStatus,
  updateBannerOrder
} from '../../api/banner'

// 轮播图列表数据
const bannerList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(3)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const formLoading = ref(false)
const form = reactive({
  id: null,
  title: '',
  targetType: 1,
  targetId: null,
  linkUrl: '',
  orderNum: 1,
  status: 1
})
const imageUrl = ref('')
const imageFile = ref(null)

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  // 移除 image 的验证规则，在提交时手动验证
  targetType: [
    { required: true, message: '请选择目标类型', trigger: 'change' }
  ],
  targetId: [
    { required: true, message: '请输入目标ID', trigger: 'blur' },
    { type: 'number', message: '目标ID必须为数字', trigger: 'blur' }
  ],
  linkUrl: [
    { pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w.-]*)*\/?$/, message: '请输入有效的URL', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString()
}

// 获取轮播图列表
const fetchBannerList = async () => {
  loading.value = true
  try {
    const res = await getBannerPage(currentPage.value, pageSize.value)
    console.log('获取轮播图列表响应:', res)
    if (res.code === 200) {
      // 适配不同的数据结构
      if (res.data.records) {
        bannerList.value = res.data.records
        total.value = res.data.total
      } else if (res.data.list) {
        bannerList.value = res.data.list
        total.value = res.data.total
      } else {
        bannerList.value = Array.isArray(res.data) ? res.data : []
        total.value = bannerList.value.length
      }
      console.log('轮播图列表数据:', bannerList.value)
    } else {
      ElMessage.error(res.message || '获取轮播图列表失败')
    }
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

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

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

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    const res = await updateBannerStatus(row.id, row.status)
    if (res.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(res.message || '状态更新失败')
    }
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
    console.error('更新轮播图状态失败:', error)
    ElMessage.error('更新轮播图状态失败，请稍后再试')
  }
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  isEdit.value = true
  resetForm()

  try {
    const res = await getBannerById(row.id)
    if (res.code === 200) {
      const bannerData = res.data
      form.id = bannerData.id
      form.title = bannerData.title
      form.targetType = bannerData.targetType
      form.targetId = bannerData.targetId
      form.linkUrl = bannerData.linkUrl || ''
      form.orderNum = bannerData.orderNum
      form.status = bannerData.status

      // 设置图片URL
      if (bannerData.imageUrl) {
        imageUrl.value = bannerData.imageUrl
        console.log('编辑模式设置图片URL:', imageUrl.value)
      }

      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取轮播图详情失败')
    }
  } catch (error) {
    console.error('获取轮播图详情失败:', error)
    ElMessage.error('获取轮播图详情失败，请稍后再试')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }

  form.id = null
  form.title = ''
  form.targetType = 1
  form.targetId = null
  form.linkUrl = ''
  form.orderNum = 1
  form.status = 1

  imageUrl.value = ''
  imageFile.value = null
}

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

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

    // 设置图片预览
    imageFile.value = file.raw
    imageUrl.value = URL.createObjectURL(file.raw)

    console.log('图片已选择:', imageFile.value, imageUrl.value)
  } else {
    console.log('没有选择图片')
  }
}

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

  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 检查是否上传了图片
      if (!isEdit.value && !imageFile.value) {
        ElMessage.error('请上传轮播图图片')
        return
      }

      // 编辑模式下，如果没有选择新图片，也没有原图片URL，则提示上传图片
      if (isEdit.value && !imageFile.value && !imageUrl.value) {
        ElMessage.error('请上传轮播图图片')
        return
      }

      formLoading.value = true

      try {
        let res
        if (isEdit.value) {
          // 编辑轮播图
          console.log('提交编辑表单:', form, imageFile.value, imageUrl.value)
          res = await updateBanner(form.id, form, imageFile.value)
        } else {
          // 添加轮播图
          console.log('提交添加表单:', form, imageFile.value)
          res = await addBanner(form, imageFile.value)
        }

        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchBannerList()
        } else {
          ElMessage.error(res.message || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新轮播图失败:' : '添加轮播图失败:', error)
        ElMessage.error((isEdit.value ? '更新' : '添加') + '轮播图失败，请稍后再试')
      } finally {
        formLoading.value = false
      }
    }
  })
}

// 处理删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这个轮播图吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteBanner(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        // 如果当前页只有一条数据，且不是第一页，则返回上一页
        if (bannerList.value.length === 1 && currentPage.value > 1) {
          currentPage.value--
        }
        fetchBannerList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除轮播图失败:', error)
      ElMessage.error('删除轮播图失败，请稍后再试')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchBannerList()
})
</script>

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  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;
}

.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;
}

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

.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;
}

.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);
}

.el-tag {
  border-radius: 8px !important;
}

.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);
}

.banner-upload {
  width: 100%;
}

.banner-image {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.banner-image:hover {
  transform: scale(1.02);
}

.banner-upload-placeholder {
  width: 100%;
  max-width: 400px;
  height: 150px;
  border: 1px dashed #b3e5fc;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.banner-upload-placeholder:hover {
  border-color: #4dd0e1;
  transform: scale(1.01);
}

.banner-upload-placeholder .el-icon {
  font-size: 28px;
  color: #4dd0e1;
}

.upload-tip {
  font-size: 12px;
  color: #4a4a4a;
  margin-top: 5px;
}

.no-image {
  width: 120px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e1f5fe;
  color: #4a4a4a;
  font-size: 12px;
  border-radius: 8px;
  transition: all 0.3s;
}

.no-image:hover {
  transform: scale(1.05);
}

.image-url-debug {
  margin-top: 5px;
  font-size: 8px;
  color: #4a4a4a;
  word-break: break-all;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-error {
  width: 120px;
  height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ffebee;
  color: #f44336;
  font-size: 12px;
  border-radius: 8px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.el-switch :deep(.el-switch__core) {
  border-radius: 12px !important;
}

.el-switch :deep(.el-switch__action) {
  border-radius: 50% !important;
}
</style>
