<template>
  <div class="preview-map">
    <cesium-map :options="options" @init="initMap">
    </cesium-map>
    <toolbar :viewer="viewerRef" class="toolbar"></toolbar>
  </div>
</template>

<script setup>
import { shallowRef } from 'vue';
import * as Cesium from 'cesium';
import CesiumMap from '@/components/CesiumMap/index.vue';
import { useEventBus } from '@/components/CesiumMap/mixins/useEventBus';
import Toolbar from './Toolbar';
import DialogPropertyGrid from './DialogPropertyGrid';
import { setPropertyData } from './DialogPropertyGrid/property';
import FeatureGroundPrimitive from '@/components/CesiumMap/FeatureGroundPrimitive';

const viewerRef = shallowRef(null)
const options = ref({
  setView: {
    // duration: '默认',
    x: 102.70862516,
    y: 25.01198423,
    z: 30000,
    heading: 0, // 偏航角
    pitch: -90, // 俯仰角
    roll: 0 // 翻滚角
  },
  ditu: 'tianditu', // 底图选择
  isTerrainProvider: true, // 启用地形
})
const showProperty = ref(false); // 控制属性面板的显示与隐藏
const propertyData = ref([])

const initMap = (v) => {
  viewerRef.value = v;
  console.log('地图已初始化', v);

  const bus = useEventBus(viewerRef.value)
  // bus.on('hoverTest', ({ screenPosition }) => {
  //   console.log('hoverTest 事件触发屏幕位置:', screenPosition);
    
  // });
  bus.onScreen(Cesium.ScreenSpaceEventType.LEFT_CLICK, ({ position }) => {
    console.log('左键点击屏幕位置:', position);
    // 如果点击的是实体，则获取该实体的属性数据
    const pickedObjectList = viewerRef.value.scene.drillPick(position);
    if (pickedObjectList.length > 0) {
      // 遍历拾取实体，获取第一个非辅助实体
      for (let index = 0; index < pickedObjectList.length; index++) {
        const obj = pickedObjectList[index];
        if (obj && obj.id && obj.id instanceof Cesium.Entity) {
          // 辅助实体的name都以'__'开头，不识别
          if(obj.id.name?.indexOf('__') === 0) {
            continue
          }
          // getPropertyData(obj.id);
          DialogPropertyGrid.show(obj.id, (data) => {
            // 更新实体属性
            setPropertyData(data, obj.id);
            // 调用接口
          })
          return
        } else if(obj.primitive && obj.primitive instanceof FeatureGroundPrimitive) {
          DialogPropertyGrid.show(obj.primitive, (data) => {
            // 更新实体属性
            setPropertyData(data, obj.primitive);
            // 调用接口
          })
        }
      }
    }
  })
};

</script>

<style lang="scss" scoped>
.preview-map {
  // z-index: 2;
  position: absolute;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
}
.toolbar {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translate(0, -50%);
}
.infobox {
  position: absolute;
  right: 20px;
  top: 20px;
  // width: 600px;
}
</style>