<template>
  <div class="w-[116.94vh] h-[85.51vh] bgRightMidBox">
    <section class="h-full" ref="echartsContainer"></section>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
export default {
  data() {
    return {
      isLoding: false,
      chartOptions: {
        grid: {
          width: '86%',
          height: '80%',
          top: '14%',
        },
        legend: {
          data: [
            {
              name: '入手术室',
              icon: 'rect',
              itemStyle: {
                color: '#92CC76',
              },
            },
            {
              name: '开始手术',
              icon: 'rect',
              itemStyle: {
                color: '#EF6666',
              },
            },
            {
              name: '手术结束',
              icon: 'rect',
              itemStyle: {
                color: '#FAC858',
              },
            },
            {
              name: '出手术室',
              icon: 'rect',
              itemStyle: {
                color: '#5470C6',
              },
            },
          ],
          selectedMode: 'none',
          top: "6%",
          right: "4%",
          textStyle: {
            color: '#fff',
            fontSize: 14,
            fontFamily: 'DIN-Bold,Microsoft YaHei',
          },
        },
        xAxis: {
          type: 'time',
          position: 'top',
          splitNumber: 24,
          axisLabel: {
            color: '#B7BDBF',
            fontSize: 12,
            margin: 16,
            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: '#B7BDBF',
            fontSize: 12,
            margin: 16,
            fontFamily: 'DIN-Bold,Microsoft YaHei',
          },
        },
        series: [],
      },
    };
  },
  methods: {
    initData() {
      // 创建一个数组来存储整点时间
      const currentDate = dayjs().format('YYYY-MM-DD');
      const hours = new Date().getHours();
      const detailMin = dayjs().subtract(1, 'minute').format('HH:mm:00');
      const sevenMinutesAgo = dayjs().subtract(8, 'minute').format('HH:mm:00');
      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(3, '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: '#5470C6',
              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) {
            if (Math.random() > 0.5) {
              timeArr.push({
                startTime: `${currentDate} ${isUseArr[j - 1]}:00:00`,
                endTime: `${currentDate} ${detailMin}`,
                yValue: index - 1,
                color: '#EF6666',
                diff: dayjs(`${currentDate} ${detailMin}`).diff(dayjs(`${currentDate} ${isUseArr[j - 1]}:00:00`), 'minute'),
                name: '开始手术',
              });
            } else {
              timeArr.push({
                startTime: `${currentDate} ${isUseArr[j - 1]}:00:00`,
                endTime: `${currentDate} ${detailMin}`,
                yValue: index - 1,
                color: '#FAC858',
                diff: dayjs(`${currentDate} ${detailMin}`).diff(dayjs(`${currentDate} ${isUseArr[j - 1]}:00:00`), 'minute'),
                name: '手术结束',
              });
            }
          } else if (isUseArr[j] > hours && isUseArr[j - 1] == hours) {
            timeArr.push({
              startTime: `${currentDate} ${sevenMinutesAgo}`,
              endTime: `${currentDate} ${detailMin}`,
              yValue: index - 1,
              color: '#92CC76',
              diff: '7',
              name: '入手术室',
            });
          }
        }
      }
      // 生成series数据
      console.log(timeArr);
      this.chartOptions.series = this.seriesData(timeArr);
    },
    seriesData(data) {
      const res = 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: '#B7BDBF',
                    textSize: '12px',
                    textAlign: 'center',
                  },
                },
              ],
            };
          },
          data: [item],
        };
      });
      return res;
    },
    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();
    chart.setOption(this.chartOptions);
  },
};
</script>

<style>
.bgRightMidBox {
  background-image: url('@/assets/svg/Room/RightMid/Box.svg');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}
</style>
