<template>
  <div class="rightMiddle">
    <dv-border-box-13>
      <dv-loading v-if="isLoding">Loading...</dv-loading>
      <section v-else ref="echartsContainer"></section>
    </dv-border-box-13>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
export default {
  data() {
    return {
      isLoding: false,
      chartOptions: {
        grid: {
          width: '92%',
          height: '88%',
          left: '6%',
          top: '10%',
        },
        legend: {
          type: 'scroll',
          data: ['手术准备', '手术中', '完成手术'],
          top: 10,
          left: 10,
          textStyle: {
            color: '#fff',
            fontSize: 14,
          },
        },
        xAxis: {
          type: 'time',
          position: 'top',
          splitNumber: 24,
          axisLabel: {
            color: '#fff',
            fontSize: 14,
            formatter: function (value) {
              var date = new Date(value);
              var hours = date.getHours();
              var minutes = date.getMinutes();
              if (hours === 0 && minutes === 0) {
                return '00:00';
              } else {
                return (hours < 10 ? '0' : '') + hours + ':' + (minutes < 10 ? '0' : '') + minutes;
              }
            },
          },
        },
        yAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            color: '#fff',
            fontSize: 14,
          },
        },
        series: [],
      },
    };
  },
  methods: {
    initData() {
      // 创建一个数组来存储整点时间
      const currentDate = dayjs().format('YYYY-MM-DD');
      const hours = new Date().getHours();
      this.chartOptions.xAxis.min = `${currentDate} 08:00:00`;
      this.chartOptions.xAxis.max = `${dayjs().add(1, 'day').format('YYYY-MM-DD')} 07:00:00`;
      // 手术间数量
      const num = 20;
      // 时间数组
      const timeArr = [];
      // 生成手术间
      for (let index = num; index >= 1; index--) {
        this.chartOptions.yAxis.data.push(`手术间${String(index).padStart(2, '0')}`);
        const isUseArr = this.getUseTime();
        for (let j = 1; j < isUseArr.length; j += 2) {
          if (isUseArr[j] <= hours) {
            timeArr.push({
              startTime: `${currentDate} ${isUseArr[j - 1]}:00:00`,
              endTime: `${currentDate} ${isUseArr[j]}:00:00`,
              yValue: index - 1,
              color: '#87ceeb',
              diff: dayjs(`${currentDate} ${isUseArr[j]}:00:00`).diff(
                dayjs(`${currentDate} ${isUseArr[j - 1]}:00:00`),
                'minute'
              ),
              name: '完成手术',
            });
          } else if (isUseArr[j] > hours && isUseArr[j - 1] < hours) {
            timeArr.push({
              startTime: `${currentDate} ${isUseArr[j - 1]}:00:00`,
              endTime: `${currentDate} ${hours}:00:00`,
              yValue: index - 1,
              color: '#72BDA3',
              diff: dayjs(`${currentDate} ${hours}:00:00`).diff(
                dayjs(`${currentDate} ${isUseArr[j - 1]}:00:00`),
                'minute'
              ),
              name: '手术中',
            });
          } else if (isUseArr[j] > hours && isUseArr[j - 1] == hours) {
            timeArr.push({
              startTime: `${currentDate} ${isUseArr[j - 1]}:00:00`,
              endTime: `${currentDate} ${hours}:05:00`,
              yValue: index - 1,
              color: '#ECBA82',
              diff: dayjs(`${currentDate} ${hours}:05:00`).diff(
                dayjs(`${currentDate} ${isUseArr[j - 1]}:00:00`),
                'minute'
              ),
              name: '手术准备',
            });
          }
        }
      }
      // 生成series数据
      this.chartOptions.series = this.seriesData(timeArr);
    },
    seriesData(data) {
      return data.map(function (item) {
        return {
          type: 'custom',
          name: item.name,
          renderItem: function (params, api) {
            var xStart = api.coord([item.startTime, item.yValue]);
            var xEnd = api.coord([item.endTime, item.yValue]);
            var textX = (xStart[0] + xEnd[0]) / 2;
            var textY = xStart[1] - 20;
            return {
              type: 'group',
              children: [
                {
                  type: 'line',
                  shape: {
                    x1: xStart[0],
                    y1: xStart[1],
                    x2: xEnd[0],
                    y2: xEnd[1],
                  },
                  style: {
                    stroke: item.color,
                    lineWidth: 8,
                  },
                },
                {
                  type: 'text',
                  position: [textX, textY],
                  style: {
                    text: `${item.diff} min`,
                    fill: item.color,
                    textSize: '14px',
                    textAlign: 'center',
                  },
                },
              ],
            };
          },
          data: [item],
        };
      });
    },
    getUseTime() {
      // 随机生成当天手术室的使用时间
      function getRandomUniqueValues(min, max, count) {
        const values = new Set();
        while (values.size < count) {
          values.add(Math.floor(Math.random() * (max - min + 1)) + min);
        }
        return Array.from(values);
      }

      const numValues = Math.floor(Math.random() * 3) + 8;
      const randomValues = getRandomUniqueValues(8, 24, numValues % 2 ? numValues + 1 : numValues);
      return randomValues.sort((a, b) => {
        return a - b;
      });
    },
  },
  mounted() {
    const chartContainer = this.$refs.echartsContainer;
    const chart = echarts.init(chartContainer);
    this.initData();
    // console.group('group');
    // console.log(this.chartOptions);
    // console.log(JSON.stringify(this.chartOptions));
    // console.groupEnd();
    chart.setOption(this.chartOptions);
  },
};
</script>

<style lang="scss" scoped>
.rightMiddle {
  height: 100%;
  :deep(.dv-border-box-13) {
    padding: 2vh;
    box-sizing: border-box;
    section {
      height: 100%;
    }
  }
}
</style>
