<template>
  <div style="width: 100%;">
    <div v-if="hasImage">
      <AntdAuthImage :auth-src="imageThumbnailSrc" :width="64" :height="64" />
      <a-button v-if="!readonly" size="small" danger @click="emitFieldValue(null)">
        {{ $t("lang.ImageWidget.delete") }}
      </a-button>
    </div>
    <div v-else>
      <a-upload
        v-model:file-list="imageFileList" :readonly="!readonly" :max-count="1" :before-upload="beforeUpload"
        :show-upload-list="false" @change="imageFileChange"
      >
        <a-button :readonly="!readonly" size="small" @click="showUploadImageModal">
          <upload-outlined />
          {{ $t("lang.ImageWidget.addPicture") }}
        </a-button>
      </a-upload>
    </div>
  </div>
</template>

<script>
import Common from '../../common/Common.js';

import ImageService from '../../resource/file/ImageService.js';
import FileService from '../../resource/file/FileService.js';


import Cropper from '../../widget/Cropper.vue';

import WebRtcImage from '../../widget/WebRtcImage.vue';
import WebSocketImage from '../../widget/WebSocketImage.vue';
import AntdAuthImage from '../../widget/AntdAuthImage.vue';
import { Notify, Uuid } from 'pc-component-v3';
import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
export default {

  components: {
    AntdAuthImage,
    WebSocketImage,
    WebRtcImage,
    Cropper,
    UploadOutlined,
  },


  props: {
    readonly: {
      type: Boolean,
      default: false,
    },
    className: {
      type: String,
      default: null,
    },
    uuid: {
      type: String,
      default: null,
    },
    fieldValue: {
      type: Object,
      default: function () {
        return null;
      },
    },
  },


  emits: ['valueChanged'],

  data: function () {
    this.Common = Common;
    return {
      show: false,
      index: 1,
      loading: false,
      addModal: false,
      imageFileList: [],
      imageSize: false,
      imageFile: null,
    };
  },
  computed: {
    /**
     * 计算图片地址
     * @return {String} 图片URL地址
     */
    imageThumbnailSrc: function () {
      var _self = this;
      if (
        this.fieldValue != undefined &&
        this.fieldValue.displayValue != undefined
      ) {
        var imageName = this.fieldValue.displayValue[0];
        return Common.getThumbnailImageSrc(_self.className, imageName);
      } else {
        return '';
      }
    },

    /**
     * 判断是否有图片
     * @return {Boolean} 是否有图片
     */
    hasImage: function () {
      if (
        this.fieldValue != undefined &&
        this.fieldValue.displayValue != undefined &&
        this.fieldValue.displayValue[0] != undefined &&
        this.fieldValue.displayValue[0].length > 0
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  mounted: function () {
    //判断浏览器是否支持FileReader接口
    if (typeof FileReader == 'undefined') {
      Notify.error(this.$t('lang.Notify.prompt'), this.$t('lang.ImageWidget.describe1'), false);
    }
  },

  methods: {
    beforeUpload: function (file) {
      this.imageSize = file.size > 5 * 1024 * 1024;
      this.imageFile = file;
      return false;
    },

    imageFileChange: function (file) {
      if (this.imageSize) {
        message.warning('图片大小超过限制，最大5M');
        return;
      }
      this.fileUpload(this.imageFile);
    },

    /**
     * 上传图片
     */
    uploadImage: function (dataURL) {
      var _self = this;

      var blobImg = FileService.dataURLToPngBlob(dataURL);
      var nameImg = new Date().getTime() + '.png';

      var formData = new FormData();
      formData.append('className', this.className);
      formData.append('uploadImage', blobImg, nameImg);

      this.loading = true;
      ImageService.uploadImage(formData).then(
        data => {
          _self.loading = false;
          _self.addModal = false;

          console.log(data);

          if (data.errorCode == 0) {
            if (data.datas != null && data.datas.length > 0) {
              message.success(_self.$t('lang.ImageWidget.describe2'));
              _self.emitFieldValue(data.datas[0]);
            }
          } else {
            message.warning(data.errorMessage);
          }



        },
        errorData => {
          _self.loading = false;
        },
      );
    },
    /**
     * 上传图片
     *  不裁剪压缩
     * @param {Object} imageSrcs
     * @author GuoZhiBo 20210520
     */
    fileUpload: function (selectedFile) {
      var _self = this;
      var formData = new FormData();
      formData.append('uploadImage', selectedFile);
      formData.append('className', _self.className);
      this.loading = true;
      ImageService.uploadImage(formData).then(
        data => {
          _self.loading = false;
          _self.addModal = false;

          console.log(data);

          if (data.errorCode == 0) {
            if (data.datas != null && data.datas.length > 0) {
              // Notify.success(_self.$t('lang.Notify.prompt'), _self.$t('lang.ImageWidget.describe2'), 1500);
              message.success(_self.$t('lang.ImageWidget.describe3'));
              _self.emitFieldValue(data.datas[0]);
            }
          } else {
            message.warning(data.errorMessage);
          }
        },
        errorData => {
          _self.loading = false;
        },
      );
    },

    /**
     * 触发FieldValue发生改变
     * @param {String} imageName 添加的图片名称
     */
    emitFieldValue: function (imageName) {
      var newFieldValue = {
        displayValue: [],
        fieldType: 'String',
      };
      if (imageName != null) {
        newFieldValue.displayValue[0] = imageName;
      }
      this.index = 1;
      this.$emit('valueChanged', newFieldValue);
    },

    /**
     * 显示上传图片的模态框
     */
    showUploadImageModal: function () {
      this.addModal = true;
    },
  },
};
</script>

<style scoped>
.input-group {
  width: 100%;
}

img {
  max-width: 100%;
}

/* Override Cropper's styles */
.cropper-view-box,
.cropper-face {
  border-radius: 50%;
}

.finish_room {
  width: 400px;
  height: auto;
}

.finish_room2 {
  width: 100%;
  height: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  align-items: center;
}

.finish_room2 .room_img {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  position: relative;
  overflow: hidden;
}

.finish_room2 .room_img img {
  width: 100%;
  height: 100%;
}

.finish_room2>.room_img span {
  position: absolute;
  width: auto;
  height: auto;
  right: 5px;
  bottom: 3px;
}

.room_add_img {
  width: 148px;
  height: 98px;
  border: 1px solid #e1e1e1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  position: relative;
}

.room_add_img>span:nth-child(1) {
  margin-top: 20px;
  width: 40px;
  height: 40px;
  overflow: hidden;
}

.room_add_img>span:nth-child(2) {
  margin-bottom: 10px;
}

.room_add_img input {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 99999;
  opacity: 0;
}
</style>
