<template>
  <a-upload
    name="avatar"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <AntdAuthImage
      v-if="modelValue != null && modelValue.length > 0" :auth-src="getImageUrl(modelValue)"
      :is-preview="false" :width="128"
    />
    <!-- <img
      v-if="modelValue != null && modelValue.length > 0"
      :src="getImageUrl(modelValue)"
      class="preview-image"
      alt="avatar"
    /> -->
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">
        {{ $t("lang.imageUpload.upload") }}
      </div>
    </div>
  </a-upload>
</template>

<script>
import { getThumbnailSrc } from '../common/image-src.js';
import { requestFailed } from '../common/request-result.js';
import {notificationError} from '../common/notification.js';
import AntdAuthImage from './AntdAuthImage.vue';
import Common from '../common/Common.js';

export default {
  components:{
    AntdAuthImage,
  },
  props: {
    className: {
      type:String,
      default:()=>{
        return null;
      },
    },
    modelValue: {
      type:String,
      default:()=>{
        return null;
      },
    },
  },

  data() {
    return {
      loading: false,
      imagefile: null,
    };
  },

  computed: {
    /**
     * 获取图片预览的地址
     */
    getImageUrl: function(){
      return item => {
        if (item != undefined) {
          return getThumbnailSrc(this.className, item);
        } else {
          return '';
        }
      };
    },
  },

  mounted: function () {
  },

  methods: {
    imageUpload: function(formData){
      var requestUrl = 'file/imageUpload';
      return new Promise((resolve, reject) => {
        $.ajax({
          url: Common.getApiURL(requestUrl),
          type: 'post',
          contentType: false,
          processData: false,
          // dataType: 'text',
          data: formData,
          beforeSend: function(request) {
            Common.addTokenToRequest(request);
          },
          success: function(data) {
            resolve(data);
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            reject(XMLHttpRequest);
          },
        });
      });
    },
    handleChange() {
      var _self = this;
      if (this.imagefile != null) {
        var formData = new FormData();
        formData.append('images', this.imagefile);
        formData.append('className', this.className);
        _self.imageUpload(formData).then(res => {
          if (res.errorCode == 0) {
            if(res.datas != null && res.datas.length > 0){
              var imageName = res.datas[0];
              _self.$emit('update:modelValue', imageName);
            }
          } else {
            notificationError(res.errorMessage, '图片上传失败');
          }
        }).catch(err => {
          requestFailed(err);
        });
      }
    },

    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      this.imagefile = file;
      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;
}

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