<script setup name="CustomUploadComp" lang="ts">
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { Upload, Spin } from 'ant-design-vue';
  import { ref, watchEffect } from 'vue';
  import { useUpload } from './hooks/useUploadFile.hook';
  import { logoUpload } from '/@/api/oem';

  const props = withDefaults(
    defineProps<{
      imgUrl: string;
    }>(),
    {
      imgUrl: '',
    }
  );
  const emit = defineEmits(['setImg']);

  const { beforeUploadVerify } = useUpload();

  const uploadLoading = ref(false);

  const uploadImgUrl = ref('');

  //上传图片接口
  const customUpload = async ({ file }) => {
    try {
      if (beforeUploadVerify(file)) {
        uploadImgUrl.value = '';
        uploadLoading.value = true;
        const formData = new FormData();
        formData.append('file', file);
        const response = await logoUpload(formData);
        if (response.fileStaticUri) {
          uploadImgUrl.value = response.fileStaticUri;
          emit('setImg', uploadImgUrl.value);
        }
      }
    } finally {
      uploadLoading.value = false;
    }
  };

  watchEffect(() => {
    init();
  });
  function init() {
    if (!props.imgUrl) uploadImgUrl.value = '';
    uploadImgUrl.value = props.imgUrl;
  }
</script>

<template>
  <div>
    <Upload
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :customRequest="customUpload"
      :before-upload="beforeUploadVerify"
    >
      <img v-if="uploadImgUrl" class="fill-img" :src="uploadImgUrl" alt="avatar" />
      <div v-else>
        <Spin v-if="uploadLoading" tip="正在上传中..." />
        <PlusOutlined v-else />
        <div class="ant-upload-text">上传</div>
      </div>
    </Upload>
  </div>
</template>

<style lang="less" scoped>
  .fill-img {
    width: 100%;
    height: 100%;
  }
</style>
