<template>
  <div class="gantt-container">
    <div ref="gantt" class="gantt-chart"></div>
  </div>
</template>

<script>
import { gantt } from "dhtmlx-gantt";
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";

export default {
  name: "GanttChart",
  props: {
    tasks: {
      type: Object,
      default: () => ({
        data: []
      })
    }
  },
  mounted() {
    this.initGantt();
  },
  beforeDestroy() {
    if (gantt.$_initialized) {
      gantt.destructor();
      gantt.$_initialized = false;
    }
  },
  methods: {
    initGantt() {
      // 初始化甘特图
      gantt.init(this.$refs.gantt);

      // 配置甘特图
      gantt.config.scale_unit = "day";
      gantt.config.date_scale = "%d %M";
      gantt.config.subscales = [
        { unit: "hour", step: 6, date: "%H:%i" }
      ];

      gantt.config.columns = [
  {
    name: 'text',
    label: '生产令号',
    tree: true,
    width: 300, // 增大宽度
    align: "left",
    editor: {type: 'text', map_to: 'text'},
    onrender: function (task, node) {
      node.setAttribute("class", "gantt_cell gantt_last_cell gantt_cell_tree " + task.status);
    }
  },
  {name: "start_date", label: "开始时间", width: 100, resize: true, align: "left"}, // 增大宽度
  {name: "duration", label: "天数", width: 80, resize: true, align: "center"},     // 增大宽度
  {name: 'end_date', label: '完成时间', width: 90, resize: true, align: "left"},   // 增大宽度
];

      gantt.config.drag_progress = true;

      // 启用任务拖拽
      gantt.config.drag_move = true;
      gantt.config.drag_resize = true;

      // 自定义拖拽外观
      gantt.config.drag_lightbox = true;

      // 任务更新时触发事件
      gantt.attachEvent("onTaskChanged", (id, task) => {
        this.$emit("task-updated", id, task);
        return true;
      });

      // 任务拖拽结束时触发事件
      gantt.attachEvent("onAfterTaskDrag", (id, mode, e) => {
        this.$emit("task-dragged", id, mode, e);
        return true;
      });

      console.log(this.tasks)

      // 加载数据
      gantt.parse(this.tasks);
    }
  },
  watch: {
    tasks: {
      deep: true,
      handler(newValue) {
        if (gantt.$_initialized) {
          gantt.clearAll();
          gantt.parse(newValue);
        }
      }
    }
  }
};
</script>

<style scoped>
.gantt-container {
  width: 100%;
  height: 600px;
}

.gantt-chart {
  width: 100%;
  height: 100%;
}
</style>