<template>
  <div class=" bgRightMidBox">
    <section class="h-full" ref="echartsContainer"></section>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { GetRoomList, GetMonitorRoomUsageRate } from '@/api/room';
import { statusToTxt, textToColor } from '@/utils/common';
let chart = null;
export default {
  data() {
    return {
      isLoding: false,
      chartOptions: {
        grid: {
          width: '90%',
          height: '87%',
          top: '10%',
          left: '7%',
        },
        legend: {
          data: [],
          selectedMode: false,
          top: '3%',
          right: '4%',
          textStyle: {
            color: '#675C88',
            fontSize: 12,
          },
        },
        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,
          },
        },
        series: [],
      },
      legendDataList: ['入手术间', '手术开始', '手术结束', '出手术间'],
      yAxisArr: [],
      showPageIndex: -1,
      allPageIndex: 0,
      allPageNum: 0,
      pageNum: 20,
      allRoomList: [],
      originData: [],
      renderTimer: null,
    };
  },
  methods: {
    initMockData() {
      // 创建一个数组来存储整点时间
      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: textToColor('出手术间'),
              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: textToColor('手术开始'),
                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: textToColor('手术结束'),
                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: textToColor('入手术间'),
              diff: '7',
              name: '入手术间',
            });
          }
        }
      }
      this.formatLegendData();
      // 生成series数据
      this.chartOptions.series = this.seriesData(timeArr);
      console.log(this.chartOptions);

      chart.setOption(this.chartOptions);
    },
    onGetPageData() {
      let today = dayjs().format('YYYY-MM-DD');
      // today = '2024-06-06';
      // today = '2024-08-07';
      this.chartOptions.xAxis.min = `${today} 08:00:00`;
      this.chartOptions.xAxis.max = `${dayjs(today).add(1, 'day').format('YYYY-MM-DD')} 07:00:00`;
      GetMonitorRoomUsageRate(today).then(res => {
        this.originData = res['data'];
        this.formatPageList();
      });
    },
    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;
      });
    },
    formatLegendData() {
      if (this.legendDataList.length) {
        this.legendDataList.forEach(item => {
          this.chartOptions.legend.data.push({
            name: item,
            icon: 'rect',
            itemStyle: {
              color: textToColor(item),
            },
          });
        });
      } else {
        this.chartOptions.legend.data = [];
      }
    },
    formatPageList() {
      // X轴数据
      const timeArr = [];
      // 根据展示页数,处理Y轴数据
      ++this.showPageIndex >= this.allPageNum && (this.showPageIndex = 0);
      this.yAxisArr = this.allRoomList.slice(this.pageNum * this.showPageIndex, this.pageNum * (this.showPageIndex + 1)).reverse();
      console.log(this.yAxisArr);
      this.chartOptions.yAxis.data = this.yAxisArr;
      this.legendDataList = [];
      // 格式化指定手术间信息
      this.originData.forEach(item => {
        if (this.yAxisArr.includes(item['roomName'])) {
          if (!this.legendDataList.includes(statusToTxt(item['procStatus']))) {
            this.legendDataList.push(statusToTxt(item['procStatus']));
          }
          timeArr.push({
            startTime: dayjs(item['inRoomDateTime']).format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(item['inRoomDateTime']).add(item['surgicalDuration'], 'minute').format('YYYY-MM-DD HH:mm:ss'),
            yValue: this.yAxisArr.findIndex(text => text == item['roomName']),
            color: textToColor(statusToTxt(item['procStatus'])),
            diff: item['surgicalDuration'],
            name: statusToTxt(item['procStatus']),
          });
        }
      });
      this.formatLegendData();
      console.log(timeArr);
      // 生成series数据
      this.chartOptions.series = this.seriesData(timeArr);
      chart.setOption(this.chartOptions);
      this.renderTimer = setTimeout(() => {
        this.formatPageList();
      }, 5000);
    },
  },
  mounted() {
    GetRoomList().then(res => {
      res['Data']['Data'].forEach(item => {
        if (item['RoomTypeCode'] == 0) {
          this.allRoomList.push(item['RoomName']);
          this.allPageIndex++;
        }
      });
      this.allPageNum = Math.ceil(this.allPageIndex / this.pageNum);
      chart = echarts.init(this.$refs.echartsContainer);
      if (this.$store.getters.isMock) {
        this.initMockData();
      } else {
        this.onGetPageData();
        setInterval(() => {
          this.onGetPageData();
        }, this.$store.getters.intervalTime);
      }
    });
    window.addEventListener("resize", () => {
      chart.resize();
    });
  },
};
</script>

<style lang="scss" scoped>
.bgRightMidBox {
  width: vw(1270);
  height: vh(904);
  background-image: url('@/assets/svg/Room/RightMid/Box.svg');
  background-size: 103%;
  background-position: center;
  background-repeat: no-repeat;
}
</style>
