<script setup lang="ts">
import type { UploadProps} from "ant-design-vue";
import {ref} from "vue";
import {
  UploadOutlined
} from '@ant-design/icons-vue';
const fileList1 = ref<UploadProps['fileList']>([]);
const props = defineProps({ filePath: String });
const emit= defineEmits(['update:filePath'])
const handleRemove = (file: UploadProps['fileList']) => {
  console.log( file)
  return false;
};
console.log(props.filePath)
const handleUpload = (options: any) => {
  const { file, onSuccess, onError, onProgress } = options;

  // 创建 FormData 对象
  const formData = new FormData();
  formData.append('file', file);

  // 使用 XMLHttpRequest 进行上传
  const xhr = new XMLHttpRequest();

  // 监听上传进度
  xhr.upload.onprogress = (event) => {
    if (event.lengthComputable) {
      onProgress({ percent: (event.loaded / event.total) * 100 }, file);
    }
  };

  // 上传成功回调
  xhr.onload = () => {
    if (xhr.status === 200 || xhr.status === 201) {
      console.log(xhr.responseText);
      onSuccess(xhr.responseText, file);
      emit('update:filePath', xhr.responseText)
    } else {
      onError(new Error(`Upload failed with status ${xhr.status}`));
    }
  };
  // 上传错误回调
  xhr.onerror = () => {
    onError(new Error('Network error'));
  };

  // 发送请求到服务器
  xhr.open('POST', 'http://192.168.8.146:5000/upload');
  xhr.send(formData);
};

</script>

<template>
  <a-layout-content class="container">
    <a-upload
        v-model:file-list="fileList1"
        :customRequest="handleUpload"
        list-type="picture"
        class="upload-list-inline"
        :max-count="1"
        @remove="handleRemove"
    >
      <a-button >
        <upload-outlined></upload-outlined>
        上传发票
      </a-button>
    </a-upload>

  </a-layout-content>
</template>

<style scoped>
.container {
   height: 100%;
}
</style>