<template>
  <div
    class="disk-touch"
    @touchstart="ontouchstart"
    @touchmove="ontouchmove"
    @touchend="ontouchend"
  >
  </div>
</template>

<script>
import qs from 'qs';
export default {
  name: 'DiskTouch',
  props: {
    info: {
      type: Object,
      default: null,
    },
  },
  async fetch() {
    this.info && (await this.initBusinessChannelWebSocket());
  },
  watch: {
    info: '$fetch',
  },
  methods: {
    genSendDataList(event, action) {
      const width = 720;
      const height = 1280;
      return Array.from(event.changedTouches).map((item) => ({
        data: {
          action,
          count: event.touches.length,
          pointerId: item.identifier,
          x: (
            item.clientX *
            (width / this.$el.getBoundingClientRect().width)
          ).toFixed(2),
          y: (
            item.clientY *
            (height / this.$el.getBoundingClientRect().height)
          ).toFixed(2),
        },
        type: 'event',
      }));
    },
    initBusinessChannelWebSocket() {
      this?._wx?.close();
      const { internetHttps, localIp, sn, cardToken } = this.info;
      const url = `wss://${internetHttps}/businessChannel${qs.stringify(
        {
          cardIp: localIp,
          token: cardToken,
          type: 'directives',
        },
        { addQueryPrefix: true, encode: false },
      )}`;
      const ws = new WebSocket(url);
      ws.addEventListener('open', (e) => {
        ws.send(JSON.stringify({ type: 'getVsStatus' }));
        ws.send(
          JSON.stringify({ type: 'bitRate', data: { bitRate: 1243000 } }),
        );
        ws.send(
          JSON.stringify({
            type: 'forwardMsg',
            data: { code: '3000', desc: '询问是否有在控制' },
          }),
        );
        ws.send(
          JSON.stringify({
            type: 'getPhoneSize',
          }),
        );
      });
      ws.addEventListener('error', (e) => {});
      ws.addEventListener('message', (event) => {
        var result =
          typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
        console.log(result);
        if (result.type === 'getPhoneSize') {
          this.$emit('sizeChange', result.data);
        }
      });
      ws.addEventListener('close', (e) => {});
      this.$once('hook:beforeDestroy', () => {
        ws.close();
      });
      this._ws = ws;
    },
    ontouchstart(event) {
      this.genSendDataList(event, 0).forEach((item) =>
        this._ws.send(JSON.stringify(item)),
      );
    },
    ontouchmove(event) {
      this.genSendDataList(event, 2).forEach((item) =>
        this._ws.send(JSON.stringify(item)),
      );
    },
    ontouchend(event) {
      this.genSendDataList(event, 1).forEach((item) =>
        this._ws.send(JSON.stringify(item)),
      );
    },
  },
};
</script>


<style lang="scss" scoped>
.disk-touch {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}
</style>

