<template>
  <a-card :bordered="false" class="content-card">
    <template #title>轮播图设置</template>
    <template #extra>
      <a-space>
        <a-button type="primary" @click="openBannerModal()">
          <template #icon><icon-plus /></template>
          新增轮播图
        </a-button>
        <a-button @click="loadBanners">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </a-space>
    </template>
    <a-table :columns="bannerColumns" :data="banners" :pagination="false" :bordered="false">
      <template #imageUrl="{ record }">
        <img :src="record.imageUrl" style="width: 80px; height: 40px; object-fit: cover; border-radius: 4px" />
      </template>
      <template #enabled="{ record }">
        <a-switch :model-value="record.enabled" @change="(v) => { record.enabled = v; openBannerModal(record) }" />
      </template>
      <template #actions="{ record }">
        <a-space>
          <a-button size="mini" type="primary" shape="round" @click="openBannerModal(record)">编辑</a-button>
          <a-popconfirm content="确定删除此轮播图吗？" @ok="deleteBanner(record.id)">
            <a-button size="mini" status="danger" shape="round">删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
  </a-card>

  <a-modal v-model:visible="bannerModalVisible" :title="bannerForm.id ? '编辑轮播图' : '新增轮播图'" :ok-text="bannerForm.id ? '保存' : '添加'" cancel-text="取消" @ok="submitBannerModal" width="500">
    <a-form :model="bannerForm" layout="vertical">
      <a-form-item label="轮播图片" required>
        <a-upload
          :action="uploadAction"
          :show-file-list="false"
          :headers="uploadHeaders"
          accept="image/*"
          @success="onUploadSuccess"
          @error="onUploadError"
          @before-upload="beforeUpload"
        >
          <template #upload-button>
            <div class="upload-trigger" :class="{ 'has-image': bannerForm.imageUrl }">
              <img v-if="bannerForm.imageUrl" :src="bannerForm.imageUrl" class="preview-image" />
              <div v-else class="upload-placeholder">
                <icon-plus :size="24" />
                <span>点击上传图片</span>
              </div>
            </div>
          </template>
        </a-upload>
        <div v-if="bannerForm.imageUrl" class="upload-actions">
          <a-button type="text" size="small" @click="clearImage">
            <template #icon><icon-delete /></template>
            清除图片
          </a-button>
        </div>
      </a-form-item>
      <a-form-item label="跳转链接">
        <a-input v-model="bannerForm.linkUrl" placeholder="点击轮播图跳转的URL（可选）" allow-clear />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="排序">
            <a-input-number v-model="bannerForm.sortNo" :min="1" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="启用状态">
            <a-switch v-model="bannerForm.enabled" />
            <span style="margin-left: 8px">{{ bannerForm.enabled ? '启用' : '禁用' }}</span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { api } from '../../api'
import { IconPlus, IconRefresh, IconDelete } from '@arco-design/web-vue/es/icon'

const banners = ref([])
const bannerModalVisible = ref(false)
const bannerForm = reactive({ id: null, imageUrl: '', linkUrl: '', sortNo: 1, enabled: true })

const uploadAction = '/api/upload/image'
const uploadHeaders = computed(() => ({
  'X-Token': localStorage.getItem('token') || ''
}))

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    Message.error('只能上传图片文件！')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    Message.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

const onUploadSuccess = (uploadInfo) => {
  const response = uploadInfo.response
  console.log('Upload server response:', response)
  if (response && response.code === 0 && response.data) {
    const imageUrl = response.data
    console.log('Image URL from response:', imageUrl)
    if (imageUrl.startsWith('/')) {
      bannerForm.imageUrl = window.location.origin + imageUrl
    } else {
      bannerForm.imageUrl = imageUrl
    }
    console.log('Final imageUrl:', bannerForm.imageUrl)
    Message.success('图片上传成功')
  } else {
    console.warn('Unexpected response format:', response)
    Message.warning('上传成功，但无法解析图片地址')
  }
}

const onUploadError = (error) => {
  Message.error('图片上传失败：' + (error.message || '未知错误'))
}

const clearImage = () => {
  bannerForm.imageUrl = ''
}

const bannerColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '图片', slotName: 'imageUrl', width: 100 },
  { title: '跳转链接', dataIndex: 'linkUrl', ellipsis: true },
  { title: '排序', dataIndex: 'sortNo', width: 70 },
  { title: '状态', slotName: 'enabled', width: 70 },
  { title: '操作', slotName: 'actions', width: 140 }
]

const loadBanners = async () => {
  banners.value = await api.adminBanners()
}

const openBannerModal = (row = null) => {
  if (row) {
    bannerForm.id = row.id
    bannerForm.imageUrl = row.imageUrl || ''
    bannerForm.linkUrl = row.linkUrl || ''
    bannerForm.sortNo = row.sortNo || 1
    bannerForm.enabled = !!row.enabled
  } else {
    bannerForm.id = null
    bannerForm.imageUrl = ''
    bannerForm.linkUrl = ''
    bannerForm.sortNo = 1
    bannerForm.enabled = true
  }
  bannerModalVisible.value = true
}

const submitBannerModal = async () => {
  await api.adminSaveBanner({ ...bannerForm })
  Message.success(bannerForm.id ? '轮播图已更新' : '轮播图已新增')
  bannerModalVisible.value = false
  await loadBanners()
}

const deleteBanner = async (id) => {
  await api.adminDeleteBanner(id)
  Message.success('轮播图已删除')
  await loadBanners()
}

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

<style scoped>
.content-card {
  border-radius: 12px;
}

:deep(.arco-btn-primary) {
  background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
  border-color: transparent;
}

:deep(.arco-card-header) {
  border-bottom: 1px solid #f0f0f0;
}

.upload-trigger {
  width: 100%;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.upload-trigger:hover {
  border-color: #722ed1;
}

.upload-trigger.has-image {
  border: none;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  gap: 8px;
}

.upload-actions {
  margin-top: 8px;
  text-align: center;
}
</style>
