<template>
  <div>
    <div :class="{'m-row' : hasImage}">
      <div class="row">
        <span class="col-md-12">
          <div
            v-for="item,index in newFieldValue.displayValue"
            :key="index"
            class="room_img"
          >
            <AuthImage
              class="m-small-img"
              :auth-src="getImageSrc(item)"
              @click="previewImg(getImageSrc(item))"
            />
            <span
              v-if="!readonly"
              class="glyphicon glyphicon-trash"
              @click="removeImage(item)"
            />
          </div>
          <div class="clearfix" />
        </span>
      </div>
    </div>

    <div id="app">
      <div>
        <input
          id="file"
          autocomplete="off"
          type="file"
          class="form-control"
          style="width: 100%;"
          :readonly="!readonly"
          multiple
          @change="onFileChange"
        />
      </div>
      <!-- <button class="btn btn-success" @click="toggleShow">选择图片</button>
			<my-upload field="img"
        v-model="show"
				:width="1024"
				:height="768"
				img-format="png"
				:className="className" 
				@addImg="addImg"
				></my-upload> -->
    </div>

    <Modal
      v-model:show="modal"
      :large="true"
    >
      <div class="modal-img-box">
        <AuthImage
          class="m-img"
          :auth-src="modalImgSrc"
        />
      </div>
      <template #header>图片查看器</template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>

<script>


import AuthImage from '../../widget/AuthImage.vue';
import Common from '../../common/Common.js';
import { Notify, Uuid } from 'pc-component-v3';

export default {

  components: {
    AuthImage,
  },

  
  
  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',
      },
      show: false,
      modalImgSrc: null,
      loading: false,
      modal: false,
    };
  },

  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(',');
    }
  },

  methods: {
    /**
         * 预览图片
         */
    previewImg: function (imgSrc) {
      this.modalImgSrc = imgSrc;
      this.modal = true;
    },
    /**
         * 删除图片
         * @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, element) {
      var _self = this;
      if (selectedFile == undefined) {
        return;
      }
      if (!/image\/\w+/.test(selectedFile.type)) {
        alert('请确保文件为图像类型');
        return;
      }

      if (selectedFile.size != null && selectedFile.size > 3000 * 1024) {
        Notify.error(_self.$t('lang.Notify.error'), _self.$t('lang.ImageListWidget.describe1'), true);
        element.value = '';
        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 != 'error') {
            var imageName = data.substring(data.indexOf(':') + 1);
            _self.addImg(imageName);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
         * 添加图片
         * @param {String} imageName 添加的图片名称
         */
    addImg: function (imageName) {
      var _self = this;
      if (_self.newFieldValue.displayValue == undefined) {
        _self.newFieldValue.displayValue = new Array();
      }
      _self.newFieldValue.displayValue.push(imageName);
      var images = _self.newFieldValue.displayValue.join(',');
      _self.fieldValue.displayValue[0] = images;
      this.$emit('valueChanged', _self.fieldValue);
      _self.show = false;
    },
    /**
         * 获取图片地址
         * @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 '';
      }
    },
    toggleShow() {
      this.show = !this.show;
    },
  },
};
</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%;
}
</style>