<template>
  <div class="file-upload">
    <input type="file" ref="fileInput" @change="handleFileChange" accept=".pdf" style="display: none" />
    <button @click="triggerFileInput" class="upload-button">
      选择PDF文件
    </button>
    <div v-if="uploading" class="upload-status">
      正在上传...
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const emit = defineEmits(['upload-complete'])
const fileInput = ref(null)
const uploading = ref(false)

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  uploading.value = true
  const formData = new FormData()
  formData.append('file', file)
  formData.append('dpi', '300')
  formData.append('min_size', '1000')
  formData.append('skip_first', '4')
  formData.append('skip_last', '80')

  try {
    const response = await fetch('http://192.168.1.111:8000/upload-pdf', {
      method: 'POST',
      body: formData
    })
    const data = await response.json()

    data.page_images = data.page_images.map(img => ({
      ...img,
      path: `http://192.168.1.111:8000/${img.path}`
    }))

    emit('upload-complete', data)
  } catch (error) {
    console.error('上传失败:', error)
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.file-upload {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.upload-button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.upload-button:hover {
  background-color: #45a049;
}

.upload-status {
  margin-top: 10px;
  color: #666;
}
</style>