<template>
   <div style="height: 100%; width: 100%">
      <div>
          <el-select v-model="timer" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
      </div>
      <div class="rightGatt" style="min-height:calc(78vh - 50px - 5px );width: 100%;overflow: hidden;" ref="gantt"></div>
    </div>
</template>
<script>
  // 引入 组件库
  import '@/assets/js/dhtmlx.js';
  import "@/assets/css/dhtmlxgantt.css";
  import demoData from './ganttData.json'

  export default {
    name: 'gantt',
    // 接受父级组件 传递的数据并规范类型
    data() {
      return {
        moment: '',
        timer: 'day', //定时
        item: {}, //单行数据
        searchTitle: "", //搜索标题
        tasks: {
          data: [
            {
               id: 1,//必填
               text: "这是任务",//必填
               type: "task",// 项目类型 task任务 project项目  milestone里程碑  
               userName:'张',//人名
               start_date: "2023-3-15",
               end_date: "2023-3-30",
               progress: 0.3,//项目任务滑块的进度
               open: true,//是否展开显示
               taskProgress:'0',
             },
             {
               id: 2,
               text: "这是项目",
               type: "project",// 项目类型 task任务 project项目  milestone里程碑  
               userName:'李',//人名
               start_date: "2023-1-15",
               end_date: "2023-1-20",
               progress: 0,
               taskProgress:'1',
             },
             {
              id: 3,
              text: "这是里程碑",
              type: "milestone",// 项目类型 task任务 project项目  milestone里程碑  
              userName:'陈',//人名
              start_date: "2023-2-10",
              end_date: "2023-2-15",
              progress: 0,
              taskProgress:'2',
            },
          ], //数据
          links: [
            // {
            //    id:1,//数据id
            //    source:1,
            //    target:2,
            //    type:0
            //  },
            //  {
            //    id:3,
            //    source:2,
            //    target:3,
            //    type:2
            //  },
          ],
          // 格式 id:数据id  
          //     source:开始链接的项目id  ----为tasks.data中数据的id
          //     target:要链接项目的id  ----为tasks.data中数据的id
          //     type: 0--进行-开始  `尾部链接头部`  
          //           1--开始-开始  `头部链接头部`
          //           2--进行-进行  `尾部链接尾部`
          //           3--开始-进行  `头部链接尾部`
        },
        ganttEvent: { //销毁事件
        },
        options: [{
          value: 'day',
          label: '日'
        }, {
          value: 'week',
          label: '周'
        }, {
          value: 'month',
          label: '月'
        }, {
          value: 'year',
          label: '年'
        }],
        zoomConfig:{
          levels: [
            {
              name: 'day',
              scale_height: 60,
              scales: [{ unit: 'day', step: 1, format: '%d %M' }]
            },
            {
              name: 'week',
              scale_height: 60,
              scales: [
                {
                  unit: 'week',
                  step: 1,
                  format: function (date) {
                    let dateToStr = gantt.date.date_to_str('%m-%d')
                    let endDate = gantt.date.add(date, -6, 'day')
                    let weekNum = gantt.date.date_to_str('%W')(date) //第几周
                    return dateToStr(endDate) + ' 至 ' + dateToStr(date)
                  }
                },
                {
                  unit: 'day',
                  step: 1,
                  format: '%d', // + "周%D"
                  css: function (date) {
                    if (date.getDay() == 0 || date.getDay() == 6) {
                      return 'day-item weekend weekend-border-bottom'
                    } else {
                      return 'day-item'
                    }
                  }
                }
              ]
            },
            {
              name: 'month',
              scale_height: 60,
              min_column_width: 18,
              scales: [
                { unit: 'month', format: '%Y-%m' },
                {
                  unit: 'day',
                  step: 1,
                  format: '%d',
                  css: function (date) {
                    if (date.getDay() == 0 || date.getDay() == 6) {
                      return 'day-item weekend weekend-border-bottom'
                    } else {
                      return 'day-item'
                    }
                  }
                }
              ]
            },
            {
              name: 'quarter',
              height: 60,
              min_column_width: 110,
              scales: [
                {
                  unit: 'quarter',
                  step: 1,
                  format: function (date) {
                    let yearStr = new Date(date).getFullYear() + '年'
                    let dateToStr = gantt.date.date_to_str('%M')
                    let endDate = gantt.date.add(gantt.date.add(date, 3, 'month'), -1, 'day')
                    return yearStr + dateToStr(date) + ' - ' + dateToStr(endDate)
                  }
                },
                {
                  unit: 'week',
                  step: 1,
                  format: function (date) {
                    let dateToStr = gantt.date.date_to_str('%m-%d')
                    let endDate = gantt.date.add(date, 6, 'day')
                    let weekNum = gantt.date.date_to_str('%W')(date)
                    return dateToStr(date) + ' 至 ' + dateToStr(endDate)
                  }
                }
              ]
            },
            {
              name: 'year',
              scale_height: 50,
              min_column_width: 150,
              scales: [
                { unit: 'year', step: 1, format: '%Y年' },
                { unit: 'month', format: '%Y-%m' }
              ]
            }
          ]
        }
      }
    },
    watch:{
      timer(val){
         this.changeTime(val); //默认日格式
      },
    },
    mounted() {
      this.initGantt();
      // this.ganttChangeDateView("d"); //默认日格式
    },
    methods: {
      // 切换 年 季 月 周 日视图
      ganttChangeDateView(type) {
        switch (type) {
          case 'y':
            gantt.config.scale_unit = "year";
            gantt.config.step = 1;
            gantt.config.subscales = null;
            gantt.config.date_scale = "%Y年";
            gantt.templates.date_scale = null;
            break ;
          case 'm':
            gantt.config.scale_unit = "month";
            gantt.config.step = 1;
            gantt.config.date_scale = "%m月";
            gantt.templates.date_scale = null;
            break;
          case 'w':
            gantt.config.scale_unit = "week";
            gantt.config.step = 1;
            gantt.config.date_scale = "第%w周";
            gantt.templates.date_scale = null;
            break;
          case 'd':
            gantt.config.scale_unit = "day";
            gantt.config.step = 1;
            gantt.config.date_scale = "%m月%d日";
            gantt.templates.date_scale = null;
            gantt.config.subscales = null;
            break;
        }
        gantt.render();
      },
      // 是否全屏
      changeFull() {
        gantt.ext.fullscreen.toggle();
      },
       changeTime(val){
       gantt.ext.zoom.setLevel(val)
      },
      // 定位到今日线
      changeToday() {
        this.$nextTick(() => {
          let ganTT = document.getElementsByClassName('gantt_marker today')
          gantt.scrollTo(ganTT[0].offsetLeft - 300, null);
        })
      },
      initGantt() {
        gantt.config.branch_loading = true
        //日期格式化
        gantt.config.date_format = "%Y-%m-%d";
        // gantt.config.order_branch = true;
        // gantt.config.order_branch_free = true;

        //左侧是否自适应
        gantt.config.autofit = true;
        gantt.config.drag_links = true; //连线
        gantt.config.readonly = false; //只读
        // gantt.config.layout = { //拖拽布局
        //   css: "gantt_container",
        //   rows: [{
        //       cols: [{
        //           view: "grid",
        //           id: "grid",
        //           scrollX: "scrollHor",
        //           scrollY: "scrollVer"
        //         },
        //         {
        //           resizer: true,
        //           width: 1
        //         },
        //         {
        //           view: "timeline",
        //           id: "timeline",
        //           scrollX: "scrollHor",
        //           scrollY: "scrollVer"
        //         },
        //         {
        //           view: "scrollbar",
        //           scroll: "y",
        //           id: "scrollVer"
        //         }
        //       ]
        //     },
        //     {
        //       view: "scrollbar",
        //       scroll: "x",
        //       id: "scrollHor",
        //       height: 20
        //     }
        //   ]
        // };
        gantt.config.start_on_monday = true;
        gantt.config.work_time = true;
        gantt.config.fit_tasks = true; //自动调整图表坐标轴区间用于适配task的长度

        // 汉化
        gantt.locale = {
          date: {
            month_full: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
            month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            day_short: ["日", "一", "二", "三", "四", "五", "六"]
          },
          labels: {
            dhx_cal_today_button: "今天",
            day_tab: "日",
            week_tab: "周",
            month_tab: "月",
            new_event: "新建日程",
            icon_save: "保存",
            icon_cancel: "关闭",
            icon_details: "详细",
            icon_edit: "编辑",
            icon_delete: "删除",
            confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
            confirm_deleting: "是否删除计划?",
            section_description: "描述:",
            section_time: "时间范围:",
            section_type: "类型:",
            section_text: "计划名称:",
            section_test: "测试:",
            section_projectClass: "项目类型:",
            taskProjectType_0: "项目任务",
            taskProjectType_1: "普通任务",
            section_head: "负责人:",
            section_priority: "优先级:",
            taskProgress: "任务状态",
            taskProgress_0: "未开始",
            taskProgress_1: "进行中",
            taskProgress_2: "已完成",
            taskProgress_3: "已延期",
            taskProgress_4: "搁置中",
            section_template: "Details",
            column_text: "计划名称",
            column_start_date: "开始时间",
            column_duration: "持续时间",
            column_add: "",
            column_priority: "难度",
            link: "关联",
            confirm_link_deleting: "将被删除",
            message_ok: "确定",
            message_cancel: "取消",
            link_start: "(开始)",
            link_end: "(结束)",
            type_task: "任务",
            type_project: "项目",
            type_milestone: "里程碑",
            minutes: "分钟",
            hours: "小时",
            days: "天",
            weeks: "周",
            months: "月",
            years: "年"
          }
        };

        gantt.serverList("priority", [{
            key: 0,
            label: "最高"
          },
          {
            key: 1,
            label: "较高"
          },
          {
            key: 2,
            label: "普通"
          },
          {
            key: 3,
            label: "较低"
          },
          {
            key: 4,
            label: "最低"
          },
        ]);
        // 左侧显示列名
        gantt.config.columns = [{
            name: "text",
            min_width: 100,
            max_width: 200,
            label: "任务",
            align: "left",
            resize: true,
            tree: true,
            editor: {
              type: 'text',
              map_to: 'text'
            },
          },
          {
            name: "id",
            label: "",
            hide: true
          },
          {
            name: "start_date",
            label: "开始时间",
            width: 120,
            resize: true,
            align: "left"
          },
          {
            name: "userName",
            min_width: 100,
            height: 40,
            label: "负责人",
            resize: true,
            align: "left",
            template: (item) => {
              // if (this.ganttDealById(gantt.serverList('staff'), item.head_id)) {
              //   return `<span class='userIcon' style='background-color:${item.color ? item.color : "#6666"}'>${this.ganttDealById(gantt.serverList('staff'), item.head_id).slice(0, 1)}</span>${this.ganttDealById(gantt.serverList('staff'), item.head_id)}`
              // }
            }
          },
          {
            name: "taskProgress",
            label: "任务状态",
            align: "center",
            min_width: 110,
            editor: {
              type: "select",
              map_to: "taskProgress",
              options: [{
                  key: "0",
                  label: gantt.locale.labels.taskProgress_0
                },
                {
                  key: "1",
                  label: gantt.locale.labels.taskProgress_1
                },
                {
                  key: "2",
                  label: gantt.locale.labels.taskProgress_2
                },
                {
                  key: "3",
                  label: gantt.locale.labels.taskProgress_3
                },
                {
                  key: "4",
                  label: gantt.locale.labels.taskProgress_4,
                }
              ]
            },
            template: (obj) => {
              let val = '';
              switch (obj.taskProgress) {
                case "0":
                  val = `<div class='taskProgress color_bg_1'>未开始</div>`;
                  break;
                case "1":
                  val = `<div class='taskProgress color_bg_2'>进行中</div>`;
                  break;
                case "2":
                  val = `<div class='taskProgress color_bg_3'>已完成</div>`;
                  break;
                case "3":
                  val = `<div class='taskProgress color_bg_4'>已延期</div>`;
                  break;
                case "4":
                  val = `<div class='taskProgress color_bg_5'>搁置中</div>`;
                  break;
              };
              return val
            }
          }

        ]
        gantt.config.lightbox.sections = [
            {
              name: 'text',
              height: 70,
              map_to: 'text',
              type: 'textarea',
              focus: true,
              width: '*'
            },
            {
              name: 'time',
              height: 40,
              map_to: 'auto',
              type: 'duration',
              time_format: ["%Y", "%m", "%d"],
            },
            {
              name: 'projectClass',
              height: 30,
              map_to: 'proTemplate',
              type: 'template',
            },
            {
              name: 'head',
              height: 22,
              map_to: 'head_id',
              type: 'select',
              options: gantt.serverList("staff", []),
            },
            {
              name: 'description',
              height: 70,
              map_to: 'description',
              type: 'textarea'
            },
            {
              name: 'priority',
              height: 40,
              map_to: 'priority',
              type: 'radio',
              options: gantt.serverList("priority")
            },
        ]
        gantt.config.smart_scales = true;
        gantt.plugins({
          click_drag: true,
          drag_timeline: true, // 拖动图
          marker: true, // 时间标记
          fullscreen: true, // 全屏
          tooltip: true, // 鼠标经过时信息
          undo: true // 允许撤销
        })
        gantt.init(this.$refs.gantt);
        gantt.parse(this.tasks);
      },
    }
  };
</script>
<style scoped lang="scss">

  .ant-layout {
    background: #f8f9f9;
  }

  ​ .ant-layout-header {
    background: #fdffff;
    color: rgb(29, 28, 28);
    border: 1px solid #dee0e0;
  }

  ​ .header {
    // position: fixed;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  ​ .content {
    background: #fdffff;
    height: 99vh;
  }

  ​ // 中间

  .centerContent {
    position: relative;
    background: #fdffff;
    width: 100%;
    overflow-y: auto;
    display: flex;
    justify-content: space-between;

    .selectDate {
      width: 100px;
      position: fixed;
      top: 18%;
      right: 9%;
      z-index: 99;
      display: flex;
      justify-content: space-between;
    }
  }
  /deep/ .color_bg_1{
    background-color:#60a3bc !important;
  }
  .color_bg_2{
    background-color:#079992 ;
  }
  .color_bg_3{
    background-color:#78e08f ;
  }
  .color_bg_4{
    background-color:#e55039 ;
  }
  .color_bg_5{
    background-color:#f6b93b ;
  }

</style>
