<template>
  <div>
    <span v-for="(item, index) in newFieldValue.displayValue" :key="index">
      <a
        role="button"
        class="btn btn-default btn-left"
        :title="$t('lang.FileListWidget.download')"
        @click="download(item)"
      >
        {{ item }}
      </a>
      <a
        role="button"
        class="btn btn-success"
        :class="{ 'btn-middle': readonly != true , 'btn-right': readonly == true }"
        :title="$t('lang.FileListWidget.download')"
        @click="download(item)"
      >
        <i class="fa fa-download" />
      </a>
      <a
        v-if="!readonly"
        role="button"
        class="btn btn-danger btn-right"
        :title="$t('lang.FileListWidget.delete')"
        @click="removeFile(item)"
      >
        <i class="fa fa-trash-o" />
      </a>
    </span>
    <span>
      <UploadButton v-if="!readonly" class="m-btn" @change="onFileChange" />
    </span>
    <Loading v-if="loading" />
  </div>
</template>
<script>


import Common from '../../common/Common.js';
import UploadButton from '../../widget/UploadButton.vue';
import { notificationError } from '../../common/notification.js';

export default {

  components: {
    UploadButton,
  },

  
  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 () {
    return {
      newFieldValue: {
        displayValue: [],
        displayType: 'String',
      },
      loading: false,
    };
  },
  watch: {
    fieldValue: {
      deep: true,
      handler(curVal, oldVal) {
        var displayValue = this.fieldValue.displayValue;
        if (displayValue != undefined && displayValue.length > 0) {
          if(displayValue[0] == null || displayValue[0] == ''){
            this.newFieldValue.displayValue = [];
          }else{
            this.newFieldValue.displayValue = displayValue[0].split(',');
          }
        }else{
          this.newFieldValue.displayValue = [];
        }
      },
    },
  },

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

  methods: {
    fileProperty: function (item) {
      return {
        fileName: item,
      };
    },
    /**
     * 删除文件
     * @param  {String} item 文件Name
     */
    removeFile: function (item) {
      var _self = this;
      var index = _self.newFieldValue.displayValue.indexOf(item);
      if (index > -1) {
        _self.newFieldValue.displayValue.splice(index, 1);
      }
      var files = _self.newFieldValue.displayValue.join(',');
      _self.fieldValue.displayValue[0] = files;
      this.$emit('valueChanged', _self.fieldValue);
    },

    /**
     * 选择文件发生改变
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
    onFileChange: function (e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) {
        return;
      }
      this.uploadFile(files[0]);
    },

    /**
     * 上传文件
     * @param  {File} selectedFile 选择的文件
     */
    uploadFile: function (selectedFile) {
      var _self = this;
      if (selectedFile == undefined) {
        return;
      }

      var formData = new FormData();
      formData.append('files', selectedFile);
      formData.append('className', _self.className);
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('file/classFileUpload'),
        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) {
            var fileNames = data.datas;
            _self.addFiles(fileNames);
          }else{
            notificationError(data.errorMessage, '文件上传失败');
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 添加文件
     * @param {String} imageName 添加的文件名称
     */
    addFiles: function (fileNames) {
      var _self = this;
      if (_self.newFieldValue.displayValue == undefined) {
        _self.newFieldValue.displayValue = new Array();
      }
      if(fileNames != null){
        fileNames.forEach(element => {
          _self.newFieldValue.displayValue.push(element);
        });
      }
      
      var files = _self.newFieldValue.displayValue.join(',');
      _self.fieldValue.displayValue[0] = files;
      this.$emit('valueChanged', _self.fieldValue);
    },

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

    /**
     * 下载文件
     * @param  {String} fileName 文件名
     * @return {void}
     */
    download: function (fileName) {
      var _self = this;
      var className = _self.className;
      var downloadUrl =
        Common.getHostPageBaseURL() +
        '/Files/0/Files/' +
        className +
        '/' +
        fileName;
      window.open(downloadUrl);
    },
  },
};
</script>

<style scoped>
.m-btn {
  margin-right: 5px;
  display: inline;
}

.btn-left{
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}


.btn-middle{
  border-radius: 0;
}

.btn-right{
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-right: 5px;
}
</style>