<template>
  <div>
    <el-row align="middle">
      <span style="margin-left: 10px">通道名称：</span>
      <el-select
        v-model="channelId"
        placeholder="请选择"
        @change="changeChannel"
        size="small"
        style="width: 200px"
      >
        <el-option
          v-for="option in channelList"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <span style="margin: 0 10px 0 30px">开启拉流:</span>
      <el-switch
        v-model="pushStream"
        active-color="#13ce66"
        inactive-color="#c4c6c9"
        :disabled="channelId === ''"
        @change="startPushStream"
      />
      <span style="margin: 0 10px 0 30px">开启直播录像:</span>
      <el-switch
        v-model="playrecord"
        active-color="#13ce66"
        inactive-color="#c4c6c9"
        :disabled="channelId === ''"
        @change="handleStartPlayRecord"
      />
    </el-row>
    <player
      ref="playerRef"
      :playerInfo="playinfo"
      class="components-container"
      style="margin-top: 10px; width: 90%; height: 80vh"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import Player from './easyplayer.vue'

import { startPlay, closeStream, listChannel } from '@/api/pms/video/channel'
import { startPlayRecord } from '@/api/pms/video/record'

// 定义props
const props = defineProps({
  device: {
    type: Object,
    default: null
  }
})

// 定义响应式数据
const playerRef = ref(null)
const deviceInfo = ref({})
const deviceId = ref('')
const channelId = ref('')
const streamId = ref('')
const ssrc = ref('')
const playurl = ref('')
const playrecord = ref(false)
const playrecording = ref(false)
const playing = ref(false)
const pushStream = ref(false)
const retrycount = ref(0)
const channelList = ref([])

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 99,
  deviceSipId: null,
  channelSipId: null
})

// 播放信息
const playinfo = reactive({
  playtype: 'play'
})

// Watch device prop变化
watch(
  () => props.device,
  (newVal, oldVal) => {
    console.log('device 发生变化>>>>>>>>>>>>>>>', newVal?.channelId)
    deviceInfo.value = newVal
    if (newVal?.channelId) {
      channelId.value = newVal.channelId
      changeChannel()
    }
    if (newVal && newVal.deviceId !== 0) {
      queryParams.deviceSipId = newVal.serialNumber
      deviceId.value = newVal.serialNumber
    }
  },
  { immediate: true }
)

// 组件挂载时执行
onMounted(() => {
  if (props.device) {
    queryParams.deviceSipId = props.device.serialNumber
    deviceId.value = props.device.serialNumber
    getList()
    playinfo.deviceId = props.device.serialNumber
  }
})

// 组件销毁前执行
onBeforeUnmount(() => {
  console.log('beforeDestroy')
  closeDestroy(false)
})

// 查询监控设备通道信息列表
const getList = () => {
  listChannel(queryParams).then((response) => {
    channelList.value = response.list.map((item) => {
      return { value: item.channelSipId, label: item.channelName }
    })
  })
}

// 通道切换
const changeChannel = () => {
  console.log('channelId>>>>>>>>>>>>>>>', channelId.value)
  playinfo.channelId = channelId.value
  startPlayer()
}

// 超时回调
const TimeoutCallback = () => {
  closeDestroy(false)
  retrycount.value = 0
  setTimeout(() => {
    startPlayer()
  }, 1000)
}

// 开启/关闭推流
const startPushStream = () => {
  if (!channelId.value) {
    console.log('开始通道: [' + channelId.value + ']')
    return
  }
  console.log('推流状态: [' + pushStream.value + ']')
  if (pushStream.value) {
    startPlayer()
  } else {
    closeDestroy(true)
  }
}

// 开启/关闭录像播放
const handleStartPlayRecord = () => {
  console.log('录像状态: [' + playrecord.value + ']')
  closeDestroy(true)
  setTimeout(() => {
    startPlayer()
  }, 500)
}

// 开启直播播放器
const startPlayer = () => {
  if (!channelId.value) {
    return
  }
  deviceId.value = queryParams.deviceSipId
  if (playing.value) {
    closeDestroy(false)
  }

  // 注册回调
  playerRef.value?.registercallback('loadingTimeout', TimeoutCallback)
  playerRef.value?.registercallback('delayTimeout', TimeoutCallback)

  if (playrecord.value) {
    // 录像播放
    startPlayRecord(deviceId.value, channelId.value).then((response) => {
      // const res = response.data
      streamId.value = response.streamId
      playurl.value = response.playurl
      playerRef.value?.play(playurl.value)
      playing.value = true
      playrecording.value = true
      pushStream.value = true
    })
  } else {
    // 直播播放
    startPlay(deviceId.value, channelId.value).then((response) => {
      console.log('开始播放：' + deviceId.value + ' : ' + channelId.value)
      streamId.value = response.streamId
      playurl.value = response.playurl
      playerRef.value?.play(playurl.value)
      playing.value = true
      playrecording.value = false
      pushStream.value = true
    })
  }
}

// 关闭流
const handleCloseStream = (force) => {
  if (force) {
    if (playing.value && streamId.value) {
      closeStream(deviceId.value, channelId.value, streamId.value).then((res) => {
        streamId.value = ''
        ssrc.value = ''
        playurl.value = ''
        pushStream.value = false
      })
      playing.value = false
      playrecording.value = false
    }
  } else {
    if (playrecording.value === true) {
      return
    }
    if (playing.value && streamId.value) {
      console.log('关闭推流: [' + streamId.value + ']')
      closeStream(deviceId.value, channelId.value, streamId.value).then((res) => {
        streamId.value = ''
        ssrc.value = ''
        playurl.value = ''
        pushStream.value = false
      })
      playing.value = false
      playrecording.value = false
    }
  }
}

// 关闭并销毁
const closeDestroy = (force) => {
  handleCloseStream(force)
  playerRef.value?.destroy()
}

// 销毁播放器
const destroy = () => {
  playerRef.value?.destroy()
}

// 暴露给父组件的方法
defineExpose({
  destroy,
  channelId,
  closeDestroy,
  playing,
  changeChannel
})
</script>
