<template>
  <div class="upload">
    <a-upload :action="uploadUrl"
              v-model:file-list="uploadImgList"
              :before-upload="beforeUpload"
              @change="uploadAction">
      <a-button class="uploadBtn">上传</a-button>
    </a-upload>
    <div class="look"
         v-if="uploadImgList.length"
         @click="previewImg(uploadImgList[0])">查看附件</div>
    <a-modal :visible="previewVisible"
             :footer="null"
             @cancel="cancelImg">
      <img alt="预览附件"
           style="width: 100%"
           :src="previewImage" />
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent } from '@/common/export/table';
import { handlePreviewImg, handleUplodImg } from '@/common/setup/upload';
import { FileInfo, FileItem } from '@/common/setup/upload/interface';
import { PropType, watchEffect } from '@vue/runtime-core';
import { message } from 'ant-design-vue';

export default defineComponent({
    name: 'upload-img',
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        imgList: {
            type: Array as PropType<FileItem[]>,
            default: [],
        },
    },
    setup(props, context) {
        // 上传附件
        const { uploadUrl, uploadImgList, uploadChange, getUploadUrl, getUploadResultUrl } = handleUplodImg();
        // 预览附件
        const { previewVisible, previewImage, cancelImg, previewImg } = handlePreviewImg();
        function uploadAction(obj: FileInfo) {
            uploadChange(obj).then(() => {
                const arr = getUploadResultUrl();
                context.emit('upload', arr);
            });
        }
        watchEffect(() => {
            if (props.visible) {
                getUploadUrl();
                uploadImgList.value = props.imgList;
            }
        });
        // 文件上传校验
        const beforeUpload = (file:any) => {
          const isLt2M = file.size / 1024 / 1024 <= 1;
          if (!isLt2M) {
            message.error(file.name + "图片大小超出1M限制，请修改后重新上传", 0.8);
            return isLt2M;
          }
          return isLt2M;
        };
        return {
            beforeUpload,
            uploadUrl,
            uploadAction,
            uploadChange,
            uploadImgList,
            previewVisible,
            previewImage,
            cancelImg,
            previewImg,
        };
    },
});
</script>
<style lang="less">
.upload {
    .flex;
    flex-direction: column;
    .ant-upload-list {
        max-width: calc(100% - 80px);
    }
    .look {
        white-space: nowrap;
    }
}
</style
>;
