<template>
  <div style="width: 100%">
    <a-upload
      v-model:file-list="fileList"
      :before-upload="beforeUpload"
      list-type="picture-card"
      @preview="previewImg"
      @change="fileChange"
      @remove="handleRemove"
    >
      <div>
        <plus-outlined />
        <div style="margin-top: 8px">
          {{ $t("lang.ImageWidget.addPicture") }}
        </div>
      </div>
    </a-upload>
    <a-modal
      :open="modal"
      :title="previewTitle"
      :footer="null"
      @cancel="modal = false"
    >
      <img
        alt="预览图片"
        style="width: 100%"
        :src="modalImgSrc"
        @onload="onload"
      />
      <!-- <AntdAuthImage :width="'100%'" :auth-src="modalImgSrc" :is-preview="false" /> -->
    </a-modal>
  </div>
</template>

<script>
import Common from '../../common/Common.js';
import { notificationError } from '../../common/notification.js';
import { Notify, Uuid } from 'pc-component-v3';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import AntdAuthImage from '../../widget/AntdAuthImage.vue';
export default {
  components: {
    PlusOutlined,
    DeleteOutlined,
    AntdAuthImage,
  },

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

  emits: ['valueChanged'],

  data: function () {
    this.Common = Common;
    return {
      newFieldValue: {
        displayValue: [],
        displayType: 'String',
      },
      modalImgSrc: null,
      loading: false,
      modal: false,
      fileList: [],
      isLimit3M: false,
      fileName: null,
      previewTitle: '',
    };
  },

  computed: {
    /**
     * 判断是否有图片
     * @return {Boolean} 是否有图片
     */
    hasImage: function () {
      if (
        this.newFieldValue != undefined &&
        this.newFieldValue.displayValue != undefined &&
        this.newFieldValue.displayValue[0] != undefined &&
        this.newFieldValue.displayValue[0].length > 0
      ) {
        return true;
      } else {
        return false;
      }
    },
  },

  mounted: function () {
    var _self = this;
    var displayValue = _self.fieldValue.displayValue;
    if (displayValue != undefined && displayValue.length > 0) {
      _self.newFieldValue.displayValue = displayValue[0].split(',');
    }
    _self.newFieldValue.displayValue.forEach(item => {
      _self.getObjectUrl(_self.getThumbnailImageSrc(item), 'thumbnail', item);
    });
  },

  methods: {
    // 手动上传
    beforeUpload: function (file) {
      return false;
    },

    // 选择图片发生改变
    fileChange: function (info) {
      this.handleRemove(info.file);
      this.uploadImage(info.file);
    },

    // 删除图片前先清除fileList中的图片
    handleRemove: function (file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.removeImage(file.name);
    },

    // 预览图片
    previewImg: async function (file) {
      this.modal = true;
      this.previewTitle = this.$t('lang.ImageWidget.preview');
      this.getObjectUrl(this.getImageSrc(file.name), 'preview');
    },

    // 将地址转为blob
    getObjectUrl: function (url, type, name) {
      const _self = this;
      fetch(url, {
        method: 'GET',
        headers: {
          token: localStorage.getItem('#token'),
        },
      })
        .then(res => res.blob())
        .then(blob => {
          const objectURL = URL.createObjectURL(blob);
          if (type == 'preview') {
            _self.modalImgSrc = objectURL;
          } else {
            this.fileList.push({
              uid: Uuid.createUUID(),
              name: name,
              url: objectURL,
            });
          }
        })
        .catch(err => {
          console.error(err);
        });
    },
    onload() {
      URL.revokeObjectURL(this.modalImgSrc);
    },
    /**
     * 删除图片
     * @param  {String} item 图片Name
     */
    removeImage(item) {
      var _self = this;
      var index = _self.newFieldValue.displayValue.indexOf(item);
      if (index > -1) {
        _self.newFieldValue.displayValue.splice(index, 1);
      }
      var images = _self.newFieldValue.displayValue.join(',');
      _self.fieldValue.displayValue[0] = images;
      this.$emit('valueChanged', _self.fieldValue);
    },

    /**
     * 选择图片发生改变
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
    onFileChange(e) {
      const _self = this;
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      // 批量上传
      for (let i = 0; i < files.length; i++) {
        var reader = new FileReader();
        reader.onload = function (e) {
          _self.uploadImage(files[i], e.target.result);
        };
        reader.readAsDataURL(files[i]);
      }
    },

    /**
     * 上传图片
     * @param  {File} selectedFile 选择的文件
     */
    uploadImage: function (selectedFile) {
      var _self = this;
      if (selectedFile == undefined) {
        return;
      }
      if (!/image\/\w+/.test(selectedFile.type)) {
        alert('请确保文件为图像类型');
        _self.fileList.splice(-1, 1);
        return;
      }

      if (selectedFile.size != null && selectedFile.size > 3000 * 1024) {
        _self.fileList.splice(-1, 1);
        message.error(_self.$t('lang.ImageListWidget.describe1'));
        return;
      }

      var formData = new FormData();
      formData.append('images', selectedFile);
      formData.append('className', _self.className);
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('file/imageUpload'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: formData,
        contentType: false,
        processData: false,
        success: function (data) {
          _self.loading = false;
          console.log(data);
          if (data.errorCode == 0) {
            _self.addImgs(data.datas);
            _self.getObjectUrl(_self.getThumbnailImageSrc(data.datas[0]), 'thumbnail', data.datas[0]);
          } else {
            notificationError(data.errorMessage, '图片上传失败');
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 添加图片
     * @param {String} imageName 添加的图片名称
     */
    addImgs: function (imageNames) {
      var _self = this;
      if (_self.newFieldValue.displayValue == undefined) {
        _self.newFieldValue.displayValue = new Array();
      }

      if (imageNames != null) {
        imageNames.forEach(element => {
          _self.newFieldValue.displayValue.push(element);
        });
      }

      var images = _self.newFieldValue.displayValue.join(',');
      _self.fieldValue.displayValue[0] = images;
      this.$emit('valueChanged', _self.fieldValue);
    },

    /**
     * 获取图片地址
     * @param  {String} item 图片名称
     * @return {String}      图片URL地址
     */
    getImageSrc: function (item) {
      var _self = this;
      if (item != undefined && item != null) {
        return Common.getImageSrc(_self.className, item);
      } else {
        return '';
      }
    },

    /**
     * 获取图片缩略图地址
     * @param  {String} item 图片名称
     * @return {String}      图片缩略图URL地址
     */
    getThumbnailImageSrc: function (item) {
      var _self = this;
      if (item != undefined && item != null) {
        return Common.getThumbnailImageSrc(_self.className, item);
      } else {
        return '';
      }
    },
  },
};
</script>

<style scoped>
.inputfile {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.room_img {
  width: 150px;
  height: 100px;
  float: left;
  margin-right: 10px;
}

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

.room_img span {
  position: relative;
  right: -125px;
  top: -95px;
  font-size: 20px;
  color: #43a51e;
  cursor: pointer;
}

.label-btn {
  color: white;
  background-color: #006699;
  display: inline-block;
  padding: 5px 15px;
  border-radius: 5px;
}

.label-btn:hover {
  color: white;
  background-color: #003399;
  display: inline-block;
  padding: 5px 15px;
  border-radius: 5px;
  cursor: pointer;
}

.modal-img-box {
  width: 100%;
  text-align: center;
  overflow: auto;
}

.m-small-img {
  cursor: pointer;
}

.m-img {
  width: 100%;
}

:deep(.ant-upload-list-item-container) {
  width: 68px !important;
  height: 68px !important;
}

:deep(.ant-upload.ant-upload-select.ant-upload-select-picture-card) {
  width: 68px !important;
  height: 68px !important;
}
</style>