<template>
  <div class="p5" style="width: 100%; height: calc(100vh - 84px)" v-loading="loading">
    <div id="TrajectoryEarth" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup name="equipmentGPS">
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { getFootNote } from '@/api/equipment/index';

const route = useRoute();
const loading = ref(true);
let earthInstance = null;
let data = [
  {
    'locLongitude': 106.45637808828741,
    'locLatitude': 29.5597535878972,
    'locAltitude': 0
  }
];

// 获取轨迹数据
const getTrajectoryData = async () => {
  try {
    // 从URL参数中获取clientId、projectId和userId
    const { clientId, projectId, userId } = route.query;

    if (!clientId || !projectId || !userId) {
      ElMessage.warning('缺少必要参数，请检查传入的参数');
      return;
    }

    loading.value = true;
    const res = await getFootNote({ clientId, projectId, userId });

    if (res && res.code === 200 && res.data && res.data.length > 0) {
      data = res.data;
      // 渲染轨迹
      if (earthInstance && earthInstance.viewer) {
        renderRange(data);
      }
    } else {
      ElMessage.warning('暂无轨迹数据');
    }
  } catch (error) {
    console.error('获取轨迹数据失败:', error);
    ElMessage.error('获取轨迹数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 创建地球
const createEarth = () => {
  if (!window.YJ) {
    ElMessage.error('YJ库未加载，请检查依赖');
    return;
  }

  window.YJ.on({
    ws: true
    // host: getIP(), // 资源所在服务器地址
    // username: this.loginForm.username, // 用户名
    // password: md5pass, // 密码
  })
    .then((res) => {
      // 创建地球实例
      earthInstance = new YJ.YJEarth('TrajectoryEarth');
      window.Earth3 = earthInstance;

      // 开启右键和左键点击事件
      YJ.Global.openRightClick(window.Earth3);
      YJ.Global.openLeftClick(window.Earth3);

      // 设置初始视角
      const view = {
        position: {
          lng: 102.03643298211526,
          lat: 34.393586474501,
          alt: 11298179.51993155
        },
        orientation: {
          heading: 360,
          pitch: -89.94481747201486,
          roll: 0
        }
      };

      YJ.Global.CesiumContainer(window.Earth3, {
        compass: false //罗盘
      });
      // 加载底图
      loadBaseMap(earthInstance.viewer);

      // 可以取消注释以下代码来设置初始视角
      // YJ.Global.flyTo(earthInstance, view);
      // YJ.Global.setDefaultView(earthInstance.viewer, view)

      // 地球创建完成后获取并渲染轨迹数据
      getTrajectoryData();
    })
    .catch((err) => {
      console.error('初始化地球失败:', err);
      ElMessage.error('初始化地球失败，请稍后重试');
    });
};

// 加载底图
const loadBaseMap = (viewer) => {
  if (!viewer || !Cesium) {
    ElMessage.error('Cesium库未加载，请检查依赖');
    return;
  }

  try {
    // 创建瓦片提供器
    const imageryProvider = new Cesium.UrlTemplateImageryProvider({
      url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
      fileExtension: 'png',
      minimumLevel: 0,
      maximumLevel: 18,
      projection: Cesium.WebMercatorProjection,
      credit: new Cesium.Credit('卫星图数据来源')
    });

    // 添加图层到视图
    viewer.imageryLayers.addImageryProvider(imageryProvider);
  } catch (err) {
    console.error('加载底图失败:', err);
    ElMessage.error('加载底图失败');
  }
};

// 渲染轨迹
const renderRange = (data) => {
  if (!data || data.length === 0) {
    ElMessage.warning('无轨迹数据可渲染');
    return;
  }

  if (!earthInstance || !earthInstance.viewer) {
    ElMessage.error('地球实例未初始化');
    return;
  }

  try {
    const positions = data.map((point) => {
      return Cesium.Cartesian3.fromDegrees(point.locLongitude, point.locLatitude, point.locAltitude || 0);
    });

    const entity = earthInstance.viewer.entities.add({
      polyline: {
        positions: positions,
        width: 5,
        material: Cesium.Color.RED,
        clampToGround: true
      }
    });

    // 调整视角以适应轨迹
    earthInstance.viewer.flyTo(entity);
  } catch (err) {
    console.error('渲染轨迹失败:', err);
    ElMessage.error('渲染轨迹失败');
  }
};

//
onMounted(() => {
  createEarth();
});

//
onUnmounted(() => {
  if (earthInstance) {
    earthInstance.destroy();
    earthInstance = null;
    window.Earth3 = null;
  }
});
</script>

<style></style>
