<template>
  <div>
    <h3>轮播图上传测试</h3>
    
    <!-- 方式1: 使用 el-upload -->
    <div style="margin: 20px 0;">
      <h4>方式1: Element Plus Upload</h4>
      <el-upload
        action="/api/file/upload"
        :show-file-list="false"
        :on-success="handleSuccess"
        :on-error="handleError"
        :before-upload="beforeUpload"
        accept="image/*"
        name="file"
        :headers="uploadHeaders"
      >
        <el-button type="primary">点击上传</el-button>
      </el-upload>
      <div v-if="uploadedUrl">
        <p>上传成功: {{ uploadedUrl }}</p>
        <img :src="uploadedUrl" style="max-width: 300px;" />
      </div>
    </div>

    <!-- 方式2: 原生 input -->
    <div style="margin: 20px 0;">
      <h4>方式2: 原生 Input</h4>
      <input type="file" @change="handleFileChange" accept="image/*" />
      <button @click="uploadFile">手动上传</button>
      <div v-if="uploadedUrl2">
        <p>上传成功: {{ uploadedUrl2 }}</p>
        <img :src="uploadedUrl2" style="max-width: 300px;" />
      </div>
    </div>

    <!-- 调试信息 -->
    <div style="margin: 20px 0; padding: 10px; background: #f5f5f5;">
      <h4>调试信息</h4>
      <p>后端地址: http://localhost:8089</p>
      <p>上传接口: /api/file/upload</p>
      <p>Token: {{ token ? '已设置' : '未设置' }}</p>
      <pre>{{ debugInfo }}</pre>
    </div>
  </div>
</template>

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

const uploadedUrl = ref('')
const uploadedUrl2 = ref('')
const selectedFile = ref(null)
const debugInfo = ref('')
const token = ref(localStorage.getItem('token'))

const uploadHeaders = computed(() => {
  return token.value ? { Authorization: `Bearer ${token.value}` } : {}
})

// 方式1: el-upload 回调
const beforeUpload = (file) => {
  console.log('beforeUpload:', file)
  debugInfo.value = `准备上传: ${file.name}, 大小: ${file.size} bytes`
  
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleSuccess = (response) => {
  console.log('上传成功:', response)
  debugInfo.value = JSON.stringify(response, null, 2)
  
  if (response.code === 200 && response.data) {
    uploadedUrl.value = response.data.fileUrl || response.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleError = (error) => {
  console.error('上传失败:', error)
  debugInfo.value = `上传失败: ${error.message || error}`
  ElMessage.error('上传失败')
}

// 方式2: 手动上传
const handleFileChange = (event) => {
  selectedFile.value = event.target.files[0]
  console.log('选择文件:', selectedFile.value)
}

const uploadFile = async () => {
  if (!selectedFile.value) {
    ElMessage.error('请先选择文件')
    return
  }

  const formData = new FormData()
  formData.append('file', selectedFile.value)

  try {
    debugInfo.value = '正在上传...'
    
    const response = await fetch('/api/file/upload', {
      method: 'POST',
      headers: uploadHeaders.value,
      body: formData
    })

    const data = await response.json()
    console.log('上传响应:', data)
    debugInfo.value = JSON.stringify(data, null, 2)

    if (data.code === 200 && data.data) {
      uploadedUrl2.value = data.data.fileUrl || data.data.url
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(data.message || '上传失败')
    }
  } catch (error) {
    console.error('上传错误:', error)
    debugInfo.value = `上传错误: ${error.message}`
    ElMessage.error('上传失败: ' + error.message)
  }
}
</script>
