<template>
  <div>
    <div class="img-view" v-if="dialogImageUrl">
      <img :src="dialogImageUrl" alt="" srcset="" />
    </div>
    <div class="placeholder-box" v-else>
      <img src="~@/assets/upload-placeholder.svg" alt="" />
    </div>
    <div class="btn-box">
      <el-upload
        class="avatar-div"
        action="#"
        accept="image/png,image/jpeg,image/jpg"
        :show-file-list="false"
        ref="uploadRef"
        :on-exceed="handleExceed"
        :limit="1"
        :http-request="handlSuccess"
        :multiple="false"
      >
        <el-button type="text">上传{{ assetName }}图片</el-button>
      </el-upload>
      <el-button type="text" @click="clearImg">清除图片</el-button>
    </div>
  </div>
</template>

<script>
  import { uploadFile, removeFile } from '@/api/system/file/index.js';
  import { getImageUrl } from '@/utils/file';
  export default {
    props: {
      assetName: {
        type: String,
        default: '设备'
      },
      value: {
        type: Object,
        default: () => []
      },
      // 所属模块
      module: {
        type: String,
        default: 'main'
      }
    },
    data () {
      return {};
    },
    computed: {
      dialogImageUrl () {
        return this.value?.storePath && getImageUrl(this.value.storePath);
      }
    },
    methods: {
      // 清空已上传的文件列表
      clearUploadFiles () {},
      //图片添加
      async handlSuccess (params) {
        let res = await uploadFile({
          multiPartFile: params.file,
          module: this.module
        });
        if (res?.data) {
          this.$emit('input', res.data);
        }
      },
      async clearImg () {
        // await removeFile({ fileId: this.value.id });
        this.$emit('input', {});
        this.$refs.uploadRef.clearFiles();
      },
      // 限制上传的数量
      handleExceed (files, fileList) {
        this.$message.warning(`最多允许上传一张图片！`);
      }
    }
  };
</script>
<style lang="scss" scoped>
  .img-view {
    width: 280px;
    height: 342px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(215, 215, 215, 1);
    img {
      max-width: 100%;
    }
  }
  .placeholder-box {
    width: 280px;
    height: 342px;
    text-align: center;

    background-color: rgba(242, 242, 242, 1);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(215, 215, 215, 1);
    padding-top: 60px;
    img {
      width: 158px;
      height: 158px;
    }
  }

  .btn-box {
    display: flex;
    justify-content: space-around;
  }
</style>
