<template>
  <div class="p5" style="width: 100%; height: calc(100vh - 84px)" v-loading="loading">
    <!-- 返回按钮区域 -->
    <div style="position: absolute; top: 20px; left: 20px; z-index: 100; display: flex; gap: 10px">
      <el-button type="primary" icon="ArrowLeft" @click="handleBack">返回</el-button>
      <el-button type="success" icon="Play" @click="handleStart">开始</el-button>
      <el-button type="warning" icon="Pause" @click="handleStop">停止</el-button>
    </div>
    <div id="TrajectoryEarth" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup name="equipmentGPS">
import { ref, onMounted, onUnmounted } from 'vue';
import { ElButton } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router'; // 补充导入useRouter
import { getFootNote } from '@/api/equipment/index';
import { ModelPathMover } from './index.js';

const route = useRoute();
const router = useRouter(); // 初始化router
const loading = ref(true);
let modelMover = null;

// 返回上一页
const handleBack = () => {
  router.back();
};

// 开始轨迹运动
const handleStart = () => {
  if (modelMover && typeof modelMover.start === 'function') {
    try {
      modelMover.start();
      ElMessage.success('轨迹已开始播放');
    } catch (error) {
      console.error('启动轨迹失败:', error);
      ElMessage.error('启动轨迹失败');
    }
  } else {
    ElMessage.warning('轨迹未初始化，请稍后再试');
  }
};

// 停止轨迹运动
const handleStop = () => {
  if (modelMover && typeof modelMover.stop === 'function') {
    try {
      modelMover.stop();
      ElMessage.success('轨迹已停止');
    } catch (error) {
      console.error('停止轨迹失败:', error);
      ElMessage.error('停止轨迹失败');
    }
  } else {
    ElMessage.warning('轨迹未初始化，请稍后再试');
  }
};

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, gpsType } = route.query;

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

    loading.value = true;
    // 确保gpsType转换为数字类型，以便正确传递给后端
    const gpsTypeNum = parseInt(gpsType, 10);
    const res = await getFootNote({ clientId, projectId, userId, gpsType: gpsTypeNum });

    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((item) => {
      return {
        lon: item.locLongitude,
        lat: item.locLatitude,
        height: item.locAltitude || 0,
        name: item.name || ''
      };
    });

    modelMover = new ModelPathMover(window.Earth3.viewer, {
      // modelUrl: './air.glb', // 模型URL
      positions: positions,
      speed: 50, // 移动速度
      loop: true, // 循环运动
      iconUrl: '/image/Foot.png', // 模型上方图标
      baseHeight: 10 // 外部传入的统一高度（米）
    });
    window.modelMover = modelMover;
  } catch (err) {
    console.error('渲染轨迹失败:', err);
    ElMessage.error('渲染轨迹失败');
  }
};

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

onUnmounted(() => {
  if (modelMover) {
    modelMover.stop(); // 组件卸载时停止轨迹
    modelMover = null;
  }
  if (earthInstance) {
    earthInstance.destroy();
    earthInstance = null;
    window.Earth3 = null;
  }
});
</script>

<style></style>
