<template>
  <div :ref="el => setRefMap(el)" :key="props.chartConfig.id"></div>
</template>

<script setup>
import { onMounted, ref, watch, computed } from 'vue';
import { gantt } from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css';
import { getRandomNumber } from '../../../../../utils/chart-util';
import { useChartDataFetch } from '../../../hooks/useChartDataFetch.hook';
import { useChartEditStore } from '@/store/modules/chart/chartEditStore';

const props = defineProps({
  themeSetting: {
    type: Object,
    required: true
  },
  themeColor: {
    type: Object,
    required: true
  },
  chartConfig: {
    type: Object,
    required: true
  }
});

const ganntRef = ref({});

const ganntId = ref(getRandomNumber(8));

onMounted(() => {
  if (props.chartConfig.option.dataset) {
    initGantt(props.chartConfig.option.dataset);
  }
});

// 动态设置ref
const setRefMap = el => {
  if (el) {
    ganntRef.value[ganntId.value] = el;
  }
};

const dataHandle = newData => {
  initGantt(newData);
};

//初始化甘特图
const initGantt = newData => {
  gantt.clearAll();

  gantt.config.grid_width = 350;
  gantt.config.add_column = true; //添加符号

  //时间轴图表中，如果不设置，只有行边框，区分上下的任务，设置之后带有列的边框，整个时间轴变成格子状。
  gantt.config.autofit = false;
  gantt.config.row_height = 60;
  gantt.config.bar_height = 34;
  gantt.config.fit_tasks = true; //自动延长时间刻度，以适应所有显示的任务
  gantt.config.auto_types = true; //将包含子任务的任务转换为项目，将没有子任务的项目转换回任务
  gantt.config.readonly = true; //是否只读
  gantt.i18n.setLocale('cn'); //设置语言
  if (gantt) {
    gantt.init(ganntRef.value[ganntId.value]);
    gantt.parse(JSON.stringify(newData));
  }
};

// 配置时
watch(
  () => props.chartConfig.option.dataset,
  newData => {
    try {
      dataHandle(newData);
    } catch (error) {
      console.log(error);
    }
  },
  {
    deep: false
  }
);

// 预览时
useChartDataFetch(props.chartConfig, useChartEditStore, newData => {
  dataHandle(newData);
});
</script>

<style scoped lang="less"></style>
