<template>
  <section></section>
</template>

<script>
export default {
  data() {
    return {
      popupMsg: '',
      synth: window.speechSynthesis,
    };
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.popupMsg = `请您的家属到手术室门口接病人${Date.now()}`;
      }, 1000);
    });
  },
  watch: {
    popupMsg(newVal) {
      if (newVal) {
        console.log(newVal);
        this.speakText(newVal);
      }
    },
  },
  methods: {
    speakText(text) {
      if (this.synth) {
        // 清除之前的语音合成
        this.synth.cancel();

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

            // 创建 SpeechSynthesisUtterance 实例
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.rate = 0.6;
            const selectedVoice = voices.find(voice => voice.lang === 'zh-CN');
            if (selectedVoice) {
              utterance.voice = selectedVoice;
            }

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

            // 播放语音
            this.synth.speak(utterance);
          }
        };

        // 定期检查语音列表是否加载完成
        const voicesCheckInterval = setInterval(checkVoices, 100);
      }
    },
  },
};
</script>
