<template>
  <section class="waitBox bg-[#F3F2FA]">
    <nav class="h-[11.11vh] pl-[3.7vh] pr-[2.22vh] flex justify-between items-center bg-[#5D49AF] relative overflow-hidden">
      <div class="logBox h-[5vh]">
        <img class="h-full" src="@/assets/svg/Wait/logo.png" />
      </div>
      <div class="absolute titleBox w-full flex justify-around">
        <div class="flex items-center">
          <p class="text-[5.55vh] font-bold mr-[1.48vh]">家属等候大屏</p>
          <span class="text-[2.96vh] text-[#ccc] tracking-widest">({{ carouselCountDown }}s)</span>
        </div>
      </div>
      <div class="timeBox text-right">
        <p class="text-[3.14vh] font-medium leading-tight">{{ formatTime }}</p>
        <p class="text-[1.66vh]">{{ formatDate }}</p>
      </div>
    </nav>
    <main class="h-[calc(100vh-18.51vh)] p-[15px] pb-0 relative overflow-hidden" ref="mainRef">
      <div class="absolute top-[24px] left-1/2 -translate-x-1/2 w-[calc(100%-30px)]">
        <div class="bg-[#9A82FF] flex text-center" :style="carouselNav">
          <div class="w-[16%] font-semibold border-r">手术间</div>
          <div class="w-[20%] font-semibold border-r">患者姓名</div>
          <div class="w-[16%] font-semibold border-r">床号</div>
          <div class="w-[28%] font-semibold border-r">科室</div>
          <div class="w-[20%] font-semibold">状态</div>
        </div>
        <div :style="carouselWrap" class="border border-[#9A82FF] border-t-0" v-loading="isLoading">
          <template v-if="patientList['length']">
            <el-carousel direction="vertical" :autoplay="false" indicatorPosition="none" ref="carousel" @change="onCarouselChange">
              <el-carousel-item v-for="(item, index) in patientList" :key="index">
                <section class="carouselItemBox">
                  <template v-for="(subItem, index) in item">
                    <div :key="index" :style="carouselItemStyle">
                      <div class="flex text-center">
                        <div class="w-[16%] border-r text-[#333] font-semibold truncate">{{ subItem['RoomName'] }}</div>
                        <div class="w-[20%] border-r text-[#333] font-semibold truncate">{{ subItem['PatientName'] }}</div>
                        <div class="w-[16%] border-r text-[#333] font-semibold truncate">{{ subItem['BedNo'] }}</div>
                        <div class="w-[28%] border-r text-[#333] font-semibold truncate">{{ subItem['DeptName'] }}</div>
                        <div class="w-[20%] text-[#333] font-semibold" :style="{ color: `${textWaitToColor(subItem['ProcStatusName'])}` }">
                          {{ subItem['ProcStatusName'] }}
                        </div>
                      </div>
                    </div>
                  </template>
                </section>
              </el-carousel-item>
            </el-carousel>
          </template>
        </div>
      </div>

      <div class="absolute bottom-2 left-1/2 -translate-x-1/2 flex">
        <template v-for="(item, index) in patientList">
          <div class="w-3 h-3 rounded-full bg-[#D8D8D8] mx-1" :class="{ '!bg-[#8C8D92]': index == activeIndex }" :key="index" />
        </template>
      </div>
    </main>
    <footer class="h-[7.4vh] flex items-center justify-around bg-[#5D49AF] overflow-hidden">
      <div class="flex items-center">
        <div class="logBox w-[15vh] h-[3.7vh] mr-[1.48vh]">
          <img class="h-full" src="@/assets/svg/Wait/footText.png" />
        </div>
        <p class="text-[2.59vh]">请勿吸烟，请照顾好自己随身携带的物品，请耐心等待，我们将竭诚为您服务</p>
      </div>
    </footer>
  </section>
</template>

<script>
import { getAnesPatientList } from '@/api/waitList';
import { Carousel, CarouselItem, Notification } from 'element-ui';
import dayjs from 'dayjs';
import { statusToTxt, textWaitToColor } from '@/utils/common';
import Stomp from 'stompjs';
const { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD } = window.globalMQ;

export default {
  data() {
    return {
      isLoading: true,
      mainRefHeight: 0,
      showItemNum: 8,
      carouselNav: {},
      carouselWrap: {},
      carouselItemStyle: {},
      patientList: [],
      currentDateTime: dayjs().format('YYYY-MM-DD HH:mm dddd'),
      dateTimer: null,
      carouselCountDown: 10,
      carouselTimer: null,
      activeIndex: 0,
      getDataTimer: null,
      popupMsg: '',
      synth: window.speechSynthesis,
    };
  },
  methods: {
    statusToTxt,
    textWaitToColor,
    onGetPageData() {
      let today = dayjs().format('YYYY-MM-DD');
      today = '2024-06-06';
      getAnesPatientList(today)
        .then(res => {
          this.patientList = [];
          if (res['Data']['length']) {
            for (let index = 0; index < res['Data'].length; index++) {
              const element = res['Data'][index];
              const groupIndex = parseInt(index / this.showItemNum);
              if (this.patientList[groupIndex]) {
                this.patientList[groupIndex].push(element);
              } else {
                this.patientList[groupIndex] = [element];
              }
            }
            if (!this.carouselTimer) {
              this.onCarouselTimer();
            }
          } else {
            clearInterval(this.carouselTimer);
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    onCarouselTimer() {
      this.$nextTick(() => {
        this.carouselTimer = setInterval(() => {
          this.carouselCountDown -= 1;
          if (this.carouselCountDown == 0) {
            this.$refs.carousel.next();
            this.carouselCountDown = 10;
          }
        }, 1000);
      });
    },
    onCalculate() {
      // 根据展示数量计算高度
      this.mainRefHeight = parseInt(this.$refs.mainRef.clientHeight - 15 - 40);
      const rowHeight = this.mainRefHeight / (this.showItemNum + 1);
      this.carouselNav = {
        'font-size': `${(rowHeight * 0.53).toFixed(2)}px`,
        'line-height': `${rowHeight.toFixed(2)}px`,
      };
      this.carouselWrap = {
        height: `${(rowHeight * this.showItemNum).toFixed(2)}px`,
      };
      this.carouselItemStyle = {
        'line-height': `${rowHeight.toFixed(2)}px`,
        'font-size': `${(rowHeight * 0.5).toFixed(2)}px`,
      };
    },
    onCarouselChange(index) {
      this.activeIndex = index;
    },
    setRabitMQ() {
      this.client = Stomp.client(MQTT_SERVICE);
      this.connect();
    },
    connect: function () {
      const headers = {
        login: MQTT_USERNAME,
        passcode: MQTT_PASSWORD,
      };
      this.client.connect(headers, this.onConnected, this.onFailed);
    },
    onConnected: function () {
      this.client.subscribe('/exchange/DeviceExchange/SignsNonStandard', this.responseCallback);
    },
    responseCallback: function (frame) {
      try {
        if (frame.body) {
          let data = JSON.parse(frame.body);
          this.popupMsg = data['msg'];
        }
      } catch (e) {
        console.log(e);
      }
    },
    onFailed: function (frame) {
      console.log('MQ Failed: ' + frame);
      setTimeout(() => {
        this.client = Stomp.client(MQTT_SERVICE);
        Stomp.over(this.client);
        this.connect();
      }, 5000);
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.onCalculate();

      // 每秒更新一次当前时间
      this.dateTimer = setInterval(() => {
        this.currentDateTime = dayjs().format('YYYY-MM-DD HH:mm dddd');
      }, 10000);

      this.onGetPageData();
      this.getDataTimer = setInterval(() => {
        this.onGetPageData();
      }, 35000);
      window.addEventListener('resize', this.onCalculate);
      this.setRabitMQ();
      // setTimeout(() => {
      //   this.popupMsg = `请0的家属到手术室门口接病人`;
      // }, 1000);
    });
  },
  components: {
    'el-carousel': Carousel,
    'el-carousel-item': CarouselItem,
  },
  watch: {
    popupMsg(newVal) {
      if (newVal) {
        const h = this.$createElement;
        Notification({
          title: '呼叫信息',
          message: h('i', { style: 'color: teal;font-size:24px' }, newVal),
          duration: 12000,
        });
        if (this.synth) {
          console.log(this.synth);
          const utterance = new SpeechSynthesisUtterance([newVal, newVal, newVal].join(''));
          utterance.rate = 0.6;
          const voices = this.synth.getVoices();
          const selectedVoice = voices.find(voice => voice.lang === 'zh-CN');
          if (selectedVoice) {
            utterance.voice = selectedVoice;
          }

          // 添加 onend 事件处理器
          utterance.onend = function () {
            this.popupMsg = '';
            Notification.colseAll();
            console.log('Speech has finished.');
          };

          this.synth.speak(utterance);

          // 等待语音列表加载完成
          const checkVoices = () => {
            if (this.synth.getVoices().length !== 0) {
              clearInterval(voicesCheckInterval);
            }
          };

          const voicesCheckInterval = setInterval(checkVoices, 100);
        }
      }
    },
  },
  computed: {
    formatDate() {
      const timeArr = this.currentDateTime.split(' ');
      let weekName = '星期一';
      if (timeArr[2] == 'Tuesday') {
        weekName = '星期二';
      }
      if (timeArr[2] == 'Wednesday') {
        weekName = '星期三';
      }
      if (timeArr[2] == 'Thursday') {
        weekName = '星期四';
      }
      if (timeArr[2] == 'Friday') {
        weekName = '星期五';
      }
      if (timeArr[2] == 'Saturday') {
        weekName = '星期六';
      }
      if (timeArr[2] == 'Sunday') {
        weekName = '星期日';
      }
      return `${timeArr[0]} ${weekName}`;
    },
    formatTime() {
      return this.currentDateTime.split(' ')[1];
    },
  },
  beforeDestroy() {
    // 清除定时器
    clearInterval(this.dateTimer);
    clearInterval(this.carouselTimer);
    clearInterval(this.getDataTimer);
    // 组件销毁前移除 resize 事件监听器
    window.removeEventListener('resize', this.onCalculate);
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-carousel) {
  height: 100%;
  .el-carousel__container,
  .el-carousel__item {
    height: 100%;
    .carouselItemBox {
      > div:nth-child(odd) {
        background: #fff;
      }
      > div:nth-child(even) {
        background: #f5f8ff;
      }
    }
  }
}
</style>
