<template>
  <a-upload
      :file-list="files"
      :action="FILE_UPLOAD_URL"
      :show-upload-list="showUploadList"
      :multiple="multiple"
      :before-upload="beforeUpload"
      @change="handleChange"
      ref="imageRef"
  >
    <template v-for="(_, key, index) in $slots" :key="index" v-slot:[key]>
      <slot :name="key"></slot>
    </template>
  </a-upload>
</template>
<script setup>
import {defineProps, defineEmits, defineExpose, ref, watch} from "vue";
import {message} from "ant-design-vue";
import {FILE_UPLOAD_URL} from "@/api/config";

const props = defineProps({
  value: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  showUploadList: {
    type: Boolean,
    default: false
  },
  fileType: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits({})

const files = ref([])
const imageRef = ref()

watch(props, () => {
  props.value.length !== files.value.length && (files.value = props.value)
})

function handleChange({file, fileList}) {
  file.response && file.response.code === 200 && (file.url = file.response.data)
  files.value = fileList
  emit('update:value', fileList)
}

function beforeUpload(file) {
  if (!props.fileType.includes(file.name.split(".").slice(-1).join(''))) {
    message.error(
        "不支持该格式"
    );
    return false;
  }
}

function remove(i) {
  files.value.splice(i, 1)
  emit('update:value', files.value)
}

function reUpload(i) {
  if (files.value[i].status === 'ready' || files.value[i].status === 'uploading') {
    imageRef.value.abort(files.value[i].raw)
    files.value[i].status = 'abort';
  } else if (files.value[i].status === 'fail' || files.value[i].status === 'abort') {
    imageRef.value.handleStart(files.value[i].raw)
    imageRef.value.submit()
  }
}

function abort(i) {
  imageRef.value.abort(files.value[i].raw)
}


defineExpose({reUpload, remove, abort})

</script>
