<template>
  <div class="banner-page">
    <div class="page-header">
      <h2>📺 轮播图管理</h2>
      <p class="desc">管理移动端首页轮播广告图</p>
    </div>

    <el-card shadow="never">
      <div style="margin-bottom:16px">
        <el-button type="primary" @click="showDialog = true; editForm = {title:'',url:'',sort:0}">
          <el-icon><Plus /></el-icon>添加轮播图
        </el-button>
        <el-button @click="loadBanners" :icon="Refresh">刷新</el-button>
      </div>
      
      <el-table :data="banners" v-loading="loading" border stripe>
        <el-table-column label="预览" width="200">
          <template #default="{row}">
            <el-image :src="row.image" style="width:180px;height:80px;object-fit:cover;border-radius:4px">
              <template #error><div style="width:180px;height:80px;background:#f0f0f0;display:flex;align-items:center;justify-content:center;color:#ccc">📷</div></template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column prop="url" label="链接" min-width="200">
          <template #default="{row}"><span style="color:#999;font-size:12px">{{ row.url || '-' }}</span></template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">{{ row.status === 1 ? '显示' : '隐藏' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="small" @click="editBanner(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteBanner(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="showDialog" :title="editingId ? '编辑轮播图' : '添加轮播图'" width="500px">
      <el-form label-width="100px">
        <el-form-item label="上传图片">
          <el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="onUpload" accept="image/*">
            <el-button type="primary">选择图片</el-button>
          </el-upload>
          <div v-if="editForm.image" style="margin-top:8px">
            <el-image :src="editForm.image" style="width:100%;max-height:150px;object-fit:cover;border-radius:4px" />
            <div style="font-size:12px;color:#999;margin-top:4px">点击 <el-button size="small" circle @click="editForm.image=''">✕</el-button> 移除</div>
          </div>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="editForm.title" placeholder="轮播图标题（选填）" />
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="editForm.url" placeholder="点击跳转链接（选填）" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editForm.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBanner" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'

const banners = ref([])
const loading = ref(false)
const saving = ref(false)
const showDialog = ref(false)
const editingId = ref(null)
const editForm = ref({ title: '', url: '', sort: 0, image: '' })

const token = localStorage.getItem('admin_token')
const uploadUrl = '/api/admin/banner/add'
const uh = { Authorization: 'Bearer ' + token }

async function loadBanners() {
  loading.value = true
  try {
    const resp = await fetch('/api/admin/banner/list', { headers: { Authorization: 'Bearer ' + token } })
    const data = await resp.json()
    if (data.code === 0) banners.value = data.data || []
  } catch (e) { ElMessage.error('加载失败') }
  finally { loading.value = false }
}

function onUpload(resp) {
  if (resp.code === 0) {
    editForm.value.image = resp.data?.url || resp.data?.image || ''
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(resp.message || '上传失败')
  }
}

function editBanner(row) {
  editingId.value = row.id
  editForm.value = { title: row.title, url: row.url, sort: row.sort, image: row.image }
  showDialog.value = true
}

async function saveBanner() {
  if (!editForm.value.image) { ElMessage.warning('请上传图片'); return }
  saving.value = true
  try {
    const method = editingId.value ? 'PUT' : 'POST'
    const url = editingId.value ? '/api/admin/banner/' + editingId.value : '/api/admin/banner/add'
    const resp = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
      body: JSON.stringify(editForm.value)
    })
    const data = await resp.json()
    if (data.code === 0) {
      ElMessage.success(editingId.value ? '更新成功' : '添加成功')
      showDialog.value = false
      loadBanners()
    } else {
      ElMessage.error(data.message)
    }
  } catch (e) { ElMessage.error('保存失败') }
  finally { saving.value = false }
}

async function deleteBanner(row) {
  try {
    await ElMessageBox.confirm('确定删除这张轮播图？')
    const resp = await fetch('/api/admin/banner/' + row.id, {
      method: 'DELETE', headers: { Authorization: 'Bearer ' + token }
    })
    const data = await resp.json()
    if (data.code === 0) { ElMessage.success('已删除'); loadBanners() }
    else ElMessage.error(data.message)
  } catch (e) { /* cancelled */ }
}

onMounted(loadBanners)
</script>

<style scoped>
.banner-page { padding: 20px; }
.page-header { margin-bottom: 20px; }
.page-header h2 { font-size: 22px; color: #1a1a2e; margin: 0 0 6px 0; }
.page-header .desc { color: #999; font-size: 13px; }
</style>
