<template>
  <div class="file-uploader">
    <div class="upload-area" v-if="!isUploading">
      <el-upload
        ref="uploadRef"
        class="upload-dragger"
        drag
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleFileChange"
        multiple
        accept=".json,.png,.jpg,.jpeg,.bmp,.tiff"
      >
        <el-icon class="upload-icon"><Upload /></el-icon>
        <div class="upload-text">将文件拖到此处，或点击上传</div>
        <div class="upload-hint">
          请同时上传 OCR JSON 文件和对应的图片文件
        </div>
      </el-upload>
      
      <!-- 已选择的文件 -->
      <div class="selected-files" v-if="jsonFile || imageFile">
        <div class="file-item" v-if="jsonFile">
          <el-icon><Document /></el-icon>
          <span>{{ jsonFile.name }}</span>
          <el-button link type="danger" @click="jsonFile = null">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="file-item" v-if="imageFile">
          <el-icon><Picture /></el-icon>
          <span>{{ imageFile.name }}</span>
          <el-button link type="danger" @click="imageFile = null">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <el-button 
          type="primary" 
          @click="handleUpload"
          :disabled="!jsonFile || !imageFile"
          class="upload-btn"
        >
          <el-icon><UploadFilled /></el-icon>
          开始分析
        </el-button>
      </div>
    </div>
    
    <!-- 上传中 -->
    <div class="uploading" v-else>
      <el-icon class="is-loading" :size="48"><Loading /></el-icon>
      <div class="uploading-text">正在分析...</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Document, Picture, Close, UploadFilled, Loading } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { uploadFiles } from '@/api'
import { useEditorStore } from '@/stores'

const editorStore = useEditorStore()
const jsonFile = ref<File | null>(null)
const imageFile = ref<File | null>(null)
const isUploading = ref(false)

function handleFileChange(uploadFile: UploadFile) {
  const file = uploadFile.raw
  if (!file) return
  
  const ext = file.name.split('.').pop()?.toLowerCase()
  
  if (ext === 'json') {
    jsonFile.value = file
  } else if (['png', 'jpg', 'jpeg', 'bmp', 'tiff'].includes(ext || '')) {
    imageFile.value = file
  } else {
    ElMessage.warning(`不支持的文件格式: ${ext}`)
  }
}

async function handleUpload() {
  if (!jsonFile.value || !imageFile.value) {
    ElMessage.warning('请同时选择 JSON 文件和图片文件')
    return
  }
  
  isUploading.value = true
  editorStore.setLoading(true)
  
  try {
    const response = await uploadFiles(jsonFile.value, imageFile.value)
    
    if (response.success) {
      editorStore.loadData(
        response.image_base64,
        response.image_size,
        response.structure,
        response.scale_factor,
        response.ocr_data || null,
        response.suggested_filename || undefined
      )
      
      ElMessage.success('分析完成')
      
      // 清空选择
      jsonFile.value = null
      imageFile.value = null
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error: unknown) {
    console.error('上传失败:', error)
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    ElMessage.error(`上传失败: ${errorMessage}`)
  } finally {
    isUploading.value = false
    editorStore.setLoading(false)
  }
}
</script>

<style scoped>
.file-uploader {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area {
  text-align: center;
}

.upload-dragger {
  width: 400px;
}

.upload-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 13px;
  color: #909399;
}

.selected-files {
  margin-top: 24px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.upload-btn {
  margin-top: 16px;
}

.uploading {
  text-align: center;
  color: #909399;
}

.uploading-text {
  margin-top: 16px;
  font-size: 14px;
}
</style>
