<template>
  <div>
    <div class="radio">
      <label class="radio-inline" />
      <div class="btn-group btn-link pull-left">
        <button v-if="canEdit" type="button" class="btn btn-default fa fa-floppy-o" @click="runSaveGantt">&nbsp;保存</button>
        <button type="button" class="btn btn-default fa fa-refresh" @click="showTaskDtos">&nbsp;刷新</button>
        <button type="button" class="btn btn-default fa fa-search-plus" :disabled="disableEnlarge" @click="scale++">&nbsp;放大</button>
        <button type="button" class="btn btn-default fa fa-search-minus" :disabled="disableReduction" @click="scale--">&nbsp;缩小</button>
        <button type="button" class="btn btn-default fa fa-search" @click="setDefaultScale">&nbsp;默认</button>
        <button v-if="hideButtons != true" type="button" class="btn btn-default" @click="showGanttChanged">
          <span v-if="showGantt == 1">手动排程</span>
          <span v-if="showGantt == 2">自动排程</span>
        </button>
        <button type="button" class="btn btn-default fa fa-undo" @click="undo">&nbsp;上一步</button>
        <button type="button" class="btn btn-default fa fa-repeat" @click="redo">&nbsp;下一步</button>
        <button id="fullscreen_button" type="button" class="btn btn-default fa fa-arrows-alt" @click="expand">&nbsp;全屏</button>
        <button v-if="canEdit" type="button" class="btn btn-default" @click="importTemplate">导入模板</button>
        <button type="button" class="btn btn-default" @click="exportFile">导出</button>
      </div>
      <!-- 			<div id="output">
				选择的网站是: {{selected}}
			</div> -->
      <Modal v-model:show="create" large="true" @cancel="$refs.create.show = false" @ok="importTest">
        <template #header>
          选择模板进行导入
        </template>
        <div>
          <div class="form-horizontal">
            <div class="form-group">
              <label for="ganttName" class="col-xs-4 col-sm-3 col-md-2 col-lg-1 control-label">
                <nobr>选择模板</nobr>
              </label>
              <div class="col-xs-8 col-sm-9 col-md-10 col-lg-11">
                <select v-model="selected" class="form-control">
                  <option value="">选择一个模板</option>
                  <option v-for="template in templates" :key="template">{{ template }}</option>
                </select>
              </div>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  </div>
</template>


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


module.exports = {
  /**
		 * ganttDivId : 甘特图DIV的id
		 */
  props: ['ganttDivId', 'hideIndex', 'hideButtons'],

  data: function() {
    return {
      disableEnlarge: false,
      disableReduction: false,
      scale: 1,
      showGantt: 1, // 1：手动排版,2.自动排版
      columnsTemp: [],
      templates: [],
      selected: '', //select选中的值
      canEdit:false, //是否可以编辑甘特图
      create: false,
    };
  },

  components: {
    Common,
    Modal,
  },

  methods: {
    showGanttChanged: function() {
      if (this.showGantt >= 2) {
        this.showGantt = 1;
      } else {
        this.showGantt++;
      }
    },
    importTemplate: function() {
      this.create = true;

    },
    /**
			 * 设置默认的标度
			 */
    setDefaultScale: function() {
      this.setScaleConfig(1);
    },
    /**
			 * 上一步
			 */
    undo: function() {
      gantt.undo();
    },
    /**
			 * 下一步
			 */
    redo: function() {
      gantt.redo();
    },

    /**
			 * 全屏
			 */
    expand: function() {
      if (!gantt.getState().fullscreen) {
        // expanding the gantt to full screen
        gantt.expand();
      } else {
        // collapsing the gantt to the normal mode
        gantt.collapse();
      }
    },
    /**
			 * 导出
			 */
    exportFile: function() {
      gantt.exportToPDF();
    },
    /**
			 * 设置标度
			 */
    setScaleConfig: function(value) {
      if (value == 4) {
        this.disableEnlarge = true;
      } else {
        this.disableEnlarge = false;
      }
      if (value == 0) {
        this.disableReduction = true;
      } else {
        this.disableReduction = false;
      }
      switch (value) {
      case 0:
        gantt.config.scale_unit = 'day';
        gantt.config.date_scale = '%l, %F %d';
        gantt.config.min_column_width = 20;
        gantt.config.scale_height = 20 * 3;
        gantt.templates.task_cell_class = function(task, date) {
          if (date.getHours() == 8) {
            return 'day_start';
          }
          if (date.getHours() == 18) {
            return 'day_end';
          }
          return '';
        };
        var weekScaleTemplate = function(date) {
          var dateToStr = gantt.date.date_to_str('%d %M');
          var weekNum = gantt.date.date_to_str('(week %W)');
          var endDate = gantt.date.add(
            gantt.date.add(date, 1, 'week'),
            -1,
            'day',
          );
          return (
            dateToStr(date) + ' - ' + dateToStr(endDate) + ' ' + weekNum(date)
          );
        };
        gantt.config.subscales = [{
          unit: 'week',
          step: 1,
          template: weekScaleTemplate,
        },
        {
          unit: 'hour',
          step: 1,
          date: '%G',
        },
        ];
        break;
      case 1:
        gantt.config.scale_unit = 'day';
        gantt.config.step = 1;
        gantt.config.date_scale = '%M %d日';
        gantt.config.subscales = [];
        gantt.config.scale_height = 27;
        gantt.config.min_column_width = 50;
        gantt.templates.date_scale = null;
        break;
      case 2:
        weekScaleTemplate = function(date) {
          var dateToStr = gantt.date.date_to_str('%M %d日');
          var startDate = gantt.date.week_start(new Date(date));
          var endDate = gantt.date.add(
            gantt.date.add(startDate, 1, 'week'),
            -1,
            'day',
          );
          return dateToStr(startDate) + ' - ' + dateToStr(endDate);
        };

        gantt.config.scale_unit = 'week';
        gantt.config.step = 1;
        gantt.templates.date_scale = weekScaleTemplate;
        gantt.config.min_column_width = 50;
        gantt.config.subscales = [{
          unit: 'day',
          step: 1,
          date: '%D',
        }];
        gantt.config.scale_height = 50;
        break;
      case 3:
        gantt.config.scale_unit = 'month';
        gantt.config.date_scale = '%Y年%F';
        gantt.config.subscales = [{
          unit: 'day',
          step: 1,
          date: '%j, 周%D',
        }];
        gantt.config.scale_height = 50;
        gantt.config.min_column_width = 50;
        gantt.templates.date_scale = null;
        break;
      case 4:
        gantt.config.scale_unit = 'year';
        gantt.config.step = 1;
        gantt.config.date_scale = '%Y年';
        gantt.config.min_column_width = 50;
        gantt.config.scale_height = 90;
        gantt.templates.date_scale = null;
        gantt.config.subscales = [{
          unit: 'month',
          step: 1,
          date: '%M',
        }];
        break;
      }
      gantt.render();
    },
    //获得登录用户权限
    personnelJurisdictionSet: function() {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceResource/queryPersonnelJurisdiction'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.$route.params.projectId,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          if (data == null) {
            return;
          }
          if (data.levelOfPerson == 1) {
            _self.canEdit = false;
          }
          if (data.levelOfPerson == 2 || data.levelOfPerson == 3) {
            _self.canEdit = true;
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //获得模板名
    getTemplate: function() {
      var _self = this;
      $.ajax({
        type: 'get',
        url: Common.getApiURL('ProjectTaskResource/queryAllTaskTemples'),
        contentType: 'application/json',
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(datas) {
          _self.templates = datas;
        },

        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },

      });
    },
    //导入模板
    importTest: function() {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('ProjectTaskResource/importTemplateByTimeJson'),
        type: 'get',
        contentType: 'application/json',
        data: {
          selected: _self.selected,
          projectId: _self.$route.params.projectId,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          _self.showTaskDtos();
          _self.selected = '';
          Notify.success('提示', '导入成功', 1500);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //保存数据
    runSaveGantt: function() {
      var _self = this;
      var canEdit=_self.canEdit;
      if(canEdit == false){
        Notify.error('警告', '保存失败，该用户没有权限修改时间节点，请联系管理员分配权限', 1500);
        return;
      }
      var ganttData = [];
      var tasks = gantt.getTaskByTime();
      for (var x = 0; x < tasks.length; x++) {
        var globalTaskIndex = gantt.getGlobalTaskIndex(tasks[x].id);
        var event = {
          id: tasks[x].id,
          parentId: tasks[x].parent == 0 ? undefined : tasks[x].parent,
          name: tasks[x].text,
          type: tasks[x].type,
          projectItemId: _self.$route.params.projectId,
          startDate: tasks[x].start_date,
          endDate: tasks[x].end_date,
          progress: tasks[x].progress,
          sequenceNo: globalTaskIndex,
          remarks: tasks[x].remarks,
          owenUserId: tasks[x].owner_id,
        };
        ganttData.push(event);
      }
      /* 				gantt.eachTask(item => {
									
								}); */
      var links = gantt.getLinks();
      var links2 = [];
      for (let x = 0; x < links.length; x++) {
        let event = {
          id: links[x].id,
          predecessorTaskId: links[x].source,
          taskId: links[x].target,
          type: links[x].type,
        };
        links2.push(event);
      }
      var projectItemDto2 = {
        projectId: _self.$route.params.projectId,
        data: ganttData,
        links: links2,
      };
      $.ajax({
        url: Common.getApiURL('ProjectTaskResource/saveTasksAndLinks'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(projectItemDto2),
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          Notify.success('提示', '保存成功', 1500);
          _self.showTaskDtos();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //刷新数据
    showTaskDtos: function() {
      var _self = this;
      var obj = _self.$route.params.projectId;
      $.ajax({
        url: Common.getApiURL('ProjectTaskResource/queryProjectAndTasks'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': obj,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          if (data == null) {
            return;
          }
          _self.title = data.projectname;
          var projectTaskDtos = data.data;
          var events = [];
          var projectTaskRelationDtos = data.links;
          var events2 = [];
          for (var i = 0; i < projectTaskDtos.length; i++) {
            var event = {
              id: projectTaskDtos[i].id,
              text: projectTaskDtos[i].name,
              remarks: projectTaskDtos[i].remarks,
              owner_id: projectTaskDtos[i].owenUserId,
              start_date: projectTaskDtos[i].startDate,
              duration: projectTaskDtos[i].duration,
              parent: projectTaskDtos[i].parentId,
              type: projectTaskDtos[i].type,
              open: true,
              progress: projectTaskDtos[i].progress,
              index: projectTaskDtos[i].sequenceNo,
            };
            events.push(event);
          }
          for (let i = 0; i < projectTaskRelationDtos.length; i++) {
            let event = {
              id: projectTaskRelationDtos[i].id,
              source: projectTaskRelationDtos[i].predecessorTaskId,
              target: projectTaskRelationDtos[i].taskId,
              type: projectTaskRelationDtos[i].type,
            };
            events2.push(event);
          }
          var tasks = {
            data: events,
            links: events2,
          };
          gantt.clearAll();
          gantt.parse(tasks);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
  watch: {
    scale: function(newValue, oldValue) {
      this.setScaleConfig(newValue);
    },
    showGantt: function(newValue, oldValue) {
      if (newValue == 1) {
        gantt.config.undo = true;
        gantt.config.redo = true;
        gantt.config.auto_scheduling = true;
        gantt.autoSchedule();
      } else if (newValue == 2) {
        gantt.config.undo = false;
        gantt.config.redo = false;
        gantt.config.auto_scheduling = false;
      }
    },
  },
  mounted: function() {
    var _self = this;
    _self.getTemplate();
    _self.personnelJurisdictionSet();
  },
};
</script>

<style scoped>
.btn-focus {
    background-color: #e6e6e6;
    background-position: 0 32px;
    color: #333;
}
</style>
