
<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { EmbeddingApi } from '@/api/new-ai/embedding'

const route = useRoute()
const fileList = ref<any[]>([])
const uploadRef = ref()

const handleUpload = async (file: File) => {
  const knowledgeId = route.params.id as string
  try {
    const formData = new FormData()
    formData.append('file', file)
    await EmbeddingApi.embeddingDocs(knowledgeId, formData, (event: any) => {
      if (event.lengthComputable) {
        const progress = Math.round((event.loaded * 100) / event.total)
        console.log('Upload progress:', progress)
      }
    })
    ElMessage.success('上传成功，文档解析中...')
  } catch (error) {
    console.error('Upload failed:', error)
    ElMessage.error('上传失败')
  }
}

const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件')
}
</script>

<template>
  <div class="upload-container">
    <el-upload
      ref="uploadRef"
      class="upload-dragger"
      drag
      :auto-upload="false"
      :limit="1"
      accept=".doc,.docx,.pdf,.txt,.md"
      :on-exceed="handleExceed"
      :on-change="(file) => handleUpload(file.raw as File)"
    >
      <el-icon class="el-icon--upload"><Upload /></el-icon>
      <div class="el-upload__text">
        拖拽文件到此处或 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持的文件格式：.txt、.md、.docx、.doc、.pdf
        </div>
      </template>
    </el-upload>
  </div>
</template>

<style scoped>
.upload-container {
  padding: 20px;
}

.upload-dragger {
  width: 100%;
}

.el-upload__tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

.el-icon--upload {
  font-size: 48px;
  color: var(--el-text-color-regular);
  margin-bottom: 12px;
}

.el-upload__text {
  color: var(--el-text-color-regular);
  font-size: 16px;
  margin: 8px 0;
}

.el-upload__text em {
  color: var(--el-color-primary);
  font-style: normal;
}
</style>
