<template>
  <a-upload :before-upload="beforeUpload" v-model:file-list="fileList" @change="handleChange">
    <a-button type="primary"> Upload </a-button>
  </a-upload>
</template>
<script lang="ts">
  import { defineComponent, reactive, toRefs } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { uploadApi } from '/@/api/sys/upload';

  interface FileItem {
    uid: string;
    name?: string;
    status?: string;
    response?: string;
    url?: string;
  }
  interface FileInfo {
    file: FileItem;
    fileList: FileItem[];
  }
  interface State {
    fileList: FileItem[];
  }

  export default defineComponent({
    components: {
      [Upload.name]: Upload,
    },
    setup() {
      const state = reactive<State>({
        fileList: [
          {
            uid: '1',
            name: 'xxx.png',
            status: 'done',
            response: 'Server Error 500', // custom error message to show
            url: 'http://www.baidu.com/xxx.png',
          },
          {
            uid: '2',
            name: 'yyy.png',
            // status: 'done',
            url: 'http://www.baidu.com/yyy.png',
          },
          {
            uid: '3',
            name: 'zzz.png',
            status: 'error',
            response: 'Server Error 500', // custom error message to show
            url: 'http://www.baidu.com/zzz.png',
          },
        ],
      });
      function beforeUpload(file) {
        console.log(`file`, file);
        uploadApi({ file })
          .then((res) => {
            console.log(`res`, res);
          })
          .catch((err) => {
            console.log(`err`, err);
          });
        return false;
      }
      const handleChange = ({ file, fileList }: FileInfo) => {
        console.log(`file`, file);
        console.log(`fileList`, fileList);
        if (file.status !== 'uploading') {
          console.log(file, fileList);
        }
      };
      return {
        beforeUpload,
        handleChange,
        ...toRefs(state),
      };
    },
  });
</script>
