<template>
  <div class="document-upload">
    <a-upload-dragger
      :multiple="true"
      :custom-request="handleUpload"
      :before-upload="beforeUpload"
      :show-upload-list="false"
      accept=".pdf,.docx,.doc,.md,.txt,.html,.csv,.json"
    >
      <p class="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
      <p class="ant-upload-hint">
        支持 PDF、Word、Markdown、HTML、纯文本等格式
      </p>
    </a-upload-dragger>

    <a-spin v-if="kbStore.isUploading" tip="正在上传处理..." class="upload-spin" />

    <div v-if="uploadedFiles.length > 0" class="uploaded-list">
      <a-divider>已上传文档</a-divider>
      <a-list :data-source="uploadedFiles" size="small">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #title>
                <span>{{ item.filename }}</span>
              </template>
              <template #description>
                <a-tag :color="item.status === 'indexed' ? 'green' : 'orange'">
                  {{ item.status === 'indexed' ? '已索引' : '处理中' }}
                </a-tag>
                <span class="chunk-count">{{ item.chunks }} 个分块</span>
              </template>
              <template #avatar>
                <FileOutlined />
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { InboxOutlined, FileOutlined } from '@ant-design/icons-vue'
import { useKnowledgeStore } from '@/stores/knowledge'

interface UploadedFile {
  document_id: string
  filename: string
  chunks: number
  status: string
}

const kbStore = useKnowledgeStore()
const uploadedFiles = ref<UploadedFile[]>([])

function beforeUpload(file: File): boolean {
  const validExtensions = ['.pdf', '.docx', '.doc', '.md', '.txt', '.html', '.csv', '.json']
  const ext = '.' + file.name.split('.').pop()?.toLowerCase()
  if (!validExtensions.includes(ext)) {
    message.error(`不支持的文件格式: ${ext}`)
    return false
  }
  return true
}

async function handleUpload(options: { file: File; onSuccess?: () => void; onError?: (err: unknown) => void }): Promise<void> {
  try {
    await kbStore.uploadDocument(options.file)
    uploadedFiles.value.unshift({
      document_id: Date.now().toString(),
      filename: options.file.name,
      chunks: 1,
      status: 'indexed',
    })
    message.success(`${options.file.name} 上传成功`)
    options.onSuccess?.()
  } catch (err) {
    message.error(`${options.file.name} 上传失败`)
    options.onError?.(err)
  }
}
</script>

<style scoped>
.document-upload {
  padding: 8px 0;
}

.upload-spin {
  display: block;
  text-align: center;
  padding: 16px;
}

.uploaded-list {
  margin-top: 16px;
}

.chunk-count {
  margin-left: 8px;
  color: #999;
  font-size: 12px;
}
</style>
