<script lang="ts" setup>
  import { computed } from 'vue';
  import { message, Upload } from 'ant-design-vue';
  import { uploadApi } from '/@/api/sys/upload';
  import { UploadApiResult } from '/@/api/sys/model/uploadModel';
  import { FileItem, FileInfo, CustomFile } from '/@/components/Upload/src/upload';

  const props = defineProps<{
    fileList: FileItem[];
  }>();
  const emit = defineEmits(['update:fileList']);

  // 使用计算属性，实现双向数据绑定
  const file = computed({
    get: () => props.fileList,
    set: (value: any) => emit('update:fileList', value),
  });

  const handleChange = ({ fileList: newFileList }: FileInfo) => {
    file.value = newFileList;
  };
  const customRequest = async (newFile: CustomFile) => {
    try {
      console.log(newFile);
      const res = await uploadApi({ file: newFile.file });
      const response = res.data as UploadApiResult;
      const fileInfo = file.value.filter((el) => el.uid === newFile.file.uid)[0];
      if (response.code === 20000) {
        newFile.onSuccess(response.data, fileInfo);
      } else {
        message.error(response?.msg);
        newFile.onError(response.data, fileInfo);
      }
    } catch (e) {
      console.log(e);
    }
  };
</script>

<template>
  <Upload
    v-model:file-list="file"
    action="/api/mg/attach/upload"
    list-type="picture-card"
    @change="handleChange"
    :customRequest="customRequest"
  >
    <slot></slot>
  </Upload>
</template>
