<template>
  <div>
    <div>
      <Navbar
        title="编辑任务"
        :is-go-back="true"
      />
      <div v-if="traceDto != null">
        <div class="form-group">
          <label for="exampleInputEmail1">标题</label>
          <input
            id="exampleInputEmail1"
            v-model="traceDto.summary"
            type="text"
            class="form-control"
            placeholder="标题"
          />
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">内容</label>
          <div id="summernote" />
        </div>

        <div class="form-group">
          <label for="projectName">项目</label>
          <select
            id="projectName"
            v-model="traceDto.projectId"
            class="form-control"
            @change="changeProjectSelected()"
          >
            <option
              v-for="project in projectItemUserListProject"
              :key="project.id"
              :value="project.projectItemId"
            >
              {{ project.projectItemName }}
            </option>
          </select>
        </div>
        <AudioField
          :class-name="className"
          :src-array="srcArray"
          :is-readonly="'false'"
          @handle-stop="handelEndRecord"
          @delete-audio-src="deleteAudioSrc"
        />
        <div class="form-group">
          <label for="projectName">时间节点</label>
          <Treeselect
            ref="treeSelect"
            :multiple="false"
            :options="projectTaskDtos"
          />
        </div>
        <div class="form-group">
          <label for="receiveUserId">责任人</label>
          <select
            id="receiveUserId"
            v-model="traceDto.receiveUserId"
            class="form-control"
          >
            <option value="" />
            <option
              v-for="user in projectItemUserListUser"
              :key="user.userId"
              :value="user.userId"
            >
              {{ user.userName }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <label>完成时间</label>
          <DateWidget
            :date-value="formatDate(traceDto.planFinishedDate)"
            class="form-control"
            @on-value-change="planFinishedDateChanged"
          />
        </div>

        <button
          style="width:100%;background-color: #007aff;color: white"
          type="button"
          class="btn btn-blue search-button"
          @click="updateTrace()"
        >
          保存
        </button>
      </div>
    </div>
    <Loading v-if="loading" />
  </div>
</template>
<script>
import TraceResource from './TraceResource.js';
var Notify = require('pc-component-v3').default.Notify;
var Common = require('../common/Common.js');
var UpladFile = require('../widget/UpladFile.js');
import TraceCommon from './TraceCommon.js';
var DateWidget = require('pc-component-v3').default.Date;
var Navbar = require('pc-component-v3').default.Navbar;
var Loading = require('pc-component-v3').default.Loading;
import Treeselect from '../widget/TreeSelect.vue';
var AudioField = require('../widget/AudioField.vue').default;
export default {
  components: {
    Navbar,
    Loading,
    Common,
    Notify,
    UpladFile,
    DateWidget,
    Treeselect,
    AudioField,
  },
  data: function () {
    return {
      traceId: '',
      traceDto: {},
      className: 'com.leanwo.prodog.Trace',
      projectItemUserListUser: [],
      projectItemUserListProject: [],
      formatDate: TraceCommon.formatDate,
      summernoteInitSuccess: false, // summernote初始化成功
      projectTaskDtos: [],//项目任务时间点
      isflag: true,
      srcArray: [],
      loading: false,
    };
  },
  watch: {
    'traceDto.projectId': function (curVal, oldVal) {
      var _self = this;
      _self.queryProjectTaskDtoByProjectId();
      if (_self.isflag) {
        _self.$refs.treeSelect.setValue(undefined);
      } else {
        _self.$refs.treeSelect.setValue(_self.traceDto.projectTaskId);
      }
      _self.isflag = true;
    },
  },

  mounted: function () {
    var _self = this;
    this.initProject();
    this.initContext();
    this.isflag = false;
  },


  beforeUnmount: function () {
    if (this.summernoteInitSuccess == true) {
      $('#summernote').summernote('destroy');
    }
    //界面销毁时，修改插入连接的display属性
    $('.note-link-popover').removeAttr('style');
  },
  methods: {
    /**
         * 删除语音
         * @param {Object} index
         */
    deleteAudioSrc: function (index) {
      var _self = this;
      _self.srcArray.splice(index, 1);
      _self.traceDto.audioSrcs = JSON.stringify(_self.srcArray);
    },
    /**
         * 录音停止之后
         * @param {Object} param
         */
    handelEndRecord: function (param) {
      var _self = this;
      if (param.fileName != undefined) {
        _self.srcArray.push(param.fileName);
        _self.traceDto.audioSrcs = JSON.stringify(_self.srcArray);
      }
    },
    back: function () {
      history.back();
    },

    updateTrace: function () {
      var _self = this;
      _self.traceDto.detail = $('#summernote').summernote('code');
      _self.traceDto.projectTaskId = _self.$refs.treeSelect.getValue();
      if (_self.traceDto.summary != '' && _self.traceDto.summary != undefined) {
        _self.loading=true;
        $.ajax({
          url: Common.getApiURL('TraceResource/updateTrace'),
          type: 'post',
          contentType: 'application/json',
          data: JSON.stringify(_self.traceDto),
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          success: function (data) {
            Notify.success('提示', '修改成功！');
            _self.loading=false;
            _self.back();
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading=false;
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      } else {
        Notify.error('提示', '标题不能为空！');
      }
    },

    //图片上传  
    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);
              // 方法1: 直接插入图片，由于图片不能加载，导致导致插入失败。
              // $("#summernote").summernote('insertImage', Common.getResourceUrl("image", _self.className, imageName), 'image name');

              // 方法2：创建img节点，然后插入<img>节点，可以插入，但是图片没有显示，点击一下code，然后就显示了。
              // var node = document.createElement('img') // 创建节点，用于包裹视频，再加这一层是方便调视频样式
              // node.setAttribute("authSrc", Common.getResourceUrl("image", _self.className, imageName));
              // node.setAttribute("is", "auth-img");
              // $("#summernote").summernote('insertNode', node);

              // 方法3：重新给code赋值，此时丢失了鼠标焦点，此时不满足要求。
              // var get_code = $('#summernote').summernote('code');
              // $('#summernote').summernote('code', get_code);

              // 方法4：插入文本（尝试失败)
              //let imageText = "<img is='auth-img' authSrc='" + Common.getResourceUrl("image", _self.className, imageName) + "'/>";
              //$('#summernote').summernote('insertText', imageText);

              // 方法5: 插入div,div中嵌入img，测试OK
              //                          var node = document.createElement('div') // 创建节点，用于包裹视频，再加这一层是方便调视频样式
              //                          node.innerHTML = "<img is='auth-img' authSrc='" + Common.getResourceUrl("image", _self.className, imageName) + "' />";
              //                          $("#summernote").summernote('insertNode', node);
              $('#summernote').summernote('insertImage', Common.getResourceUrl('image', _self.className, imageName), 'image name');
            }
          },
          error: function () {
            Notify.error('提示', '上传失败！');
            return;
          },
        });
        return rst.file;
      });
    },

    /**
         * 初始化项目
         */
    initProject: function () {
      var _self = this;
      _self.projectItemUserListProject.splice(0, _self.projectItemUserListProject.length);
      $.ajax({
        url: Common.getApiURL('ProjectItemUserResource/listByUserId'),//通过用户Id查找有权操作的项目
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          for (var index = 0; index < data.length; index++) {
            _self.projectItemUserListProject[index] = data[index];
            // _self.$set(_self.projectItemUserListProject, index, data[index]);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },


    /**
         * 项目选择
         * @author ZhangTeng 20190213
         */
    changeProjectSelected: function () {
      var _self = this;
      var count = 0;
      _self.projectItemUserListUser.splice(0, _self.projectItemUserListUser.length);

      if (_self.traceDto == null || _self.traceDto.projectId == null) {
        return;
      }

      $.ajax({
        url: Common.getApiURL('ProjectItemUserResource/listByProjectItemId'),//通过项目Id查找有权操作的项目的用户
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: { 'projectItemId': _self.traceDto.projectId },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          for (var index = 0; index < data.length; index++) {
            _self.projectItemUserListUser[index] = data[index];
            // _self.$set(_self.projectItemUserListUser, index, data[index]);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },


    //日期选择
    planFinishedDateChanged: function (value) {
      if (value == '') {
        this.traceDto.planFinishedDate = null;
      } else {
        this.traceDto.planFinishedDate = value;
      }
    },

    //初始化数据
    initContext: function () {
      var _self = this;
      _self.traceId = this.$route.params.traceId;
      if (_self.traceId != null && _self.traceId != '') {
        TraceResource.uniqueByTraceId(_self.traceId).then(successData => {
          _self.traceDto = successData;
          if (successData != undefined && successData.audioSrcs != undefined) {
            _self.srcArray = JSON.parse(successData.audioSrcs);
          }
          _self.changeProjectSelected();
          $('#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.traceDto != null) {
            $('#summernote').summernote('code', _self.traceDto.detail);
          }
          _self.summernoteInitSuccess = true;
        }, errorData => {
          Common.processException(errorData);
        });
      }
    },
    /**
         * 根据项目id查询项目任务时间节点
         * @author GuoZhiBo 20191010
         */
    queryProjectTaskDtoByProjectId: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('ProjectTaskResource/queryProjectTaskDtoByProjectId'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          projectId: _self.traceDto.projectId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.projectTaskDtos = data;
          console.log(_self.projectTaskDtos);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>

</style>