<template>
  <div>
    <!--     loop autoplay muted hidden-->
    <!--    @ended="audioEnd"-->
    <audio id="neworder" ref="audio" controls hidden>
      <source :src="neworder" type="audio/mpeg" />
    </audio>
    <audio id="outStock" ref="audio" controls hidden>
      <source :src="outStock" type="audio/mpeg" />
    </audio>
  </div>
</template>

<script>
  function playTimes(elem, times, start = 0) {
    // let start = 0;
    elem.play();
    // console.log(start, times);
    elem.addEventListener("ended", function () {
      start++;
      // console.log(start);
      if (start === times) {
        elem.pause();
      } else {
        playTimes(elem, times, start);
      }
    });
  }
  import neworder from "@/assets/mp3/neworder.mp3";
  import outStock from "@/assets/mp3/out_stock.mp3";
  import { mapGetters, mapActions } from "vuex";
  import { NoticeSetting } from "@/api/System";
  import { apiUrl } from "@/config/settings";
  export default {
    name: "Websocket",
    data() {
      return {
        wsServer: apiUrl.wsServer,
        socket: "",
        neworder: neworder,
        outStock: outStock,
      };
    },
    computed: {
      ...mapGetters({
        enterprise: "MUser/enterprise",
      }),
      newOrdertip() {
        if (this.$store.getters["MUser/audioSet"].length) {
          return this.$store.getters["MUser/audioSet"].find(
            (item) => item.type === 1
          );
        } else {
          return {
            name: "新订单",
            type: 1,
            voice_radio: 1,
            voice_type: 1,
          };
        }
      },
      outOrdertip() {
        if (this.$store.getters["MUser/audioSet"].length) {
          return this.$store.getters["MUser/audioSet"].find(
            (item) => item.type === 2
          );
        } else {
          return {
            name: "出库单",
            type: 2,
            voice_radio: 1,
            voice_type: 1,
          };
        }
      },
    },
    mounted() {
      this.NoticeSetting();
      this.init();
    },
    destroyed() {
      console.log("destroyed");
      // 关闭提示
      this.$notify.close();
      // 销毁监听
      this.socket.close();
      this.socket.onclose = this.close;
    },

    methods: {
      ...mapActions({
        changeAudioSet: "MUser/changeAudioSet",
      }),
      //  获取语音设置详情
      async NoticeSetting() {
        const { data } = await NoticeSetting();
		if(!data.content){
			return
		}
        if (data.content.length) {
          this.changeAudioSet(data.content);
        }
      },
      init() {
        if (typeof WebSocket === "undefined") {
          alert("您的浏览器不支持socket");
        } else {
          // 实例化socket
          this.socket = new WebSocket(this.wsServer);
          // 监听socket连接
          this.socket.onopen = this.open;
          // 监听socket错误信息
          this.socket.onerror = this.error;
          // 监听socket消息
          this.socket.onmessage = this.getMessage;
        }
      },
      open() {
        console.log("socket连接成功");
        this.send();
      },
      error() {
        console.log("socket连接错误");
      },
      getMessage(res) {
        const obj = JSON.parse(res.data);
        console.log(obj);
        if (obj.state) {
          // 新订单提示
          if (obj.data === "有新订单了") {
            // 如果没有新订单权限就不提醒新订单
            if (!this.$accessCheck(this.$Access.newOrderList)) {
              return;
            }
            let audio = document.getElementById("neworder");
            if (this.newOrdertip.voice_radio !== 4) {
              if (audio !== null) {
                //muted 规定视频输出应该被静音
                audio.muted = false;
                audio.loop = false;
                audio.play();
                if (this.newOrdertip.voice_radio === 1) {
                  playTimes(audio, 1);
                } else if (this.newOrdertip.voice_radio === 2) {
                  playTimes(audio, 3);
                }
                if (this.newOrdertip.voice_radio === 3) {
                  // playTimes(audio, 100000);
                  audio.loop = true;
                }
              }
              this.$notify({
                type: "success",
                title: "有新订单了",
                message: "点击关闭按钮，关闭提示语音",
                position: "bottom-right",
                duration: this.newOrdertip.voice_radio === 3 ? 0 : 2000,
                onClose: () => {
                  if (audio !== null) {
                    audio.pause();
                  }
                },
              });
            }
          } else if (obj.data === "有新出库单了") {
            // 如果没有出库单权限就不提醒【有新出库单了】
            if (!this.$accessCheck(this.$Access.InventoryOut)) {
              return;
            }
            let audio = document.getElementById("outStock");
            // 新出库单提示
            if (this.outOrdertip.voice_radio !== 4) {
              if (audio !== null) {
                //muted 规定视频输出应该被静音
                audio.muted = false;
                audio.loop = false;
                audio.play();
                if (this.outOrdertip.voice_radio === 1) {
                  playTimes(audio, 1);
                } else if (this.outOrdertip.voice_radio === 2) {
                  playTimes(audio, 3);
                }
                if (this.outOrdertip.voice_radio === 3) {
                  // playTimes(audio, 100000);
                  audio.loop = true;
                }
              }
              this.$notify({
                type: "success",
                title: "有新出库单了",
                message: "点击关闭按钮，关闭提示语音",
                position: "bottom-right",
                duration: this.outOrdertip.voice_radio === 3 ? 0 : 2000,
                onClose: () => {
                  if (audio !== null) {
                    audio.pause();
                  }
                },
              });
            }
          }
        }
      },
      send() {
        const params = {
          controller: "NewOrder",
          action: "createConnect",
          params: {
            platfrom: apiUrl.SAASTAG,
            shop_id: this.enterprise.enterpriseId,
            userId: this.enterprise.userCenterId,
          },
        };
        this.socket.send(JSON.stringify(params));
      },
      close(e) {
        console.log("connection closed (" + e.code + ")");
        console.log("socket已经关闭");
      },
    },
  };
</script>

<style scoped></style>
