<template>
  <div>
    <div>
      <input
        ref="fileInput"
        type="file"
        class="form-control file-input"
        @change="onFileChanges"
      />
      <label for="attachment">
        <a role="button" class="btn btn-primary btn-sm" @click="clickButton">
          <i class="fa fa-upload" />
          &nbsp; 上传附件
        </a>
      </label>
    </div>

    <div v-if="attachmentList != undefined && attachmentList.length > 0">
      <ul class="list-group">
        <template v-for="attachment in attachmentList" :key="attachment.id">
          <li class="list-group-item">
            <span
              class="badge"
              @click="deleteByTraceAttachmentId(attachment.id)"
            >删除</span>
            <span class="badge" @click="download(attachment)">下载</span>
            {{ attachment.attachment }}
          </li>
        </template>
      </ul>
    </div>
    <Loading v-if="loading" />
  </div>
</template>

<script>
var Common = require('../common/Common.js');
var Notify = require('pc-component-v3').default.Notify;
var DownloadService = require('pc-component-v3').default.DownloadService;
var Loading = require('pc-component-v3').default.Loading;

export default {
  components: {
    Loading,
    DownloadService,
  },
  // props: ['traceId'],
  props: {
    traceId: {
      type: String,
      default: null,
    },
  },
  data: function () {
    return {
      className: 'com.leanwo.prodog.model.trace.TraceAttachment',
      attachmentList: [],
      traceConfigDto: {},
      loading: false,
    };
  },

  watch: {
    traceId: function (curVal, oldVal) {
      if (curVal != undefined) {
        this.listTraceAttachmentByTraceId();
      }
    },
  },

  mounted: function () {
    if (this.traceId != undefined) {
      this.listTraceAttachmentByTraceId();
    }
    this.getTraceConfig();
  },
  methods: {
    /**
     * 下载文件
     * @param  {String} fileName 文件名
     * @return {void}
     */
    download: function (item) {
      var _self = this;
      DownloadService.fileDownload(_self.className, item.attachment);
    },

    /**
     * 删除任务附件
     */
    deleteByTraceAttachmentId: function (traceAttachementId) {
      var _self = this;
      $.ajax({
        url: Common.getApiURL(
          'TraceAttachmentResource/deleteByTraceAttachmentId',
        ),
        type: 'get',
        dataType: 'json',
        data: {
          id: traceAttachementId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data == false) {
            Notify.error(
              '提示',
              '您没有权限删除附件，只有任务发起人和附件上传人有权限删除附件！',
            );
            _self.listTraceAttachmentByTraceId();
          } else {
            _self.listTraceAttachmentByTraceId();
          }
        },
      });
    },

    /* 选择文件发生改变
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
    onFileChanges: 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 size = undefined;
      if (
        _self.traceConfigDto.traceAttachmentSize != undefined &&
        _self.traceConfigDto.traceAttachmentSize != null
      ) {
        size = _self.traceConfigDto.traceAttachmentSize;
      }
      //当系统没有配置附件大小时默认8m
      if (size == undefined) {
        size = 8;
      }
      if (selectedFile.size / 1024 <= 1024 * size) {
        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;
            if (data != 'error') {
              var fileName = data.substring(data.indexOf(':') + 1);
              _self.uploadTraceAttachment(fileName);
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading=false;
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      } else {
        Notify.error(
          '提示',
          '文件大小不能超过' + size + 'M，可在任务配置功能中配置！',
        );
      }
    },

    /**
     * 获取任务管理配置
     */
    getTraceConfig: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceConfigResource/queryTraceConfigDto'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },

        success: function (data) {
          _self.traceConfigDto = data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 查询当前追踪单下所有的附件
     */
    listTraceAttachmentByTraceId: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceAttachmentResource/listByTraceId'),
        type: 'get',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: {
          traceId: _self.traceId,
        },
        success: function (data) {
          console.log(data);
          _self.attachmentList = data;
        },
      });
    },

    /**
     * 上传附件
     */
    uploadTraceAttachment: function (fileName) {
      var _self = this;
      var traceAttachement = {
        traceId: _self.traceId,
        attachment: fileName,
      };
      $.ajax({
        url: Common.getApiURL('TraceAttachmentResource/save'),
        type: 'post',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: JSON.stringify(traceAttachement),
        success: function (data) {
          _self.listTraceAttachmentByTraceId();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
          Notify.error('提示', '上传失败！');
        },
      });
    },

    /**
     * 点击上传按钮事件
     * @return {[type]} [description]
     */
    clickButton: function () {
      $(this.$refs.fileInput).click();
    },
  },
};
</script>

<style scoped>
.badge {
  cursor: pointer;
  background-color: #428bca;
  color: white;
}
</style>

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