<script lang="ts" setup>
import { h, onMounted, ref, watch } from 'vue';
import { NButton, NSelect, NSpace, useMessage } from 'naive-ui';
import { create3D } from '@/api/utils/cesium';
import {
  cesiumToLongitudeAndLatitude,
  toConvertLongitudeAndLatitude,
  toProjectionCoordinates
} from '@/api/utils/coordinateUtil';
import { getElevationFromRays } from '@/api/utils/cesiumUtil';
import bluePersonIcon from '../../../assets/blueperson.png';
import redPersonIcon from '../../../assets/redperson.png';
import { getModel } from '@/api/utils/cesiumModel';
import { getModelAllApi, getPointAllPersonApi } from '@/api';

let viewer: any = null;
const value = ref(null);
let polygonCoordList: any = [];
const personList = ref([]);
const personShow = ref(false);
const personValue = ref('');
let personEntity: any; // 创建蓝色标签
let entityId: any;
const formData = ref({
  cardId: '',
  personId: '',
  realName: ''
})
const options = ref();
const message = useMessage();
// 模型
function add3dtiles() {
  const CesiumConfig = {
    defaultAccessToken:
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NTE1OTUxOS1jNTc5LTQwNmMtOWU5My1jNTI3NTIyYzAxNTUiLCJpZCI6MjUwODM5LCJpYXQiOjE3Mjk5MjE1MzV9.xromwPD3oA1e0YsWV035DE5KmYvivkC6fxt344vwObA'
  };

  Cesium.Ion.defaultAccessToken = CesiumConfig.defaultAccessToken;

  viewer = new Cesium.Viewer('cesiumcontainer', {
    geocoder: false,
    homeButton: false,
    infoBox: false,
    animation: false,
    fullscreenButton: false,
    enableCompass: true, // 启用指南针
    enableCompassOuterRing: true, // 启用指南针外环
    sceneModePicker: false,
    timeline: false,
    navigationHelpButton: false,
    baseLayerPicker: false,
    enableZoomControls: false, // 禁用缩放控件
    enableDistanceLegend: false, // 禁用比例尺
    selectionIndicator: false
  });

  viewer.scene.globe.depthTestAgainstTerrain = true;
  viewer.cesiumWidget.creditContainer.style.display = 'none';
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

  getModel().then(item => {
    create3D(viewer, item, 0);
  });
}

async function createRedLine() {
  // polygonCoordList = [
  //   { id:'1', name: '李四1', x: 122.04635389346244, y: 37.488806671581244, },
  //   { id:'2', name: '李四2', x: 122.04889441347648, y: 37.489652755263485, },
  //   { id:'3', name: '李四3', x: 122.04866968206369, y: 37.49009150670726, },
  //   { id:'4', name: '李四4', x: 122.04742994760802, y: 37.48962490165547, },
  //   { id:'5', name: '李四5', x: 122.0462100510411,  y: 37.48919903307283 },
  //   { id:'6', name: '李四6', x: 122.04604253116817, y: 37.48950907923646 },
  //   { id:'7', name: '李四7', x: 122.04722854327062, y: 37.48991898274459 },
  //   { id:'8', name: '李四8', x: 122.04706661542971, y: 37.49024792859644}
  // ];

  let res = await getPointAllPersonApi();
  polygonCoordList = res.data.data;

  for (let i = 0; i < polygonCoordList.length; i++) {
    const cartographic = Cesium.Cartographic.fromDegrees(polygonCoordList[i].lon, polygonCoordList[i].lat);
    const height = await getElevationFromRays(cartographic, viewer);
    const adjustedHeight = height;
    const cartesian = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, adjustedHeight);

    // 创建人员图标实体
    personEntity = viewer.entities.add({
      id: `person_${i}`, // 为人员图标实体设置特定前缀的ID
      position: cartesian,
      billboard: {
        image: bluePersonIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        scale: 0.5,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
      },
      // 存储人员数据
      personData: {
        index: i,
        info: polygonCoordList[i]
      }
    });

    // 创建标签框背景实体
    const entity = viewer.entities.add({
      position: cartesian,
      billboard: {
        image: new URL('../../../assets/titlePerson.png', import.meta.url).href,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        scale: 0.5,
        pixelOffset: new Cesium.Cartesian2(0, -30), // 位置在图标上方
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
      }
    });

    entity.billboard.width = 220; // 直接设置宽度
    entity.billboard.height = 50; // 直接设置高度

    // 创建名字标签实体
    viewer.entities.add({
      position: cartesian,
      label: {
        text: polygonCoordList[i].realName,
        font: 'bold 14px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        pixelOffset: new Cesium.Cartesian2(0, -36), // 位置在标签框上方
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
        scaleByDistance: new Cesium.NearFarScalar(1000, 1, 5000, 0.5),
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000)
      }
    });
  }
}

function selectChange(item:any) {
  console.log('222',item);
  personValue.value = item;
}

function handleSearch() {
  if(personValue.value == '') {
    message.info('请选择您要查询的人员');
    return;
  } else {
    personList.value = polygonCoordList.filter((item:any) => item.personId == personValue.value);
    personShow.value = true;
    message.success('查询成功');
  }
}

function handleReset() {
  viewer.entities.values.forEach((entity: any) => {
    if (typeof entity.id === 'string' && entity.id.startsWith('person_')) {
      entity.billboard.image = bluePersonIcon;
    }
  });
  value.value = null;
  personList.value = [];
  personShow.value = false;
  message.success('重置成功');
}

// 点击隐藏弹框
function personsShow() {
  if(personShow.value == true) {
    personShow.value = false;
    viewer.entities.values.forEach((entity: any) => {
    if (typeof entity.id === 'string' && entity.id.startsWith('person_')) {
      entity.billboard.image = bluePersonIcon;
    }
  });
  }
}
// 设置员工类型
function getPersonTypeName(type: number): string {
  switch(type) {
    case 1:
      return '员工';
    case 2:
      return '访客';
    default:
      return '没有该类型';
  }
}
// 获取最新模型
async function search() {
  let res = await getModelAllApi();
  options.value = res.data.data;
}

onMounted(() => {
  add3dtiles();
  search();
  setTimeout(() => {
    createRedLine();
  }, 2000);

  // 当前选中的人员图标
  let currentSelectedPerson = null;

  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

  // 鼠标点击事件
  handler.setInputAction(function (click: any) {
    const pickedObject = viewer.scene.pick(click.position);
    // 检查是否点击了人员图标
    if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id)) {
      personList.value = [];
      entityId = pickedObject.id.id;
      // if(entityId == )
      // 检查是否是人员图标实体
      if (typeof entityId === 'string' && entityId.startsWith('person_')) {

        // 重置所有人员图标为蓝色
        viewer.entities.values.forEach((entity: any) => {
          if (typeof entity.id === 'string' && entity.id.startsWith('person_')) {
            entity.billboard.image = bluePersonIcon;
          }
        });
        // 设置当前点击的图标为红色
        const clickedEntity = viewer.entities.getById(entityId);
        if (clickedEntity) {
          clickedEntity.billboard.image = redPersonIcon;
          currentSelectedPerson = clickedEntity;
        }
        personShow.value = true;
        if (pickedObject.id.personData) {
          console.log(pickedObject.id.personData);
          personList.value.push({
            personId: pickedObject.id.personData.info.personId,
            realName: pickedObject.id.personData.info.realName,
            remark: pickedObject.id.personData.info.remark,
            phone: pickedObject.id.personData.info.phone,
            deptName: pickedObject.id.personData.info.deptName,
            personType: pickedObject.id.personData.info.personType,
            cardId: pickedObject.id.personData.info.cardId,
          })
        }

      }
      else {
        // 点击了其他地方，关闭信息框
        // personEntity(); // 重置所有人员图标为蓝色
      }
    } else {
      personList.value = [];
      personShow.value = false;

      if (personShow.value == false) {
        const clickedEntity = viewer.entities.getById(entityId);
        clickedEntity.billboard.image = bluePersonIcon;  
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
</script>

<template>
  <div class="track-page">
    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center">
      <NSpace>
        <div style="display: flex; align-items: center">
          人员姓名
          <NSpace vertical style="width: 200px; margin-left: 10px">
            <NSelect v-model:value="value" :options="options" label-field="realName" value-field="personId" @update:value="selectChange" />
          </NSpace>
        </div>

        <NButton color="#2198f2" style="padding: 0px 17px; border-radius: 5px; margin-left: 40px" @click="handleSearch">
          查询
        </NButton>
        <NButton style="padding: 0px 17px; border-radius: 5px" @click="handleReset">重置</NButton>
      </NSpace>
    </div>

    <!-- cesium -->
    <div id="cesiumcontainer">
      <div class="personMessage" v-if="personShow == true">
        <div style="display: flex; justify-content: flex-start align-items: center; margin-bottom: 10px;">
          <div style="width:90%; margin: 0; font-size: 16px;"><span>人员信息</span>
            <div class="person1"></div>
          </div>

          <button id="close-info" @click="personsShow()"
            style="background: none; border: none; color: white; cursor: pointer; font-size: 18px; margin-left: 10px;">&times;</button>
        </div>
        <div style="line-height: 1.8;" v-for="item in personList">
          <p class="title1"><strong class="title2">姓名:</strong> {{ item.realName }}</p>
          <p class="title1"><strong class="title2">定位卡号:</strong> {{ item.cardId }}</p>
          <p class="title1"><strong class="title2">人员类型:</strong> {{ getPersonTypeName(item.personType) }}</p>
          <p class="title1"><strong class="title2">电话:</strong> {{item.phone}}</p>
          <p class="title1"><strong class="title2">部门:</strong> {{item.deptName}}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#home {
  width: 100%;
  height: 100%;
}

#cesiumcontainer {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

.personMessage {
  width: 450px;
  height: 250px;
  position: absolute;
  padding: 15px 20px;
  color: white;
  font-family: sans-serif;
  font-size: 14px;
  pointer-events: auto;
  z-index: 1;
  top: 100px;
  left: 30%;
  background-image: url('@/assets/person2.png');
  background-size: 100% 100%;
}

.title1 {
  margin-top: 5px;
}

.title2 {
  font-size: 16px;
  color: #29d7fb;
  margin-right: 10px;
}

span {
  position: absolute;
  z-index: 4;
  left: 30px;
  top: 10px;
}

.person1 {
  width: 85%;
  height: 40px;
  background-image: url('@/assets/person1.png');
  background-size: 100% 100%;
  position: absolute;
  left: 6px;
  top: 20px;
}
</style>
