<template>
  <div class="img-container">
    <!-- <img :src="url" v-if="url" /> -->
    <canvas class="canvas_box" ref="canvas" v-if="url" width="960" height="540" />
    <div class="image-slot" v-else>
      <i class="el-icon-video-camera"></i>
      <span>无信号</span>
      <span>{{ cameraData.name }}</span>
    </div>
  </div>
</template>
<script>
import { debounce, throttle } from 'lodash-es'
export default {
  props: {
    cameraData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      url: '',
      ws: null,
      startTime: null,
      speed: 4,
      presetIndex: 1,
    }
  },
  watch: {
    cameraData: {
      handler(val) {
        if (val.id) {
          this.updateEvent({ id: val.id }, true)
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.$EventBus.$off('updateSendParam')
    this.$EventBus.$on('updateSendParam', (data, state) => {
      if (data.id === this.cameraData.id) {
        this.updateEvent(data, state)
      }
    })
  },
  beforeDestroy() {
    this.closeHandler()
  },
  methods: {
    init(str) {
      // this.socketList[`ws_${this.cameraData.id}`];
      const host = VUE_APP_BASE_WS() + '/VideoOverWebSocket'
      // const host = 'wss://' + window.location.host + BASE_URL + '/VideoOverWebSocket'
      this.ws = new WebSocket(host)
      this.ws.onmessage = evt => {
        if (typeof evt.data === 'string') {
          console.log(JSON.parse(evt.data).Msg)
        } else {
          this.url = URL.createObjectURL(evt.data)
          this.$nextTick(() => {
            this.updateUrl()
          })
        }
      }
      this.handleSend(str)
      // console.log(window);
    },
    updateUrl() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      const img = new Image()
      // console.log('canvas', canvas.width, canvas.height)

      img.src = this.url
      img.onload = () => {
        // console.log('img', img.width, img.height)
        const canvasRatio = canvas.width / canvas.height
        const imgRatio = img.width / img.height
        if (imgRatio > canvasRatio) {
          // 图片宽高比大于画布宽高比，以宽度为基准进行缩放
          const newWidth = canvas.width
          const newHeight = newWidth / canvasRatio
          ctx.clearRect(0, 0, newWidth, newHeight)
          ctx.drawImage(img, 0, (canvas.height - newHeight) / 2, newWidth, newHeight)
        } else {
          // 图片宽高比小于等于画布宽高比，以高度为基准进行缩放
          const newHeight = canvas.height
          const newWidth = newHeight * canvasRatio
          ctx.clearRect(0, 0, newWidth, newHeight)
          ctx.drawImage(img, (canvas.width - newWidth) / 2, 0, newWidth, newHeight)
        }
      }
    },
    // 100),
    handleSend(str) {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(str)
      } else if (this.ws.readyState == WebSocket.CONNECTING) {
        // Wait for the open event, maybe do something with promises
        // depending on your use case. I believe in you developer!
        this.ws.addEventListener('open', () => this.handleSend(str))
      } else {
        // etc.
      }
    },
    updateEvent(data, state) {
      const param = JSON.stringify(data)
      if (this.ws && this.ws.readyState == 1) {
        this.handleSend(param)
      } else {
        this.init(param)
      }
      if (state) {
        setTimeout(() => {
          this.url = ''
        }, 500)
      }
    },
    closeHandler() {
      this.ws && this.ws.close()
      setTimeout(() => {
        if (this.url) URL.revokeObjectURL(this.url)
        this.url = ''
        this.ws.onclose = evt => {
          this.ws = null
          console.log('websocket已关闭')
        }
      }, 500)
    },
  },
}
</script>

<style lang="less" scoped>
.img-container {
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 100%;
    object-fit: fill;
    // display: block;
  }
  .canvas_box {
    width: 100%;
    height: 100%;
  }
  .image-slot {
    width: 100%;
    height: 100%;
    // background-color: #f5f7fa;
    color: #5bd6ff;
    font-size: 24px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-weight: 500;
    span {
      font-size: 16px;
    }
  }
}
</style>
