<template>
  <ContentWrap>
    <el-row>
      <el-col :span="5" style="height: 80vh">
        <el-tree
          style="height: 55vh"
          :data="list"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          highlight-current
          class="camera-tree"
        />
        <ptz @childTriggerParent="reVideo" v-if="cameraId" :cameraId="cameraId" />
      </el-col>
      <el-col :span="19">
        <div class="container">
          <el-button-group>
            <el-button :size="2" @click="updateTopNum(1)" type="primary">
              <Icon :size="20" icon="fa-solid:expand"
            /></el-button>
            <el-button type="primary" @click="updateTopNum(2)">
              <Icon :size="20" icon="fa-solid:th-large"
            /></el-button>
            <el-button type="primary" @click="updateTopNum(3)">
              <Icon :size="20" icon="fa-solid:th"
            /></el-button>
          </el-button-group>  
        </div>

        <el-row v-for="rowIndex in topNum" :key="rowIndex">
          <el-col
            :class="((rowIndex-1)*topNum +colIndex)!=cameraIndex?'dashed':'dashed-click'"
            v-for="colIndex in topNum"
            :key="colIndex"
            :span="24 / topNum"
            :style="{ height: videoHeight }"
            @click="clickCameraFun((rowIndex-1)*topNum +colIndex)"
          >
          
          <div v-if="((rowIndex-1)*topNum +colIndex)==cameraIndex" class="floating-text">
            <Icon :size="15" icon="ep:circle-close" @click="deleteCameraFun((rowIndex-1)*topNum +colIndex)"/>
          </div>
    
            <Camera v-if="getCameraId((rowIndex - 1) * topNum + colIndex)!== 0"
            :cameraId="getCameraId((rowIndex-1)*topNum +colIndex)" :ref="'camera'+((rowIndex-1)*topNum +colIndex)" :ptzShow="false" />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </ContentWrap>
</template>

<script setup lang="ts">
import Camera from '@/components/camera/camera.vue'

import { ref } from 'vue';
import ptz from '@/components/camera/ptzNotFlow.vue'
import { CameraApi, CameraVO } from '@/api/logistics/camera'
/** 相机 列表 */
defineOptions({ name: 'Camera' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const cameraId = ref()
const list = ref([]) // 列表的数据
const topNum = ref(2) // 默认值
// 目前选择的cameraIndex
const cameraIndex = ref()
// 用户是否选择视频
const clickCamera = ref(false)
const CameraMap = ref<Map<number, number | undefined>>()
const reVideo = async (cameraId: number) => { 
  if (CameraMap.value) {
    
    for (let i = 1; i <= topNum.value * topNum.value; i++) {
      if (CameraMap.value.get(i) === cameraId) {
        deleteCameraFun(i)
        CameraMap.value?.set(i, cameraId)
        
      }
    }
  }
}
/** 查询列表 */
const getTree = async () => {
  try {
    const tree = await CameraApi.getTree()
    list.value = tree
  } finally {
  }
}
const selectedNodeId = ref<string | null>(null)
// 关闭视频
const deleteCameraFun = (index)=>{
  console.log("删除摄像头 index:",index );
  
  clickCamera.value = true
  CameraMap.value?.delete(index)
  cameraIndex.value = index
  cameraId.value = null
}
// 点击视频墙的一部分
const clickCameraFun = (index)=>{

if (CameraMap.value?.get(index)) {
  clickCamera.value = true
} else {
  clickCamera.value = false
}

cameraIndex.value = index
cameraId.value = CameraMap.value?.get(index)
}
// 点击树的节点
const handleNodeClick = (data: any) => {
  if (data.id != null) {
    // 如果用户点击了视频节点，则修改该视频节点
    if(clickCamera.value){
      deleteCameraFun(cameraIndex.value)
      CameraMap.value?.set(cameraIndex.value, data.id)
    }else{
        // 用户未选择视频节点，找到第一个空闲位置设置 cameraId
        for (let i = 1; i <= topNum.value * topNum.value; i++) {
        if (CameraMap.value?.get(i) === undefined) {
          CameraMap.value?.set(i, data.id)
          cameraIndex.value = i // 更新 cameraIndex 为新设置的位置
          break
        }
      }
    }
    console.log(CameraMap.value);
    
    // selectedNodeId.value = data.id
    // console.log('Selected Camera ID:', data.id)
    // cameraId.value = data.id
    // document.cookie = 'cameraStreetCameraId=' + data.id + ';'
  }
}
// 获取 cookie 的值
// 获取之前所有Cameramap
const getCookie = (name) => {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
  if (match && !isNaN(Number(match[2]))) {
    cameraId.value = parseInt(match[2], 10) // 将字符串转换为数字
  }
  return match ? match[2] : null
}

// 根据 topNum 动态调整 tab 个数
const tabCount = computed(() => {
  return Math.ceil(list.value.length / (topNum.value * topNum.value))
})

const updateTopNum = (num: number) => {
  topNum.value = num
}
// 根据 tab 索引获取对应的数据项
const getItemsForTab = (tabIndex: number) => {
  const startIndex = (tabIndex - 1) * topNum.value
  const endIndex = startIndex + topNum.value
  return list.value.slice(startIndex, endIndex)
}


// 计算 videoHeight
const videoHeight = computed(() => {
  const tabHeight = (74 * window.innerHeight) / 100 // 63vh
  const rowHeight = tabHeight / topNum.value
  return `${rowHeight}px`
})

// 获取每个单元格的 cameraId
const getCameraId = (index) => {
  return CameraMap.value?.get(index) ??0
}
/** 初始化 **/
onMounted(() => {
  getTree()
  CameraMap.value = new Map()
  for (let i = 1; i <= 9; i++) {
    CameraMap.value?.set(i, undefined)
  }
  getCookie('cameraStreetCameraId')
})
</script>

<style scoped>

.floating-text {
  
  right: 0;
  position: absolute; /* 绝对定位 */
  top: 0;
  z-index: 999;
  background-color: rgba(255, 255, 255, 0);
  padding: 5px;
  font-size: 14px;
  color: #cfcfcf93;
}
.dashed {
  position: relative; /* 父容器需要设置为相对定位 */
  background-color: #555555; /* 深灰色 */
  border: 1px solid #8e888874; /* 暗色 */
}

.dashed-click {
  position: relative; /* 父容器需要设置为相对定位 */
  background-color: #555555; /* 深灰色 */
  border: 2px solid #e86a6a96; /* 暗红色 */
}
.container {
  display: flex;
  justify-content: flex-end; /* 将按钮组放到右侧 */
  padding-bottom: 10px; /* 可选，增加间距 */
}
</style>
