<template>
  <div>
    <div class="flex items-center justify-between mb-4">
      <h1 class="text-lg font-bold text-gray-800">Banner 管理</h1>
      <el-button type="primary" @click="openCreate">
        <el-icon class="mr-1"><Plus /></el-icon>新增 Banner
      </el-button>
    </div>

    <!-- Banner List -->
    <div class="space-y-3">
      <div v-for="item in banners" :key="item.id"
        class="bg-white rounded-xl border border-gray-200 p-4 flex items-start gap-4 hover:shadow-sm transition-shadow">
        <!-- Image Preview -->
        <div class="w-56 h-28 shrink-0 rounded-lg overflow-hidden bg-gray-100 border">
          <img :src="item.image_url" class="w-full h-full object-cover" @error="onImgError($event)" />
        </div>

        <!-- Info -->
        <div class="flex-1 min-w-0">
          <div class="flex items-center gap-2 mb-2">
            <el-tag size="small" :type="item.is_valid ? 'success' : 'danger'">
              {{ item.is_valid ? '启用' : '禁用' }}
            </el-tag>
            <el-tag v-if="item.is_jump" size="small" type="warning">可跳转</el-tag>
            <el-tag size="small" type="info">排序: {{ item.sort }}</el-tag>
          </div>
          <div class="text-sm text-gray-500 truncate mb-1">
            <span class="text-gray-400">图片:</span> {{ item.image_url }}
          </div>
          <div v-if="item.is_jump && item.jump_path" class="text-sm text-gray-500 truncate">
            <span class="text-gray-400">跳转:</span> {{ item.jump_path }}
          </div>
          <div class="text-xs text-gray-400 mt-1">创建时间: {{ item.created_at }}</div>
        </div>

        <!-- Actions -->
        <div class="flex gap-2 shrink-0">
          <el-button size="small" @click="openEdit(item)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(item.id)">删除</el-button>
        </div>
      </div>

      <!-- Empty -->
      <div v-if="banners.length === 0" class="bg-white rounded-xl border border-gray-200 p-12 text-center text-gray-400">
        <div class="i-carbon-image text-5xl mx-auto mb-3 opacity-50" />
        <p>暂无 Banner，点击右上角「新增 Banner」添加</p>
      </div>
    </div>

    <!-- Create/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑 Banner' : '新增 Banner'" width="520px" destroy-on-close>
      <el-form :model="form" label-width="100px" size="small">
        <!-- Image URL -->
        <el-form-item label="图片地址" required>
          <el-input v-model="form.image_url" placeholder="输入图片URL或上传图片" class="mb-2" />
          <div class="flex gap-2">
            <el-upload :show-file-list="false" :auto-upload="false" accept="image/*" @change="handleUpload">
              <el-button size="small">选择图片</el-button>
            </el-upload>
            <span v-if="form.image_url" class="text-xs text-gray-400 self-center ml-1">已选择: {{ previewName }}</span>
          </div>
          <img v-if="form.image_url" :src="form.image_url" class="mt-2 w-full h-24 object-cover rounded border" @error="onImgError($event)" />
        </el-form-item>

        <!-- Jump Settings -->
        <el-form-item label="可跳转">
          <el-switch v-model="form.is_jump" />
        </el-form-item>
        <el-form-item v-if="form.is_jump" label="跳转链接">
          <el-input v-model="form.jump_path" placeholder="输入跳转URL" />
        </el-form-item>

        <!-- Sort -->
        <el-form-item label="排序号">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>

        <!-- Valid -->
        <el-form-item label="状态">
          <el-switch v-model="form.is_valid" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getBanners, createBanner, updateBanner, deleteBanner, uploadImage } from '@/api'

const banners = ref<any[]>([])
const dialogVisible = ref(false)
const isEditing = ref(false)
const saving = ref(false)
const previewUrl = ref('')
const previewName = ref('')

const form = reactive({
  id: 0,
  image_url: '',
  jump_path: '',
  is_jump: false,
  sort: 0,
  is_valid: true,
})

async function loadBanners() {
  const res: any = await getBanners()
  banners.value = res?.data || []
}

function openCreate() {
  isEditing.value = false
  form.id = 0
  form.image_url = ''
  form.jump_path = ''
  form.is_jump = false
  form.sort = 0
  form.is_valid = true
  previewUrl.value = ''
  dialogVisible.value = true
}

function openEdit(item: any) {
  isEditing.value = true
  form.id = item.id
  form.image_url = item.image_url
  form.jump_path = item.jump_path || ''
  form.is_jump = item.is_jump
  form.sort = item.sort
  form.is_valid = item.is_valid
  dialogVisible.value = true
}

async function handleUpload(uploadFile: any) {
  const file = uploadFile.raw
  if (!file) return
  previewName.value = file.name
  saving.value = true
  try {
    const res: any = await uploadImage(file)
    const url = res?.data?.url || res?.url || ''
    if (url) {
      form.image_url = url
    } else {
      ElMessage.error('上传失败：响应中未找到图片 URL')
    }
  } catch {
    // handled by interceptor
  } finally {
    saving.value = false
  }
}

async function handleSave() {
  if (!form.image_url) {
    ElMessage.warning('请填写图片地址')
    return
  }
  saving.value = true
  try {
    if (isEditing.value) {
      await updateBanner(form.id, {
        image_url: form.image_url,
        jump_path: form.jump_path,
        is_jump: form.is_jump,
        sort: form.sort,
        is_valid: form.is_valid,
      })
      ElMessage.success('更新成功')
    } else {
      await createBanner({
        image_url: form.image_url,
        jump_path: form.jump_path,
        is_jump: form.is_jump,
        sort: form.sort,
      })
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadBanners()
  } catch {
    // handled by interceptor
  } finally {
    saving.value = false
  }
}

async function handleDelete(id: number) {
  try {
    await ElMessageBox.confirm('确定删除该 Banner？', '删除确认', { type: 'warning' })
    await deleteBanner(id)
    ElMessage.success('删除成功')
    loadBanners()
  } catch {}
}

function onImgError(e: Event) {
  (e.target as HTMLImageElement).src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100"><rect fill="%23f3f4f6" width="200" height="100"/><text x="100" y="55" text-anchor="middle" fill="%239ca3af" font-size="12">加载失败</text></svg>'
}

onMounted(loadBanners)
</script>
