<template>
  <div class="">
    <el-row :gutter="20">
      <!-- 区域树 -->
      <el-col :lg="6" :xs="24" >
        <el-card shadow="hover">
          <el-input v-model="pointName" placeholder="请输入监控点名称" prefix-icon="Search" clearable />
          <el-tree ref="areaTreeRef" class="mt-2" node-key="areaId" :data="areaOptions" :filter-node-method="filterNode"
            :props="{ label: 'areaName', children: 'children' }" :expand-on-click-node="false" highlight-current
            default-expand-all @node-click="handleNodeClick" />
        </el-card>
      </el-col>
      <el-col :lg="18" :xs="24">
          <JessibucaPlayer  class="player" :videoUrl="mediaInfo.streamUrl" :show-paint="false" :title="playerName" />
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import { getPointsTree, getPointMediaByPointId } from '@/api/manage/monitorPoint'
const pointName = ref('')
const areaOptions = ref([])
const areaTreeRef = ref<ElTreeInstance>();
const playerName = ref('')
const mediaInfo = ref({
  streamUrl: ''
})
onMounted(() => {
  getPointsTree({}).then(({ code, data }) => {
    if (code === 200) {
      areaOptions.value = [data || {}]
      handleNodeClick(getFirstLeafAreaId(data))
    }
  })
})
const getFirstLeafAreaId=(data) =>{
    let firstLeafAreaId = null;
    function traverseTree(node) {
        if (node.children && node.children.length > 0) {
            for (let child of node.children) {
                traverseTree(child);
            }
        } else if (!node.children || node.children.length === 0) { // This is a leaf node
            if (!firstLeafAreaId) {
                firstLeafAreaId = node;
            }
        }
    }
    traverseTree(data);
    return firstLeafAreaId;
}

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.areaLevel === 4 && data.areaName.indexOf(value) !== -1;
};
watchEffect(
  () => {
    areaTreeRef.value?.filter(pointName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);
/** 节点单击事件 */
const handleNodeClick = (val) => {
  if (val.areaLevel === 4) {
    playerName.value = val.areaName
    getPointMediaByPointId({ pointId: val.areaId }).then(({ code, data }) => {
      if (code === 200) {
        mediaInfo.value = data
      }
    })
  }
};

</script>
<style lang="scss" scoped>
.player{
  margin-top: 10px;
    height: 600px;
    width: calc(100% - 20px);

}
</style>
