<template>
  <view class="h-full w-full">
    <LiveVideo
      v-if="address"
      :key="address"
      :url="address"
      :type="type"
    ></LiveVideo>
  </view>
</template>
<script>
import { http } from '@/api/index.js'
import LiveVideo from '@/components/live-video/index.vue'

export default {
  components: {
    LiveVideo,
  },
  props: {
    id: {
      type: [String, Number],
    },
  },
  data() {
    return {
      address: '',
      type: '',
      expires: '',
      timer: null,
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      if (!this.id) return
      try {
        const { data } = await http.get(`/api/devices/${this.id}/live`)
        const resData = data.data
        const { address, type, expires } = resData
        this.address = address
        this.type = type
        this.expires = expires
        this.reinit()
      } catch (error) {
        console.log(error)
      }
    },
    //根据剩余秒数重新执行init
    reinit() {
      if (!this.expires || this.expires <= 0) return
      this.timer = setTimeout(() => {
        this.init()
      }, this.expires * 1000)
    },
  },
  //销毁清理定时器
  beforeDestroy() {
    this.timer && clearTimeout(this.timer)
  }
}
</script>
