<template>
  <div>
    <div>
      <Navbar
        title="新建任务"
        :is-go-back="true"
      />

      <div>
        <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>
        <AudioField
          :class-name="className"
          :src-array="srcArray"
          :is-readonly="'false'"
          @handle-stop="handelEndRecord"
          @delete-audio-src="deleteAudioSrc"
        />
        <div class="form-group">
          <label for="trackUserId">责任人</label>
          <select
            id="trackUserId"
            v-model="userSelected"
            class="form-control"
          >
            <option value="" />
            <option
              v-for="user in userList" :key="user"
              :value="user.userId"
            >
              {{ user.userName }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label for="projectName">项目</label>
          <select
            id="projectName"
            v-model="projectId"
            class="form-control"
            :disabled="'projectId != null'?'true':'false'"
          >
            <option
              v-for="project in projectUserList" :key="project"
              :value="project.projectItemId"
            >
              {{ project.projectItemName }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label for="projectName">时间节点</label>
          <ATreeselect
            ref="treeSelect"
            :multiple="false"
            :options="projectTaskDtos"
          />
        </div>
        <div class="form-group">
          <label>完成时间</label>
          <DateWidget
            :date-value="planFinishedDate"
            class="form-control"
            :readonly="isdisable"
            @on-value-change="depreciationStartDateChanged"
          />
        </div>

        <button
          style="width:100%;background-color: #007aff;color: white"
          type="button"
          class="btn btn-blue search-button"
          @click="saveTrace()"
        >
          保存
        </button>
      </div>
    </div>
    <Loading v-if="loading" />
  </div>
</template>
<script type="text/javascript">
var Notify = require('pc-component-v3').default.Notify;
var Common = require('../common/Common.js');
var Uuid = require('pc-component-v3').default.Uuid;
var UpladFile = require('../widget/UpladFile.js');

var Navbar = require('pc-component-v3').default.Navbar;
var DateWidget = require('pc-component-v3').default.Date;
var Loading = require('pc-component-v3').default.Loading;
import Treeselect from '../widget/TreeSelect.vue';
import ATreeselect from '../widget/ATreeSelect.vue';
var AudioField = require('../widget/AudioField.vue').default;
export default {
  components: {
    Navbar,
    Loading,
    Common,
    Notify,
    UpladFile,
    DateWidget,
    Treeselect,
    ATreeselect,
    AudioField,
  },
  data: function () {
    return {
      traceDto: {},
      className: 'com.leanwo.prodog.Trace',
      userList: [],
      userSelected: '',
      projectUserList: [],
      planFinishedDate: '',
      isdisable: false, //日期框是否可编辑
      projectId: '', //项目Id
      summernoteInitSuccess: false, // summernote初始化成功
      projectTaskDtos: [],//项目任务时间点
      srcArray: [],
      loading: false,
    };
  },
  watch: {
    'projectId': function (curVal, oldVal) {
      var _self = this;
      _self.$refs.treeSelect.setValue(undefined);
      _self.queryProjectTaskDtoByProjectId();
    },
  },


  mounted: function () {
    var _self = this;
    this.projectId = this.$route.params.projectId;
    this.initProject();
    this.initData();
    $('#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');
    }
    //界面销毁时，修改插入连接的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();
    },
    saveTrace: function () {
      var _self = this;
      _self.traceDto.receiveUserId = _self.userSelected;//接收人Id
      _self.traceDto.projectTaskId = _self.$refs.treeSelect.getValue();
      if (_self.planFinishedDate != undefined && _self.planFinishedDate != '') {
        _self.traceDto.planFinishedDate = _self.planFinishedDate; //完成时间
      }
      _self.traceDto.projectId = _self.projectId;//项目Id

      _self.traceDto.detail = $('#summernote').summernote('code');
      if (_self.traceDto.summary != '' && _self.traceDto.summary != undefined) {
        _self.loading=true;
        $.ajax({
          url: Common.getApiURL('TraceResource/saveTrace'),
          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: 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 ZhangTeng 20190213
         */
    initData: function () {
      var _self = this;
      _self.userList.splice(0, _self.userList.length);
      $.ajax({
        url: Common.getApiURL('ProjectItemUserResource/listByProjectItemId'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: { 'projectItemId': _self.projectId },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data != null) {
            for (var index = 0; index < data.length; index++) {
              _self.userList[index] = data[index];
              // _self.$set(_self.userList, index, data[index]);
              // if (index == 0) {
              //     _self.userSelected = data[index].userId;
              // }
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
         * 初始化项目
         * @author ZhangTeng 20190213
         */
    initProject: function () {
      var _self = this;
      _self.projectUserList.splice(0, _self.projectUserList.length);
      $.ajax({
        url: Common.getApiURL('ProjectItemUserResource/listByUserId'), //查询所有的项目用户
        type: 'get',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data != null) {
            for (var index = 0; index < data.length; index++) {
              _self.projectUserList[index] = data[index];
              // _self.$set(_self.projectUserList, index, data[index]);
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },


    //日期选择
    depreciationStartDateChanged: function (value) {
      this.planFinishedDate = value;
    },
    /**
         * 根据项目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.projectId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.projectTaskDtos = _self.convertToTreedata(data);
          console.log(_self.projectTaskDtos);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    convertToTreedata: function(data) {
      console.log(data);
      var returnData = [];
      for(var i = 0; i < data.length; i++){
        var tempObj = {
          title : data[i].label,
          value : data[i].id,
          key : data[i].id,
        };
        if('children' in data[i]){
          tempObj.children = this.convertToTreedata(data[i].children);
        }
        //push到数据数组中
        returnData.push(tempObj);
      }
      return returnData;
    },
  },

};
</script>

<style scoped>
</style>