<!-- 上传单个图片组件 只适用于单个图片上传 -->
<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action=""
      accept="image/*"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :show-file-list="false"
      :disabled="readonly"
    >
      <img
        v-if="fileUrl"
        :src="fileUrl"
        class="avatar"
      >
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
      ></i>
      <div
        slot="tip"
        class="el-upload__tip"
        v-if="tip && !readonly"
      >{{tip}}</div>
    </el-upload>
  </div>
</template>
<script>
import { uploadImg } from './api'
export default {
  name: 'UploadImage',
  props: {
    /**
     * 是否禁用
     */
    readonly: {
      type: Boolean,
      default: false,
    },
    /**
     * 文件Key
     */
    fileKey: {
      type: String,
      default: '',
    },
    /**
     * 文件Url
     */
    fileUrl: {
      type: String,
      default: '',
    },
    /**
     * 文件名称
     */
    // fileName: {
    //   type: String,
    //   default: '',
    // },
    tip: {
      type: String,
      default: '图片建议宽720px高度自定义，且不超过5M',
    },
    maxSize: {
      type: Number,
      default: 5,
    }
  },
  data() {
    return {
    };
  },
  methods: {
    /**
     * 上传
     */
    async handleUpload(event) {
      if (event && event.file) {
        let { rows } = await uploadImg(event.file);
        this.$emit('update:fileKey', rows[0].key);
        this.$emit('update:fileUrl', rows[0].url);
        this.$emit('update:fileName', rows[0].originalName);
        this.$emit('PhotoChange', rows.data.rows[0]);
        this.$message.success('上传成功');
      }
    },
    /**
     * 限制用户上传的图片格式和大小。
     */
    beforeUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < this.maxSize;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      // return isJPG && isLt2M;
      return isLt2M
    }
  }
}
</script>
<style lang="scss" scoped>
  .avatar-uploader {
    display: flex;
    .el-upload__tip {
      margin-left: 10px;
      font-size: 12px;
      color: $color-999999;
      margin-top: unset;
    }
  }
  .avatar-uploader .el-upload {
    background: #F4F4F4;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: $green;
  }
  .avatar-uploader-icon {
    font-size: 16px;
    font-weight: 600;
    color: $color-999999;
    width: 34px;
    height: 34px;
    line-height: 34px;
    text-align: center;
  }
  .avatar {
    width: 34px;
    height: 34px;
    display: block;
  }
</style>