<template>
  <a-modal
    v-model:open="open"
    title="上传文档"
    :footer="null"
    width="600px"
    :maskClosable="false"
  >
    <a-upload-dragger
      style="margin: 20px 0 10px; width: 100%"
      v-model:fileList="fileList"
      name="file"
      :multiple="true"
      :maxCount="1"
      accept=".pdf"
      :beforeUpload="handleUpload"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
      </p>
      <p class="ant-upload-text">点击上传或拖入文档</p>
      <p class="ant-upload-hint">文档单个最大50MB；当前仅支持PDF格式</p>
    </a-upload-dragger>
  </a-modal>
</template>
<script lang="ts" setup>
/**
 * @description 文件上传组件
 */
import { ref, defineExpose } from "vue";
import { InboxOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import http from "@/utils/http";

const props = defineProps<{
  pid?: number
}>();
const emits = defineEmits<{
  (e: 'close'):void
}>()
// 弹窗部分
const open = ref<boolean>(false);
const showModal = () => {
  open.value = true;
};

// 文件上传部分
const fileList = ref<any[]>([]);
const handleUpload = async (file: any) => {
  if(props.id === null) return;
  if(!file) return;
  const sizeNum = parseFloat((file.size / 1024 / 1024).toFixed(2))
  if(sizeNum > 50){
    message.error("上传文件不能大于50MB！");
    return;
  }
  const urlStr = '/ai/knowledge/file/create'
  const formData = new FormData();
  formData.append("parentId", props.pid)
  formData.append("file", file); // 文件对象
  formData.append("name", file.name); // 用户id
  formData.append("size", file.size);
  formData.append("type", file.type);
  http.post(urlStr, formData).then((result) => {
    if (result.data) {
      message.success("文件导入成功！");
      const timer = setTimeout(()=>{
        open.value = false;
        emits('close')
        clearTimeout(timer)
      }, 1500)
    } else {
      message.error("文件导入失败，请稍后重试！");
    }
  });
  return false;
};
defineExpose({ showModal });
</script>
