<template>
  <div>
    <div style="text-align: left; margin-bottom: 16px;float: left;">
      <span>刻度：</span>
      <el-select-v2 v-model="interval" :options="optionList" placeholder="Please select" />
    </div>
    <div style="text-align: left; margin-bottom: 16px;float: left; margin-left: 16px;">
      <span>时间范围：</span>
      <a-range-picker v-model:value="dateRange" show-time="{ format: 'HH:mm' }" :format="dateFormat"
        :placeholder="['开始时间', '结束时间']" allowClear @change="onRangeChange" />
    </div>
    <div style="padding: 0 24px;">
      <el-slider v-model="sliderValue" :min="minSliderValue" :max="maxSliderValue" :format-tooltip="formatTooltip" range
        @change="onSliderChange"></el-slider>
    </div>

    <g-gantt-chart :chart-start="chartStart" :chart-end="chartEnd" precision="minute" :minuteInterval="interval"
      :row-height="40" grid width="100%" bar-start="beginProcessDate" bar-end="endProcessDate" :date-format="format">
      <template v-for="item in contree" :key="item.helicopterInfoDTO.id">
        <el-button type="success" size="default">{{ item.helicopterInfoDTO.name }}</el-button>

        <g-gantt-row :label="item.helicopterInfoDTO.name" :bars="item.list" highlight-on-hover />

      </template>
    </g-gantt-chart>
  </div>

</template>

<script setup lang="ts">
import { reactive, ref, nextTick, Ref } from "vue";
import GGanttRow from "./GGanttRow.vue";
import GGanttChart from "./GGanttChart.vue";
import { GanttBarObject } from "../models/models";
import { ElSelect, ElMessage, ElSelectV2, ElButton, ElSlider } from "element-plus"
import httpRequest from '@/utils/httpRequest.js'
import dayjs, { Dayjs } from 'dayjs';
import { computed } from "@vue/reactivity";
const sliderValue = ref<[number, number]>([0, 100])
const minSliderValue = ref()
const maxSliderValue = ref()

const onSliderChange = () => {
  const [min, max] = sliderValue.value
  chartStart.value = dayjs(min).format('YYYY-MM-DD HH:mm')
  chartEnd.value = dayjs(max).format('YYYY-MM-DD HH:mm')

}

const formatTooltip = (value: number) => {
  return dayjs(value).format('YYYY-MM-DD HH:mm')
}
const optionList = [
  { label: 1, value: 1 },
  { label: 5, value: 5 },
  { label: 10, value: 10 },
  { label: 20, value: 20 },
  { label: 30, value: 30 },
  { label: 60, value: 60 },
]
let chartStart = ref("2022-02-01 12:00");
let chartEnd = ref("2022-02-01 18:00");
const format = ref("YYYY-MM-DD HH:mm");
let contree = ref([] as any[]);
const bars1 = ref([] as any);

const dateValueStart = ref("");
const dateValueEnd = ref("");
const interval = ref(10);
const minuteValue = ref();
const emits = defineEmits(["updateTaskName"]);
const Backgrounds = ['#BE9B93', '#C1F462', '#485C23', '#67EAC1', '#35B0C9', '#151EC4', '#7425EC', '#F89681', '#AC31E2', '#972880', '#5A0E34', '#247168', '#D6C51B', '#F95E3D', '#F82F04'];
const dateFormat = 'YYYY-MM-DD HH:mm';

const dateRange = ref()

const onRangeChange = (value: [Dayjs, Dayjs], dateString: [string, string]) => {
  const [first, end] = dateString
  if (first && end) {
    chartStart.value = first
    chartEnd.value = end
  } else {
    chartStart.value = dateValueStart.value
    chartEnd.value = dateValueEnd.value
  }
};
const getRandomColor = function () {
  const r = Math.floor(Math.random() * 255);
  const g = Math.floor(Math.random() * 255);
  const b = Math.floor(Math.random() * 255);
  return 'rgba(' + r + ',' + g + ',' + b + ', 1)';
}
const baseUrl = '/task/helicopterTask/getGanttInfo?id=' + sessionStorage.getItem('taskResultId') + "&token=" + sessionStorage.getItem('token')

httpRequest
  .get(baseUrl)
  .then(({ data }) => {

    if (!data) {
      ElMessage({
        message: '数据正在计算中...',
        type: 'warning'
      })
      return
    }

    let { beginTime, endTime, name, contreeList, minuteInterval } = data;
    emits("updateTaskName", name);
    chartStart.value = beginTime;
    chartEnd.value = endTime;
    dateValueStart.value = beginTime;
    dateValueEnd.value = endTime;

    minSliderValue.value = dayjs(beginTime).toDate().getTime();
    maxSliderValue.value = dayjs(endTime).toDate().getTime();
    sliderValue.value = [minSliderValue.value, maxSliderValue.value];
    // dateRange.value = [dayjs(beginTime, dateFormat), dayjs(endTime, dateFormat)];
    if (minuteInterval) {
      interval.value = minuteInterval
    }

    if (Array.isArray(contreeList)) {
      contreeList = contreeList.map((value, index) => {
        if (Array.isArray(value.processesList)) {
          const result = value.processesList.map((v, i) => {
            v.begin = new Date(v.beginProcessDate).getTime()
            v.end = new Date(v.endProcessDate).getTime()
            v.ganttBarConfig = {
              id: v.id,
              label: v.name,
              style: {
                background: i < 16 ? Backgrounds[i] : getRandomColor(),
                color: "#fff",
              },
              hasHandles: false,
              // immobile:true
            };
            return v;
          });

          formatter(result);
          value.list = result
        }
        return value
      });
    }
    contree.value.push(...contreeList)
  })
  .catch((err) => {
    console.log(err);
  });

const formatter = (processesList: any[]) => {
  let index = 0, top = 0
  while (index < processesList.length) {
    const current = processesList[index]
    const filterValues = processesList.filter((v, i) => i != index)

    for (const value of filterValues) {
      if (current.begin >= value.begin && current.begin < value.end) {
        if (!value.ganttBarConfig.isCover) {
          top = 0
        }
        top++
        current.ganttBarConfig.isCover = true
        current.ganttBarConfig.top = top
        break
      }
    }
    index++
  }
  return processesList
}



</script>
