<template>
  <div class="container-fluid">
    <Navbar
      :title="title"
      :is-go-back="true"
    />
    <GanttScale
      ref="ganttScale"
      gantt-div-id="ganttContainer"
    />
    <div style="line-height: 10px">
      <br />
    </div>
    <div
      id="ganttContainer"
      style="width:100%; height:100%px; min-height: 500px; background-color:white;"
    />
  </div>
</template>

<script>
var Common = require('../common/Common.js');
var Navbar = require('pc-component-v3').default.Navbar;
var Loading = require('pc-component-v3').default.Loading;
var GanttScale = require('../widget/GanttScale2.vue').default;


module.exports = {
  data: function () {
    return {
      title: '',
      projectId: undefined,
      userList: [],
      canEdit: false,
    };
  },

  components: {
    Common,
    Navbar,
    Loading,
    GanttScale,
  },

  methods: {
    /**
         * 上一步
         */
    undo: function () {
      gantt.undo();
    },
    /**
         * 下一步
         */
    redo: function () {
      gantt.redo();
    },
    //查询所有任务及链接
    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);
        },
      });
    },
    /**
         * 初始化用户
         * @author ZhangTeng 20190221
         */
    initData: function () {
      var _self = this;
      //var obj = _self.$route.params.projectId;
      $.ajax({
        url: Common.getApiURL('TraceResource/queryUserByProjectId'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.projectId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          for (var x = 0; x < data.length; x++) {
            var event = {
              key: data[x].id,
              label: data[x].name,
            };
            _self.userList.push(event);
          }

          _self.initGantt();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //保存数据
    runSaveGantt: function () {
      var _self = this;
      var canEdit = _self.canEdit;
      if (canEdit == false) {
        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);
      }
      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) {
          return;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //获得登录用户权限
    personnelJurisdictionSet: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceResource/queryPersonnelJurisdiction'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.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);
        },
      });
    },
    //拿到前台数据
    getProjectItemDto: function () {
      var _self = this;
      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);
      }
      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,
      };
      return projectItemDto2;
    },

    //设置返回前台的数据
    setDate: function (data) {
      var _self = this;
      _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,
      };
      return tasks;
    },
    datedifference: function (sDate1, sDate2) {
      var dateSpan,
        tempDate,
        iDays;
      if (sDate1 == undefined || sDate2 == undefined) {
        return 0;
      }
      dateSpan = sDate2 - sDate1;
      dateSpan = Math.abs(dateSpan);
      iDays = (dateSpan / (24 * 3600 * 1000));
      return iDays;
    },

    /**
         * 初始化甘特图
         */
    initGantt: function () {
      let _self = this;

      gantt.serverList('staff', _self.userList);

      // end test data
      gantt.config.grid_width = 480;
      gantt.config.grid_resize = true;
      gantt.config.open_tree_initially = true;

      var labels = gantt.locale.labels;
      labels.section_description = '任务名';
      labels.column_remarks = labels.section_remarks = '备注';
      labels.column_owner = labels.section_owner = '责任人';

      function byId(list, id) {
        for (var i = 0; i < list.length; i++) {
          if (list[i].key == id)
            return list[i].label || '';
        }
        return '';
      }

      gantt.config.columns = [{
        name: 'text',
        resize: true,
        label: '任务名',
        tree: true,
        width: '*',
        align: 'left',
      },
      {
        name: 'start_date',
        resize: true,
        label: '开始日期',
        width: 80,
        align: 'center',
      },
      {
        name: 'owner',
        resize: true,
        width: 50,
        align: 'center',
        template: function (item) {
          return byId(gantt.serverList('staff'), item.owner_id);
        },
      },
      {
        name: 'duration',
        resize: true,
        label: '耗时',
        width: 40,
        align: 'center',
      },
      {
        name: 'add',
        width: 40,
      },
      ];
      // gantt.locale.labels.section_period = "时间范围";
      // gantt.config.lightbox_additional_height = 120;

      var sections = [{
        name: 'description',
        height: 40,
        map_to: 'text',
        type: 'textarea',
      },
      {
        name: 'owner',
        height: 26,
        map_to: 'owner_id',
        type: 'select',
        options: gantt.serverList('staff'),
      },
      {
        name: 'type',
        height: 26,
        type: 'typeselect',
        map_to: 'type',
      },
      {
        name: 'time',
        height: 26,
        type: 'duration',
        map_to: 'auto',
      },
      {
        name: 'remarks',
        map_to: 'remarks',
        type: 'textarea',
      },
      ];
      gantt.config.lightbox.sections = sections;
      gantt.config.lightbox.project_sections = sections;
      gantt.config.lightbox.milestone_sections = sections;


      gantt.templates.task_text = function (start, end, task) {
        var progress = task.progress || 0;
        return task.text + '(' + Math.floor(progress * 100) + '%' + ')';
      };

      //gantt.templates.grid_row_class =
      //    gantt.templates.task_row_class =
      //    gantt.templates.task_class = function (start, end, task) {
      //       var css = [];
      //        if (task.$virtual || task.type == gantt.config.types.project)
      //           css.push("summary-bar");

      //        if (task.owner_id) {
      //            css.push("gantt_resource_task gantt_resource_" + task.owner_id);
      //        }

      //        return css.join(" ");
      //    };

      gantt.attachEvent('onLoadEnd', function () {
        var styleId = 'dynamicGanttStyles';
        var element = document.getElementById(styleId);
        if (!element) {
          element = document.createElement('style');
          element.id = styleId;
          document.querySelector('head').appendChild(element);
        }
        var html = [];
        var resources = gantt.serverList('staff');
        element.innerHTML = html.join('');
      });
      //保存后执行
      // gantt.attachEvent("onAfterTaskAdd", function (id, item) {
      //     var projectItemDto = _self.getProjectItemDto();
      //     _self.setTaskType(projectItemDto);
      // });

      //删除后执行
      // gantt.attachEvent("onAfterTaskDelete", function (id, item) {
      //     var projectItemDto = _self.getProjectItemDto();
      //     _self.setTaskType(projectItemDto);
      // });

      //拖动任务后执行
      // gantt.attachEvent("onAfterTaskMove", function (id, item) {
      //     var projectItemDto = _self.getProjectItemDto();
      //     _self.setTaskType(projectItemDto);
      // });

      //初始化自动排版
      gantt.config.undo = true;
      gantt.config.redo = true;
      gantt.config.auto_scheduling = true;
      gantt.autoSchedule();

      //设置左边项目栏可拖动			
      gantt.config.order_branch = true;

      //设置右边显示进度条
      gantt.config.layout = {
        //css: "gantt_container",
        rows: [{
          cols: [{
            view: 'grid',
            width: 320,
            scrollY: 'scrollVer',
          },
          {
            resizer: true,
            width: 1,
          },
          {
            view: 'timeline',
            scrollX: 'scrollHor',
            scrollY: 'scrollVer',
          },
          {
            resizer: true,
            width: 1,
          },
          {
            view: 'scrollbar',
            id: 'scrollVer',
          },
          ],

        },
        {
          view: 'scrollbar',
          id: 'scrollHor',
          height: 20,
        },
        ],
      };
      /* 				//显示进度百分比
                            gantt.templates.progress_text = function(start, end, task) {
                                return "<span style='text-align:left;'></span>";
                            }; */
      //设置传入后台日期格式
      gantt.config.xml_date = '%Y-%m-%d %H:%i:%s'; // XML中的日期格式
      //允许出现异常时错误警报
      gantt.config.show_errors = true;
      //分上下级显示
      // gantt.templates.task_class = function (st, end, item) {
      //     return item.$level == 0 ? "gantt_project" : ""
      // };
      gantt.config.autosize = 'y';

      gantt.init('ganttContainer');
      _self.$refs.ganttScale.setDefaultScale();
      _self.showTaskDtos();
    },
  },


  mounted: function () {
    var _self = this;
    _self.projectId = this.$route.params.projectId;
    console.log(_self.projectId);
    _self.initData();
    _self.personnelJurisdictionSet();

    // window.ganttTimer = setInterval(() => {
    // 	// 某些定时器操作  
    // 	_self.runSaveGantt();
    // }, 60000);


  },

  beforeUnmount: function () {
    // if (window.ganttTimer != null) {
    //   window.clearInterval(ganttTimer);
    //   window.ganttTimer = null;
    // }
  },
};
</script>
