<template>
  <div class="playWnd" :id="`playWnd${itemId}`"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import VideoPlugin from "./video_isc_plugin.js"
import {
	getVideoItemInfoPoliceCameraItemApi
} from "@/api/modules/workTicket";
import { ElMessage } from 'element-plus'
import { GlobalStore } from "@/stores";
const props = defineProps({
  devList: {
    type: Array,
    default: () => []
  },
  type: {
    type: String,
    default: ''
  },
  itemId: {
    type: String,
    required: true
  },
  equipmentDialog: {
    type: Boolean,
    default: false
  }
})

const store = GlobalStore();
const layout = ref('1x1')
const videoPlugin = ref(null)

// 方法
const getPreviewUrl = (row) => {
  const tempCode = row.monitoringNumber
  const param = {
    cameraIndexCode: tempCode,
    type: window.location.protocol.includes("https") ? "wss" : "ws",
    transmode: 1,
    itemId: row.itemId,
    projectSn: row.projectSn,
  }
  return getVideoItemInfoPoliceCameraItemApi(param)
}

const play = (row) => {
  getPreviewUrl(row).then((res) => {
    if (res.code !== 200 && !res.result.videoInfo) {
      ElMessage.warning("获取视频流失败！")
      return
    }
    
    const dataList = [
      {
        ...row,
        ...res.result.videoInfo,
        ...res.result.config,
        serialNumber: res.result.videoInfo.monitoringNumber,
        // defaultStreamType: 2,
      }
    ]
    
    videoPlugin.value.initPlugin(
      props.itemId, 
      res.result.config.appId, 
      res.result.config.appSecret, 
      res.result.config.ip, 
      res.result.config.port, 
      dataList, 
      layout.value
    )
    .then(() => {
      console.log('插件初始化成功')
    })
    .catch(error => {
      console.error('插件初始化失败:', error)
    })
  })
}

// 生命周期
onMounted(() => {
  videoPlugin.value = new VideoPlugin()
  
  let tempLayout = "2x2"
  if (props.type === "company") {
    tempLayout = "4x6"
  }
  if (props.type.includes("x")) {
    tempLayout = props.type
  }
  layout.value = tempLayout
  
  if (props.devList.length > 0) {
    props.devList.forEach(element => {
      play(element)
    })
  }
})

onBeforeUnmount(() => {
  if (videoPlugin.value) {
    videoPlugin.value.unInitPlugin()
  }
})

// 监听器
// watch(() => props.devList, (newVal) => {
//   if (newVal.length > 0) {
//     newVal.forEach(element => {
//       play(element)
//     })
//   }
// })

watch(() => props.equipmentDialog, (newVal) => {
  if (videoPlugin.value) {
    if (newVal) {
      videoPlugin.value.hidePluginWindow()
    } else {
      videoPlugin.value.showPluginWindow()
    }
  }
})
</script>

<style scoped>
.playWnd {
  width: 100%;
  height: 100%;
}
</style>