<script setup>
import { inject, onBeforeUnmount } from "vue"
import { useFence } from "@/hooks/useFence"

const { THREE } = VgoMap

// 可以使用pinia等管理全局数据，这里只是方便演示, 直接注入了上层提供的数据
const map = inject("map")
const polygonDataAll = inject("polygonDataAll")

// 为了演示，随意取了几个模型，获取模型形状包含的所有点位
const inFencePoints = polygonDataAll.value.filter(p => {
  return ['保卫部', '智慧大楼', '能源部办公楼'].includes(p.name)
}).map(p => p.points).flat()

// 获取生成围栏函数，高60，并封顶
const { generateFence } = useFence({
  height: 60,
  isCloseTop: true,
})

// 建立一个围栏组，便于销毁所有围栏
const fenceGroup = new THREE.Group()
map.value.scene.add(fenceGroup)

// 生成围栏，并添加到围栏组
const fence = generateFence(getMinBoxPoints(inFencePoints))
fenceGroup.add(fence)

// 清理围栏
onBeforeUnmount(() => {
  fenceGroup.dispose()
})

// 根据所有包含的点位, 获取最小的矩形顶点数组
function getMinBoxPoints(points) {
  const box = new THREE.Box2()
  box.setFromPoints(points)
  return [
    new THREE.Vector3(box.min.x, box.min.y, 0), // 左下角 (0)
    new THREE.Vector3(box.max.x, box.min.y, 0), // 右下角 (1)
    new THREE.Vector3(box.max.x, box.max.y, 0), // 右上角 (2)
    new THREE.Vector3(box.min.x, box.max.y, 0)  // 左上角 (3)
  ];
}
</script>

<template>
  <div class="fence"></div>
</template>