<template>
  <div class="outer">
    <div style="padding: 20px;">

      <Alarm v-if="isShow" :size="50" :backgroudColor="color">!</Alarm>

    </div>

    <div class="video">
      <video ref="video" autoplay></video>
    </div>
    <div></div>
    <!-- <img src="../image/感叹号.png" alt="error" class="alarmOn" /> -->

    <!-- <button @click="startRecording">开始录像</button>
    <button @click="stopRecording">停止录像</button> -->
    <!-- <video ref="recordedVideo" controls></video> -->
  </div>
</template>

<script>
import Alarm from "@/element/Alarm.vue";
export default {
  name: "User",
  data() {
    return {
      mediaRecorder: null,
      recordedChunks: [],
      videoDevices: [],
      selectedDeviceId: null,
      isShow: false,
      color: "red",
    };
  },
  components: {
    Alarm,
  },
  async mounted() {
    this.webSocketInit();
    await this.getVideoDevices();
    await this.startRecording();
  },
  methods: {
    issues() {
      this.$message({
        showClose: true,
        message: "警告：用户出现异常！",
        type: "error",
        duration: 0,
      });
    },
    alarmSound() {
      var audio = new Audio();
      audio.src = require("../image/警报声.mp3");
      audio.play();
    },
    webSocketInit() {
      const that = this;
      if (typeof WebSocket === undefined) {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8081/danger/get";
        let socket;

        if (socket != null) {
          socket.close();
          socket = null;
        }

        socket = new WebSocket(socketUrl);
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        socket.onmessage = function (message) {
          console.log(message.data);
          if (message.data == "二级") {
            that.isShow = true;
            that.color = "#CCCC00";
            that.issues();
            that.solve();
          } else if (message.data == "三级") {
            that.isShow = true;
            that.color = "red";
            //延时执行
            setTimeout(() => {
              that.alarmSound();
            }, 500);
            that.issues();
            
          }

          socket.onerror = function () {
            console.log("websocket发生了错误");
          };
          socket.onclose = function () {
            console.log("websocket已关闭");
          };
        };
      }
    },
    async solve(){
      setTimeout(() => {
        this.isShow = false;
        this.color = "red";
      }, 5000*12);
    },
    async getVideoDevices() {
      const devices = await navigator.mediaDevices.enumerateDevices();
      this.videoDevices = devices.filter(
        (device) => device.kind === "videoinput"
      );
      if (this.videoDevices.length > 0) {
        this.selectedDeviceId =
          this.videoDevices.find((device) => device.label.includes("usb")) !==
          null
            ? this.videoDevices.find((device) => device.label.includes("usb"))
            : this.videoDevices[0].deviceId;
      }
      console.log(this.selectedDeviceId);
    },
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            deviceId: this.selectedDeviceId
              ? { exact: this.selectedDeviceId }
              : undefined,
          },
        });
        this.$refs.video.srcObject = stream;

        this.mediaRecorder = new MediaRecorder(stream);
        // this.mediaRecorder.ondataavailable = (event) => {
        //   if (event.data.size > 0) {
        //     this.recordedChunks.push(event.data);
        //   }
        // };
        this.mediaRecorder.start();
      } catch (err) {
        console.error("Error accessing media devices.", err);
      }
    },
    // stopRecording() {
    //   this.mediaRecorder.stop();
    //   const blob = new Blob(this.recordedChunks, { type: 'video/webm' });
    //   this.$refs.recordedVideo.src = URL.createObjectURL(blob);
    //   this.recordedChunks = [];
    // },
  },
};
</script>

<style lang="less" scoped>
.outer {
  background-image: url("../image/back.png");
  display: flex;
  .video {
    width: 100%;

    display: flex;
    justify-content: center;
    align-items: center;
  }
}
video {
  width: 100%;
  max-width: 900px;
}
</style>