import { ref } from 'vue';
import { getPointAllPersonApi } from '@/api';
import bluePersonIcon from '@/assets/blueperson.png';
import { getElevationFromRays } from '../cesiumUtil';

let personEntity: any;
const iconEntities = ref<any[]>([]);
const pins: any = [];
// 点位图标
export async function iconPoint(viewer: any, pins: any) {
  // // 批量移除实体
  iconEntities.value.forEach(item => {
    viewer.entities.remove(item.labelExtity);
    viewer.entities.remove(item.entity);
  });

  for (const item of pins) {
    if (item.entity) {
      viewer.entities.remove(item.entity);
    }
    const cartographic = Cesium.Cartographic.fromDegrees(item.position.lon, item.position.lat);

    const height = await getElevationFromRays(cartographic, viewer);

    const cartesian = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height);

    item.entity = viewer.entities.add({
      position: cartesian,
      billboard: {
        image: item.image,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        scale: 0.5,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
      },
      properties: {
        type: item.type
      }
    });
    allEntities.push(item.entity);

    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
      },
      properties: {
        type: item.type
      }
    });
    entity.billboard.width = 220; // 直接设置宽度
    entity.billboard.height = 50; // 直接设置高度
    allEntities.push(entity);

    // 创建名字标签实体
    const labelEntit = viewer.entities.add({
      position: cartesian,
      label: {
        text: item.name,
        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)
      },
      properties: {
        type: item.type
      }
    });
    allEntities.push(labelEntit);

    iconEntities.value.push({
      labelExtity: labelEntit,
      entity
    });
  }
  return { pins, allEntities };
}
