<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="traceComment.content"></textarea> -->
        </div>
        <div>
          <input ref="fileInput" autocomplete="off" 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>


import UpladFile from '../widget/UpladFile.js';

import Common from '../common/Common.js';

import { DownloadService } from 'pc-component-v3';

export default {
  components: {
    
    
    UpladFile,
    
    
    
  },
  data: function() {
    return {
      traceCommentId: '',
      traceComment: {},
      className: 'com.leanwo.prodog.trace.model.TraceComment',
      summernoteInitSuccess: false, // summernote初始化成功
      files: [],
      loading: false,
    };
  },
  mounted: function() {
    $('.input-tan').focus(function() {
      document.activeElement.blur();
    });
    this.initData();
  },
  methods: {
			
    /**
			 * 点击上传按钮事件
			 * @return {[type]} [description]
			 */
    clickButton: function() {
      $(this.$refs.fileInput).click();
    },

    /**
			 * 初始化数据
			 * @author GuoZhiBo 20171201
			 */
    initData: function() {
      var _self = this;
      _self.traceCommentId = Number(this.$route.params.traceCommentId);
      if (_self.traceCommentId != null && _self.traceCommentId != '') {
        _self.uniqueById(_self.traceCommentId).then(successData => {
          _self.traceComment = successData;
          if(successData.attachments != null && successData.attachments != ''){
            _self.files=(successData.attachments.split(','));
          }
          $('#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);
              },
            },
          });
          if (_self.traceComment != null) {
            $('#summernote').summernote('code', _self.traceComment.content);
          }
          _self.summernoteInitSuccess = true;
        }, errorData => {
          Common.processException(errorData);
        });
      }

    },

    /**
			 * 查询Trace
			 */
    uniqueById: function(traceCommentId) {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: Common.getApiURL('TraceCommentResource/uniqueById'),
          type: 'get',
          dataType: 'json',
          contentType: 'application/json',
          data: {
            'traceCommentId': traceCommentId,
          },
          beforeSend: function(request) {
            Common.addTokenToRequest(request);
          },
          success: function(data) {
            resolve(data);
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            reject(XMLHttpRequest);
          },
        });
      });
    },

    //----------文件------------
    /**
			 * 删除文件
			 * @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;
      _self.showUploadDiv = false;
      if (selectedFile == undefined) {
        return;
      }
      if (selectedFile.size != undefined && selectedFile.size != null) {
        if ((selectedFile.size / 1024) <= (1024 * 4)) {
          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('提示', '文件大小不能超过4M！');
        }
      } else {
        Notify.error('提示', '上传的文件为空！');
      }
    },

    /**
			 * 获取文件地址
			 * @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: 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', _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 20180302
			 */
    photograph: function() {
      var _self = this;
      _self.traceComment.content = $('#summernote').summernote('code');
      if (_self.traceComment.content != '' && _self.traceComment.content != null) {
        _self.traceComment.attachments = _self.files.join(',');
        _self.loading=true;
        $.ajax({
          url: Common.getApiURL('TraceCommentResource/updateTraceComment'),
          type: 'post',
          contentType: 'application/json',
          beforeSend: function(request) {
            Common.addTokenToRequest(request);
          },
          data: JSON.stringify(_self.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() {
      var _self = this;
      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>
