<template>
  <video
    class="hlsVideo"
    ref="hlsVideo"
    autoplay
    muted
    :style="'width:' + width + ';height:' + height"
    v-if="code"
  ></video>
</template>

<script>
export default {
  // 名称
  name: "Hls",
  // 使用组件
  components: {},
  // 传入参数
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    code: {
      type: String,
      default: "",
    },
  },
  emits: {},
  // 数据
  data() {
    return {
      socket: null,
      isReady: false,
      devs: [],
      hls: null,
      currDevCode: null,
    };
  },
  // 函数
  methods: {
    _play: function () {
      if (Hls.isSupported()) {
        var self = this;
        self.$nextTick(function () {
          var video = self.$refs.hlsVideo;
          self.hls && self.hls.destroy();
          video.volume = 1.0;
          self.hls = new Hls();
          self.hls.on(Hls.Events.MANIFEST_PARSED, () => {
            self.$refs.video.play();
          });
          self.hls.loadSource(
            // `http://192.168.10.25:1935/hls/${self.currDevCode}/index.m3u8`
            `http://192.168.1.18:1935/hls/${self.code}/index.m3u8`
          );
          self.hls.attachMedia(video);
        });
      }
    },
    onReady() {
      this.send({ action: "loadDevs" });
    },
    onDevChoosed(index) {
      this.currDevCode = this.devs[index].code;
      this._play();
    },
    onMessage(data) {
      var result = eval(data);
      if (result.code === "fail") {
        if (result.message) {
          this.$message.error(result.message);
        } else {
          this.$message.error("操作失败");
        }
      } else if (result.action == "loadDevs") {
        this.devs = result.object;
      }

      console.log("result", result);
    },
    send(message) {
      if (!this.isReady) {
        alert("this socket is not ready!");
        return;
      }
      this.socket.send(JSON.stringify(message));
    },
  },
  // 生命周期钩子
  beforeCreate() {
    // 创建前
  },
  created() {
    // 创建后
    var self = this;
    if (window.WebSocket) {
      self.socket = new WebSocket("ws://" + window.location.host + "/api.ws");
      //建立websocket连接
      self.socket.onopen = function () {
        self.isReady = self.socket.readyState == 1;
        self.onReady();
      };
      self.socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        self.onMessage(data);
      };
      self.socket.onclose = function (event) {
        self.isReady = false;
      };
      self._play();
    }
  },
  beforeMount() {
    // 渲染前
  },
  mounted() {
    // 渲染后
  },
  beforeUpdate() {},
  updated() {},
  watch: {
    code() {
      this._play();
    },
  },
};
</script>

<style lang="less" scoped>
.hlsVideo {
  object-fit: fill;
}
</style>