<template>
  <div>
    <div>
      <Navbar title="创建评论" :is-go-back="true" />
      <div>
        <div class="form-group">
          <label for="exampleInputEmail2">评论内容</label>
          <div id="summernote" />
          <!-- <textarea style="width: 100%;"
                              id="hcqk"
                              class="form-control"
                              rows="5"
                              v-model="content"></textarea> -->
        </div>
        <div>
          <input autocomplete="off"
            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 style="margin-top: 10px">
          <ul class="list-group">
            <li v-for="item in files" :key="item" class="list-group-item">
              <span class="badge" @click="download(item)">下载</span>
              <span class="badge" @click="removeFile(item)">删除</span>
              {{ item }}
            </li>
          </ul>
        </div>
        <div>
          <div style="margin-top: 10px">
            <button type="text" class="btn btn-default" @click="photograph">
              确认
            </button>
            <button type="text" class="btn btn-default" @click="back">
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
    <Loading v-if="loading" />
  </div>
</template>
<script>
var Uuid = require('pc-component-v3').default.Uuid;
var Loading = require('pc-component-v3').default.Loading;
var UpladFile = require('../widget/UpladFile.js');
var Notify = require('pc-component-v3').default.Notify;
var Common = require('../common/Common.js');
var Navbar = require('pc-component-v3').default.Navbar;
var DownloadService = require('pc-component-v3').default.DownloadService;

export default {
  components: {
    Uuid,
    Loading,
    UpladFile,
    Notify,
    Common,
    Navbar,
  },
  data: function () {
    return {
      traceId: null,
      content: '',
      images: [],
      className: 'com.leanwo.prodog.trace.model.TraceComment',
      files: [],
      traceConfigDto: {},
      summernoteInitSuccess: false, // summernote初始化成功
      loading: false,
    };
  },

  mounted: function () {
    var _self = this;
    $('.input-tan').focus(function () {
      document.activeElement.blur();
    });
    this.initData();
    this.getTraceConfig();
    $('#summernote').summernote({
      toolbar: [
        [
          'insert',
          [
            'link',
            'picture',
            'video',
            'audio',
            'hr',
            'table', //插件
            'fontname',
            'fontsize',
            'color',
            'bold',
            'italic',
            'underline',
            'strikethrough',
            'clear', //字体样式
            'style',
            'ol',
            'ul',
            'paragraph',
            'height', //段落样式
            'fullscreen',
            'codeview',
            'undo',
            'redo',
            'help', //Misc
          ],
        ],
      ],
      height: 400,
      minHeight: 300,
      maxHeight: 500,
      focus: true,
      lang: 'zh-CN',
      callbacks: {
        onImageUpload: function (files, editor, $editable) {
          _self.sendFile(files[0], editor, $editable);
        },
      },
    });
    _self.summernoteInitSuccess = true;
  },
  beforeUnmount: function () {
    if (this.summernoteInitSuccess == true) {
      $('#summernote').summernote('destroy');
    }
  },
  methods: {
    /**
     * 点击上传按钮事件
     * @return {[type]} [description]
     */
    clickButton: function () {
      $(this.$refs.fileInput).click();
    },
    /**
     * 初始化数据
     * @author GuoZhiBo 20171201
     */
    initData: function () {
      var _self = this;
      this.traceId = Number(this.$route.params.traceId);
    },
    /**
     * 监听文件改变事件
     * @author GuoZhiBo 20171201
     */
    onFileChange(e) {
      var _self = this;
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      _self.uploadImage(files[0]);
    },
    /**
     * 上传图片
     * @author GuoZhiBo 20171201
     */
    uploadImage: function (selectedFile) {
      var _self = this;
      if (selectedFile == undefined) {
        return;
      }
      if (!/image\/\w+/.test(selectedFile.type)) {
        Notify.error('提示', '请确保文件为图像类型！');
        return;
      }
      UpladFile.photoCompress(
        selectedFile,
        {
          quality: 0.2,
        },
        function (base64Codes) {
          var bl = UpladFile.convertBase64UrlToBlob(base64Codes);
          var rst = new FormData();
          rst.append('images', bl, 'file_' + Date.parse(new Date()) + '.jpg');
          rst.append('className', 'com.leanwo.prodog.trace.model.TraceComment');
          _self.loading=true;
          $.ajax({
            url: Common.getApiURL('file/imageUpload'),
            type: 'post',
            beforeSend: function (request) {
              Common.addTokenToRequest(request);
            },
            data: rst,
            contentType: false,
            processData: false,
            success: function (data) {
              _self.loading=false;
              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);
            },
          });
          return rst.file;
        },
      );
    },
    /**
     * 添加图片
     * @author GuoZhiBo 20171201
     */
    addImg: function (imageName) {
      var _self = this;
      _self.images.push(imageName);
    },
    /**
     * 获取图片地址
     * @param  {String} item 图片名称
     * @return {String}      图片URL地址
     */
    getImageSrc: function (item) {
      var _self = this;
      if (item != undefined && item != null) {
        return Common.getResourceUrl(
          'image',
          'com.leanwo.prodog.trace.model.TraceComment',
          item,
        );
      } else {
        return '';
      }
    },
    /**
     * 获取图片路径供外部调用
     * @return {Array} 图片地址
     */
    getImages: function () {
      return this.images;
    },
    /**
     * 删除图片
     *@author GuoZhiBo 20171201
     */
    deleteImg(index) {
      var _self = this;
      _self.images.splice(index, 1);
    },
    //----------文件------------
    /**
     * 删除文件
     * @param  {String} item 文件Name
     */
    removeFile: function (index) {
      var _self = this;
      _self.files.splice(index, 1);
    },
    /**
     * 选择文件发生改变
     * @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.commentAttachmentSize != undefined &&
        _self.traceConfigDto.commentAttachmentSize != null
      ) {
        size = _self.traceConfigDto.commentAttachmentSize;
      }
      //当系统没有配置附件大小时默认8m
      if (size == undefined) {
        size = 8;
      }
      if (selectedFile.size != undefined && selectedFile.size != null) {
        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.files.push(fileName);
              }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              _self.loading=false;
              Common.processException(XMLHttpRequest, textStatus, errorThrown);
            },
          });
        } else {
          Notify.error(
            '提示',
            '文件大小不能超过' + size + 'M，可在任务配置功能中配置！',
          );
        }
      } else {
        Notify.error('提示', '上传的文件为空！');
      }
    },
    /**
     * 获取任务管理配置
     */
    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);
        },
      });
    },
    /**
     * 获取文件地址
     * @param  {String} item 图片名称
     * @return {String}      图片URL地址
     */
    getFileSrc: function (item) {
      var _self = this;
      if (item != undefined && item != null) {
        return Common.getResourceUrl('file', _self.className, item);
      } else {
        return '';
      }
    },

    /**
     * 下载文件
     * @param  {String} fileName 文件名
     * @return {void}
     */
    download: function (fileName) {
      var _self = this;
      DownloadService.fileDownload(_self.className, fileName);
    },

    //内容图片上传
    sendFile: function (file, editor, $editable) {
      var _self = this;
      UpladFile.photoCompress(
        file,
        {
          quality: 1,
        },
        function (base64Codes) {
          var bl = UpladFile.convertBase64UrlToBlob(base64Codes);
          var rst = new FormData();
          rst.append('images', bl, 'file_' + Date.parse(new Date()) + '.jpg');
          rst.append('className', _self.className);
          $.ajax({
            url: Common.getApiURL('file/imageUpload'),
            type: 'post',
            data: rst,
            contentType: false,
            processData: false,
            beforeSend: function (request) {
              Common.addTokenToRequest(request);
            },
            success: function (data) {
              if (data != 'error') {
                var imageName = data.substring(data.indexOf(':') + 1);
                $('#summernote').summernote(
                  'insertImage',
                  Common.getResourceUrl('image', _self.className, imageName),
                  'image name',
                );
              }
            },
            error: function () {
              Notify.error('提示', '上传失败！');
              return;
            },
          });
          return rst.file;
        },
      );
    },

    /**
     * 保存评论表数据
     * @author GuoZhiBo 20171201
     */
    photograph: function () {
      var _self = this;
      _self.content = $('#summernote').summernote('code');
      if (_self.content != '' && _self.content != null) {
        var traceComment = {
          traceId: _self.traceId,
          content: _self.content,
          attachments: _self.files.join(','),
        };
        _self.loading=true;
        $.ajax({
          url: Common.getApiURL('TraceCommentResource/saveTraceComment'),
          type: 'post',
          contentType: 'application/json',
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          data: JSON.stringify(traceComment),
          success: function (data) {
            _self.loading=false;
            _self.back();
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading=false;
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      } else {
        Notify.error('提示', '请填写评论内容！');
      }
    },

    back: function () {
      history.back();
    },
  },
};
</script>
<style scoped>
.mui-divs3 {
  margin-top: 10px;
}
.file-input {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}
.badge {
  cursor: pointer;
  background-color: #428bca;
  color: white;
}
</style>