<template>
  <div>

    <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
      :before-upload="beforeUpload" @change="handleChange">
      <img class="img-preview" v-if="showUrl" :src="showUrl" alt="avatar" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">
          上传
        </div>
      </div>
    </a-upload> 
  </div>
</template>

<script>

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  name: 'MkFormUploader',
  props: {
    value: String
  },
  data() {
    return {
      loading: false,
      showUrl: ""
    }
  },
  created() {
    this.showUrl = this.$mk.getPreviewSrc(this.value);

  },
  watch: {
    value() {
      this.showUrl = this.$mk.getPreviewSrc(this.value);
    }

  },
  methods: {
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl;
          this.loading = false;
        });
      }
    },

    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$mk.error("只能上传图片文件")

        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$mk.error(" 文件不能超过10MB")
        return false;
      }

      var suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      this.$mk.uploadFile(file, suffix, (url) => {

        this.showUrl = this.$mk.getPreviewSrc(url);


        this.$emit('input', url);

      });


      return false;
    }
  }
}
</script>

<style>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.img-preview {
  width: 128px;
  height: 128px;
}
</style>