<template>
  <div class="container">
    <el-row id="earth" style="height: 100%; width: 100%; display: flex; position: relative">
      <el-col style="height: 100%; position: relative" :span="this.leftwidth">
        <div class="main-layout" v-on:mouseover="changeActive('2D')" @mousemove="getMouseLocation">
          <div id="2DcesiumContainer" class="map" @click="onMapClick"></div>
        </div>
      </el-col>
      <el-col style="height: 100%; position: relative" :span="24 - this.leftwidth">
        <div class="main-layout" v-on:mouseover="changeActive('3D')" @mousemove="getMouseLocation">
          <div id="3DcesiumContainer" class="map" @click="onMapClick"></div>
        </div>
      </el-col>
      <el-tabs type="border-card" v-model="activeName" tab-position="left" class="menu" :stretch="true"
        @tab-click="legendClick">
        <!-- <el-tab-pane name="first">
          <el-tooltip placement="right" effect="light" slot="label">
            <span slot="content" class="item">标绘</span>
            <span><i class="el-icon-wind-power"></i></span>
          </el-tooltip>
        </el-tab-pane> -->
        <!-- <el-tab-pane name="second">
          <el-tooltip placement="right" effect="light" slot="label">
            <span slot="content" class="item">模型</span>
            <span><i class="el-icon-receiving"></i></span>
          </el-tooltip>
          <Model @selectModel="selectModel" :isShow="isShow"></Model>
        </el-tab-pane> -->
        <!-- <el-tab-pane name="third">
          <el-tooltip placement="right" effect="light" slot="label">
            <span slot="content" class="item">测量</span>
            <span><i class="el-icon-discount"></i></span>
          </el-tooltip>
        </el-tab-pane> -->
        <el-tab-pane name="fouth">
          <el-tooltip placement="right" effect="light" slot="label">
            <span slot="content" class="item">测想定</span>
            <span><i class="el-icon-house"></i></span>
          </el-tooltip>
          <el-table :data="situation">
            <el-table-column label="名称" prop="xdname" width="150px"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" @click="getJson(scope.row)">导入</el-button>
                <!-- <el-button type="primary" @click="saveJson()">保存</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div class="buttons">
        <el-button icon="el-icon-full-screen" circle @click="ismax()"></el-button>
        <el-button icon="el-icon-house" circle @click="home()"></el-button>
        <el-button icon="el-icon-plus" circle @click="big()"></el-button>
        <el-button icon="el-icon-minus" circle @click="small()"></el-button>
        <el-button icon="el-icon-download" circle @click="saveJson()"></el-button>
      </div>
    </el-row>
    <div v-if="isShow" class="modeltooltip" ref="modeltooltip">{{ modeltooltip }}</div>
  </div>
</template>
<script>
import screenfull from "screenfull";
import fireController from "@/api/fireController.js";
import { getToken } from "@/utils";
import axios from "axios";
import Model from "@/views/situation/Model.vue";
import satelliteModel from '@/assets/model/satelite.glb';
import missileModel from '@/assets/model/basic_missle.glb';
import thaadModel from '@/assets/model/anti-aircraft_gun_fire_control_radar_vehicle.glb';
import centerModel from '@/assets/model/himars_animated.glb';
import { mapGetters } from "vuex";
export default {
  components: {
    Model
  },
  computed: {
    ...mapGetters([
      "dimension"
    ])
  },
  data() {
    return {
      save : false,
      situation: [],
      nameIdList:[],
      websocket: null,
      leftwidth: 12,
      unit: [],
      satellite: [],
      center: [],
      move_data: {},
      viewer2D: null,
      viewer3D: null,
      mousevalue: null,
      // 选中的点
      selectedMarker: null,
      // 以前的标记点坐标
      oldPosition: null,
      activeName: null,
      currentLab: {
        index: -1,
        isActive: false
      },
      url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
      isShow: false,
      handler3D: null,
      handler2D: null,
      image: null,
      modeltooltip: null,
      id: 1
    };
  },
  watch: {
    dimension: {
      handler: function (val, oldVal) {
        console.log(val)
        if (val == 2) {
          this.leftwidth = 24;
        } else if (val == 3) {
          this.leftwidth = 0;
        } else if (val == 5) {
          this.leftwidth = 12;
        }
      },
    },
  },
  created() {
    this.getData();
  },
  mounted() {
    this.cesiumInit();
    this.pointMove();
    this.startWebSocket();
  },
  beforeDestroy() {
    // 在组件销毁前，关闭WebSocket连接
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.websocket.close();
    }

  },
  methods: {
    startWebSocket() {
      this.websocket = new WebSocket('ws://localhost:8765');

      this.websocket.onopen = () => {
        console.log('WebSocket连接已建立！');

      };

      this.websocket.onmessage = (event) => {
        // 处理从WebSocket服务器接收到的消息
        const data = JSON.parse(event.data);
        console.log('收到消息：', data);


        // 在这里处理接收到的数据，更新Vue组件的数据等操作
      };

      this.websocket.onerror = (error) => {
        console.error('WebSocket错误：', error);
      };

      this.websocket.onclose = () => {
        console.log('WebSocket连接已关闭！');
      };
    },
    async saveJson() {
      if(this.save){
        const jsonData = JSON.stringify(this.jsonData);
            const blob = new Blob([jsonData], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = this.jsonData.xdname + '.json';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
      }
      else{
        this.$message("请先导入想定文件！！！")
      }
    
   
      // await axios
      //   .post("http://localhost:8084/admin/online/onlineOperation/updateDatasource/main", {
      //     params: {
      //       datasourceId: "1656243335922192384",
      //       masterData: row,
      //       slaveData: {}
      //     }
      //   })
      //   .then((res) => {
      //     console.log("update successfully ");
      //   });
      //     const requestData = row
      //     if(this.websocket && this.websocket.readyState === WebSocket.OPEN){
      //       this.websocket.send(JSON.stringify(requestData));
      //     }
      //     else{
      //       this.startWebSocket();
      //       setTimeout(() => {
      //         this.websocket.send(JSON.stringify(requestData));
      // }, 2000);

      //     }

    },
    changeItemPosition(data) {

    },
    async getJson(row) {
      let redunit = [];
      let blueunit = [];
      let satellite = [];
      let center = [];
      // let fileInfoStr = row.blueunit;
      // let fileInfoArr = JSON.parse(fileInfoStr);
      // for (let i = 0; i < fileInfoArr.length; i++) {
      //   await axios
      //     .get("http://localhost:8084/admin/online/onlineOperation/downloadDatasource/main", {
      //       params: {
      //         datasourceId: "1656243335922192384",
      //         fieldName: "blueunit",
      //         asImage: false,
      //         dataId: row.id,
      //         filename: fileInfoArr[i].filename,
      //         Authorization: getToken(),
      //         MenuId: "1656244747347431424"
      //       }
      //     })
      //     .then((response) => {
      //       // 处理成功的响应
      //       blueunit.push(response.data);
      //     })
      //     .catch((error) => {
      //       // 处理错误
      //       console.error(error);
      //     });
      // }
      // fileInfoStr = row.redunit;
      // fileInfoArr = JSON.parse(fileInfoStr);

      // for (let i = 0; i < fileInfoArr.length; i++) {
      //   await axios
      //     .get("http://localhost:8084/admin/online/onlineOperation/downloadDatasource/main", {
      //       params: {
      //         datasourceId: "1656243335922192384",
      //         fieldName: "redunit",
      //         asImage: false,
      //         dataId: row.id,
      //         filename: fileInfoArr[i].filename,
      //         Authorization: getToken(),
      //         MenuId: "1656244747347431424"
      //       }
      //     })
      //     .then((response) => {
      //       // 处理成功的响应
      //       redunit.push(response.data);
      //     })
      //     .catch((error) => {
      //       // 处理错误
      //       console.error(error);
      //     });
      // }
      // fileInfoStr = row.center;
      // fileInfoArr = JSON.parse(fileInfoStr);

      // for (let i = 0; i < fileInfoArr.length; i++) {
      //   await axios
      //     .get("http://localhost:8084/admin/online/onlineOperation/downloadDatasource/main", {
      //       params: {
      //         datasourceId: "1656243335922192384",
      //         fieldName: "center",
      //         asImage: false,
      //         dataId: row.id,
      //         filename: fileInfoArr[i].filename,
      //         Authorization: getToken(),
      //         MenuId: "1656244747347431424"
      //       }
      //     })
      //     .then((response) => {
      //       // 处理成功的响应
      //       center.push(response.data);
      //     })
      //     .catch((error) => {
      //       // 处理错误
      //       console.error(error);
      //     });
      // }
      // fileInfoStr = row.satellite;
      // fileInfoArr = JSON.parse(fileInfoStr);

      // for (let i = 0; i < fileInfoArr.length; i++) {
      //   await axios
      //     .get("http://localhost:8084/admin/online/onlineOperation/downloadDatasource/main", {
      //       params: {
      //         datasourceId: "1656243335922192384",
      //         fieldName: "satellite",
      //         asImage: false,
      //         dataId: row.id,
      //         filename: fileInfoArr[i].filename,
      //         Authorization: getToken(),
      //         MenuId: "1656244747347431424"
      //       }
      //     })
      //     .then((response) => {
      //       // 处理成功的响应
      //       satellite.push(response.data);
      //     })
      //     .catch((error) => {
      //       // 处理错误
      //       console.error(error);
      //     });
      // }
      // const jsonData = {}
      //   id: row.id,
      //   xdname: row.xdname,
      //   type: row.type,
      //   creator: row.creator,
      //   createtime: row.createtime,
      //   bluecnt: row.bluecnt,
      //   target: row.target,
      //   starttime: row.starttime,
      //   steptime: row.steptime,
      //   blueunit: blueunit,
      //   redunit: redunit,
      //   satellite: satellite,
      //   center: center
      // };
     let fileInfoStr = row.xdfile;
     let fileInfoArr = JSON.parse(fileInfoStr);
      await axios
          .get("http://localhost:8084/admin/online/onlineOperation/downloadDatasource/main", {
            params: {
              datasourceId: "1656243335922192384",
              fieldName: "xdfile",
              asImage: false,
              dataId: row.id,
              filename: fileInfoArr[0].filename,
              Authorization: getToken(),
              MenuId: "1656244747347431424"
            }
          })
          .then((response) => {
            console.log('response.data :>> ', response.data);
            // // 处理成功的响应
            // jsonData = response.data
            blueunit = response.data.blueunit
            redunit = response.data.redunit
            satellite = response.data.satellite
            center = response.data.center
            this.save = true
                this.jsonData = {
        id: row.id,
        xdname: row.xdname,
        type: row.type,
        creator: row.creator,
        createtime: row.createtime,
        bluecnt: row.bluecnt,
        target: row.target,
        starttime: row.starttime,
        steptime: row.steptime,
        blueunit: blueunit,
        redunit: redunit,
        satellite: satellite,
        center: center
      }
          })
          .catch((error) => {
            // 处理错误
            console.error(error);
          });
      
      for(let i =0;i<blueunit.length;i++){
        this.markLocationbyJson(parseFloat(blueunit[i].pos.lat),parseFloat(blueunit[i].pos.lon),parseFloat(blueunit[i].pos.height),blueunit[i].name,"blue")
      }
      for(let i = 0;i<center.length;i++){
        let item = center[i]
        this.markLocationbyJson(parseFloat(item[center[i].name].properties.lat),parseFloat(item[center[i].name].properties.lon),parseFloat(item[center[i].name].properties.h),item.name,"center")
      }
      for(let i = 0;i<redunit.length;i++){
        this.markLocationbyJson(parseFloat(redunit[i].component_movementjson.properties.launch_lat),parseFloat(redunit[i].component_movementjson.properties.launch_lon),parseFloat(redunit[i].component_movementjson.properties.launch_h),redunit[i].name,"red")
        let point1 = {
          longitude : parseFloat(redunit[i].component_movementjson.properties.launch_lon),
          latitude : parseFloat(redunit[i].component_movementjson.properties.launch_lat),
          height :parseFloat(redunit[i].component_movementjson.properties.launch_h)
        }
        let point2 = {
          longitude : parseFloat(redunit[i].component_movementjson.properties.target_lon),
          latitude : parseFloat(redunit[i].component_movementjson.properties.target_lat),
          height : parseFloat(redunit[i].component_movementjson.properties.target_h)
        }
        this.markLine(point1,point2,"red")
      }
    },
    //获取所有数据
    getData() {
      this.getCenter();
      this.getSatellite();
      this.getUnit();
      this.getSituation();
    },
    // 获取场景想定数据
    getSituation() {
      let params = {
        datasourceId: "1656243335922192384",
        filterDtoList: [],
        pageParam: {
          pageNum: 1,
          pageSize: 10
        }
      };
      fireController.situation(this, params).then((res) => {
        this.situation = res.data.dataList;
      });
    },
    // 获取作战单元数据
    getUnit() {
      let params = {
        datasourceId: "1657931215497334784",
        filterDtoList: [],
        pageParam: {
          pageNum: 1,
          pageSize: 10
        }
      };
      fireController.unit(this, params).then((res) => {
        this.unit = res.data.dataList;
      });
    },
    // 获取指挥中心数据
    getCenter() {
      let params = {
        datasourceId: "1654421731512684544",
        filterDtoList: [],
        pageParam: {
          pageNum: 1,
          pageSize: 10
        }
      };
      fireController.center(this, params).then((res) => {
        this.center = res.data.dataList;
      });
    },
    // 获取预警卫星数据
    getSatellite() {
      let params = {
        datasourceId: "1654424480958648320",
        filterDtoList: [],
        pageParam: {
          pageNum: 1,
          pageSize: 10
        }
      };
      fireController.satellite(this, params).then((res) => {
        this.satellite = res.data.dataList;
      });
    },
    cesiumInit() {
      this.viewer2D = new this.Cesium.Viewer("2DcesiumContainer", {
        sceneMode: this.Cesium.SceneMode.SCENE2D,
        animation: false, // 是否显示时间轴动画
        baseLayerPicker: false,
        homeButton: false,
        geocoder: false,
        timeline: false,
        fullscreenButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        selectionIndicator: false,
        imageryProvider: new this.Cesium.UrlTemplateImageryProvider({
          url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
          layer: "tdtVecBasicLayer",
          style: "default",
          format: "image/png",
          tileMatrixSetID: "GoogleMapsCompatible",
          show: false
        })
      });

      this.viewer3D = new this.Cesium.Viewer("3DcesiumContainer", {
        animation: false, // 是否显示时间轴动画
        baseLayerPicker: false,
        homeButton: false,
        geocoder: false,
        timeline: false,
        fullscreenButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        selectionIndicator: false,
        // imageryProvider:  new this.Cesium.WebMapServiceImageryProvider({
        //   url: '/geoserver/map/wms',
        //     // 这里是自定义的图层名称
        //     layers: 'map',
        //     parameters: {
        //         service: 'WMS',
        //         format: 'image/png',
        //         transparent: true
        //     }
        // }),

        imageryProvider:
          // new this.Cesium.WebMapTileServiceImageryProvider({
          //     url: "http://10.170.16.95:8080/geoserver/gwc/service/wmts/rest/map:map/{style}/{TileMatrixSet}/{TileMatrixSet}:{TileMatrix}/{TileRow}/{TileCol}?format=image/png",
          //     layer: 'map:map',
          //     style: 'raster',
          //     format: 'image/png',
          //     tileMatrixSetID: 'EPSG:900913',      //一般使用EPSG:3857坐标系

          //   }),
          new this.Cesium.UrlTemplateImageryProvider({
            url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
            layer: "tdtVecBasicLayer",
            style: "default",
            format: "image/png",
            tileMatrixSetID: "GoogleMapsCompatible",
            show: false
          })
      });

      this.viewer3D._cesiumWidget._creditContainer.style.display = "none";
      this.viewer2D._cesiumWidget._creditContainer.style.display = "none";
      this.viewer3D.camera.setView({
        destination: new this.Cesium.Cartesian3.fromDegrees(117.918977, 25.0, 1500000)
        // 方向，俯视和仰视的视角
        // orientation:{
        //   heading: this.Cesium.Math.toRadians(90),//坐标系旋转90度
        //   pitch: this.Cesium.Math.toRadians(-45) ,//设置俯仰角度为-45度
        // }
      });
      this.viewer2D.camera.setView({
        destination: new this.Cesium.Cartesian3.fromDegrees(117.918977, 25.0, 1500000)
        // 方向，俯视和仰视的视角
        // orientation:{
        //   heading: this.Cesium.Math.toRadians(90),//坐标系旋转90度
        //   pitch: this.Cesium.Math.toRadians(-45) ,//设置俯仰角度为-45度
        // }
      });
      // this.viewer.scene.screenSpaceCameraController.maximumZoomDistance = 1500000;  //相机高度的最大值
      this.viewer2D.camera.percentageChanged = 0.01;
      this.viewer2D.camera.changed.addEventListener(this.sync); //地图移动事件
      this.viewer3D.camera.percentageChanged = 0.01;
      this.viewer3D.camera.changed.addEventListener(this.sync); //地图移动事件
      this.viewer2D.camera.moveEnd.addEventListener(this.getCammeraHeightAndZoom)  //地图缩放事件
      this.viewer3D.camera.moveEnd.addEventListener(this.getCammeraHeightAndZoom)  //地图缩放事件
      this.handler2D = new this.Cesium.ScreenSpaceEventHandler(this.viewer2D.scene.canvas);
      this.handler3D = new this.Cesium.ScreenSpaceEventHandler(this.viewer3D.scene.canvas);
    },
    sync() {
      if (this.mousevalue == "3D") {
        // 三维地图中心点
        let center = new this.Cesium.Cartesian2(
          Math.floor(this.viewer3D.canvas.clientWidth / 2),
          Math.floor(this.viewer3D.canvas.clientHeight / 2)
        );
        // 转为世界坐标系
        let position = this.viewer3D.scene.camera.pickEllipsoid(center);
        // 判断中心点是否在椭球体上
        if (this.Cesium.defined(position)) {
          // 获取三维地图中心点与相机之间的距离
          let distance = this.Cesium.Cartesian3.distance(position, this.viewer3D.scene.camera.positionWC);
          position = this.convertWorldToCartographic(position);
          // 更新二维地图
          this.viewer2D.scene.camera.setView({
            destination: new this.Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, distance)
          });
        }
      }
      if (this.mousevalue == "2D") {
        // 二维地图中心点
        let center = new this.Cesium.Cartesian2(
          Math.floor(this.viewer2D.canvas.clientWidth / 2),
          Math.floor(this.viewer2D.canvas.clientHeight / 2)
        );
        // 转为世界坐标系
        let position = this.viewer2D.scene.camera.pickEllipsoid(center);
        // 判断中心点是否在椭球体上
        if (this.Cesium.defined(position)) {
          // 获取三维地图中心点与相机之间的距离
          let distance = this.viewer2D.scene.camera.positionCartographic.height;
          position = this.convertWorldToCartographic(position);
          // 更新三维地图
          this.viewer3D.scene.camera.setView({
            destination: new this.Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, distance)
          });
        }
      }
    },
    // 将世界坐标系转换为经纬度坐标系
    convertWorldToCartographic(worldPosition) {
      const ellipsoid = this.viewer2D.scene.globe.ellipsoid;
      const cartographic = ellipsoid.cartesianToCartographic(worldPosition);
      const longitude = this.Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = this.Cesium.Math.toDegrees(cartographic.latitude);
      const height = cartographic.height;
      return { longitude, latitude, height };
    },
    // 监听地图变化
    changeActive(value) {
      this.mousevalue = value;
    },
    dimensionswitch(value) {
      this.dimension = value;
      this.selectModel();
    },
    // 全屏缩小
    ismax() {
      if (screenfull.isEnabled && screenfull.isFullscreen) {
        screenfull.exit();
      } else {
        screenfull.request();
      }
    },
    /* 获取camera中心点坐标 */
    getCenterPosition(is3D = false) {
      let viewer = is3D ? this.viewer3D : this.viewer2D;
      let result = viewer.camera.pickEllipsoid(
        new this.Cesium.Cartesian2(viewer.canvas.clientWidth / 2, viewer.canvas.clientHeight / 2)
      );
      let curPosition = this.Cesium.Ellipsoid.WGS84.cartesianToCartographic(result);
      let lon = (curPosition.longitude * 180) / Math.PI;
      let lat = (curPosition.latitude * 180) / Math.PI;
      let height = viewer.camera.positionCartographic.height;
      return {
        lon: lon,
        lat: lat,
        height: height
      };
    },
    /* 地图放大 */
    big() {
      let { lon, lat, height } = this.getCenterPosition(this.dimension === 3);
      let viewer = (this.dimension === 3 || this.dimension === 5)? this.viewer3D : this.viewer2D;
      // 镜头拉进
      viewer.camera.flyTo({
        destination: this.Cesium.Cartesian3.fromDegrees(lon, lat, height / 1.8),
        duration: 1.0
      });
    },
    /* 地图缩小 */
    small() {
      let { lon, lat, height } = this.getCenterPosition(this.dimension === 3);
      let viewer = (this.dimension === 3 || this.dimension === 5) ? this.viewer3D : this.viewer2D;
      // 镜头远离
      viewer.camera.flyTo({
        destination: this.Cesium.Cartesian3.fromDegrees(lon, lat, height * 1.2),
        duration: 1.0
      });
    },
    home() {
      let viewer = (this.dimension === 3 || this.dimension === 5)? this.viewer3D : this.viewer2D;
      viewer.camera.flyTo({
        destination: this.Cesium.Cartesian3.fromDegrees(117.918977, 25.0, 1500000),
        duration: 2.0
      });
    },
    // tabs 切换点击
    legendClick({ index }) {
      this.selectModel();
      let tab_content = document.querySelectorAll(".menu .el-tabs__content");
      if (this.currentLab.index == index) {
        tab_content[0].style.display == "none" || ""
          ? (tab_content[0].style.display = "block")
          : (tab_content[0].style.display = "none");
      }
      if (this.currentLab.index != index) {
        this.currentLab.index = index;
        tab_content[0].style.display = "block";
      }
    },
    mouseMove(event) {
      if (this.$refs.modeltooltip) {
        this.$refs.modeltooltip.style.left = event.pageX - 240 + "px";
        this.$refs.modeltooltip.style.top = event.pageY - 115 + "px";
      }
    },
    //显示鼠标经纬度
    getMouseLocation(event) {
      let {longitude,latitude} = this.getCoordinatesFromEvent(event);
      this.$store.commit("app/setMouseLocation",{longitude,latitude});
    },
    /*根据camera高度近似计算当前层级*/ 
    heightToZoom(height){ 
      var A = 40487.57; 
      var B = 0.00007096758; 
      var C = 91610.74; 
      var D = -40467.74; 
      return Math.round(D+(A-D)/(1+Math.pow(height/C, B))); 
    },
    getCammeraHeightAndZoom(){
      let viewer = (this.dimension === 3 || this.dimension === 5) ? this.viewer3D : this.viewer2D;
      //获取当前相机高度 
      let height = viewer.camera.positionCartographic.height; 
      let zoom = this.heightToZoom(height); 
      this.$store.commit("app/setCameraHeightAndZoom",{height,zoom});
    },
    selectModel(cursorStyle, image, info) {
      console.log('image :>> ', image);
      let earthMap = document.getElementById("earth");
      earthMap.style.cursor = cursorStyle || "auto";
      if (cursorStyle) {
        document.addEventListener("mousemove", this.mouseMove);
        this.isShow = true;
        this.image = image;
        this.modeltooltip = info;
      } else {
        document.removeEventListener("mousemove", this.mouseMove);
        this.isShow = false;
        this.image = null;
        this.modeltooltip = null;
      }
    },
    onMapClick(event) {
      if (this.isShow && this.modeltooltip === "左键单击确认") {
        const { latitude, longitude } = this.getCoordinatesFromEvent(event);
        this.markLocation(latitude, longitude);
      }
    },
    // 同时在2D和3D地图上标记坐标
    markLocation(latitude, longitude) {
      const position = this.Cesium.Cartesian3.fromDegrees(longitude, latitude);
      console.log('position :>> ', position);
      this.viewer2D.entities.add({
        id: this.id,
        position: position,
        // point: {
        //   pixelSize: 12, // 调整点的大小，可以增大点的像素大小
        //   color: this.Cesium.Color.fromCssColorString(this.image.color)
        // },
        model: {
          uri: satelliteModel, // 替换为你的3D模型文件路径
          scale: 1.0, // 调整3D模型的缩放大小
          minimumPixelSize: 64 // 设置3D模型的最小像素大小，确保在视图中可见
        },
        label: {
          text: this.image.name,
          show: true,
          font: "18px Helvetica", // 调整标签的字体样式和大小
          pixelOffset: new this.Cesium.Cartesian2(0, 20) // 调整标签的像素偏移，向下偏移20像素
        }
      });
      this.viewer3D.entities.add({
        id: this.id,
        position: position,
        // point: {
        //   pixelSize: 12, // 调整点的大小，可以增大点的像素大小
        //   color: this.Cesium.Color.fromCssColorString(this.image.color)
        // },
        model: {
          uri: satelliteModel, // 替换为你的3D模型文件路径
          scale: 1.0, // 调整3D模型的缩放大小
          minimumPixelSize: 64 // 设置3D模型的最小像素大小，确保在视图中可见
        },
        label: {
          text: this.image.name,
          show: true,
          font: "18px Helvetica", // 调整标签的字体样式和大小
          pixelOffset: new this.Cesium.Cartesian2(0, 20) // 调整标签的像素偏移，向下偏移20像素
        }
      });
      this.id++;
    },
    markLocationbyJson(latitude, longitude,height,name,type) {
      const position = this.Cesium.Cartesian3.fromDegrees(longitude, latitude,height);
      console.log('position :>> ', position);
      let color = ''
      let modelUrl = ''
      if(type=='red'){
        color = 'Red'
        modelUrl= missileModel
      }
      else if(type=='blue'){
        color = 'Blue'
        modelUrl = thaadModel
      }
      else if(type=='center'){
        color = 'Blue'
        modelUrl = centerModel
      }
      this.viewer2D.entities.add({
        id: this.id,
        position: position,
        point: {
          pixelSize: 12, // 调整点的大小，可以增大点的像素大小
          color: this.Cesium.Color.fromCssColorString(color)
        },
        // model: {
        //   uri: modelUrl, // 替换为你的3D模型文件路径
        //   scale: 1.0, // 调整3D模型的缩放大小
        //   minimumPixelSize: 64 // 设置3D模型的最小像素大小，确保在视图中可见
        // },
        label: {
          text: type+' '+name,
          show: true,
          font: "18px Helvetica", // 调整标签的字体样式和大小
          pixelOffset: new this.Cesium.Cartesian2(0, 20) // 调整标签的像素偏移，向下偏移20像素
        }
      });
      this.viewer3D.entities.add({
        id: this.id,
        position: position,
        point: {
          pixelSize: 12, // 调整点的大小，可以增大点的像素大小
          color: this.Cesium.Color.fromCssColorString(color)
        },
        model: {
          uri: modelUrl, // 替换为你的3D模型文件路径
          scale: 1.0, // 调整3D模型的缩放大小
          minimumPixelSize: 64 // 设置3D模型的最小像素大小，确保在视图中可见
        },
        label: {
          text: type+' '+name,
          show: true,
          font: "18px Helvetica", // 调整标签的字体样式和大小
          pixelOffset: new this.Cesium.Cartesian2(0, 20) // 调整标签的像素偏移，向下偏移20像素
        }
      });
      this.nameIdList.push({
        id: this.id,
        name: name
      })
      this.id++;
      console.log('this.viewer3D.entities :>> ', this.viewer3D.entities);
    },
    // 从鼠标点击事件获取坐标
    getCoordinatesFromEvent(event) {
      let viewer = this.mousevalue === "2D" ? this.viewer2D : this.viewer3D;
      let clickPosition;
      if (this.dimension === 5 && this.mousevalue === "3D") {
        clickPosition = new this.Cesium.Cartesian2(event.clientX - 1080, event.clientY - 160);
      } else {
        clickPosition = new this.Cesium.Cartesian2(event.clientX - 280, event.clientY - 160);
      }
      // 获取地图上的经纬度
      const viewerPosition = viewer.scene.camera.pickEllipsoid(clickPosition);
      const cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(viewerPosition);
      const latitude = this.Cesium.Math.toDegrees(cartographic.latitude);
      const longitude = this.Cesium.Math.toDegrees(cartographic.longitude);
      return {
        latitude,
        longitude
      };
    },
    markLine(point1, point2, color) {
      // 从点1和点2的WGS84坐标创建Cartesian3对象
      const position1 = this.Cesium.Cartesian3.fromDegrees(point1.longitude, point1.latitude, point1.height || 0);
      const position2 = this.Cesium.Cartesian3.fromDegrees(point2.longitude, point2.latitude, point2.height || 0);
      // 创建一个带有箭头图标的PolylineMaterial
      const material = new this.Cesium.PolylineArrowMaterialProperty(
        this.Cesium.Color.fromCssColorString(color || "red")
      );

      // 将点1和点2之间的连线添加到Viewer中
      this.viewer2D.entities.add({
        polyline: {
          positions: [position1, position2],
          width: 5, // 设置线的宽度
          material: material,
          followSurface: false // 设置为false，使连线保持在固定的高度，不会贴地显示
        }
      });
      this.viewer3D.entities.add({
        polyline: {
          positions: [position1, position2],
          width: 5, // 设置线的宽度
          material: material,
          followSurface: false // 设置为false，使连线保持在固定的高度，不会贴地显示
        }
      });
    },
    // 鼠标点击的事件监听
    pointMove() {
      // 监听鼠标左键点击事件
      this.handler2D.setInputAction((event) => {
        if (!this.selectedMarker && !this.modeltooltip) {
          const screenPosition = new this.Cesium.Cartesian2(event.position.x, event.position.y);
          const pickedEntity = this.viewer2D.scene.pick(screenPosition);
          if (this.Cesium.defined(pickedEntity)) {
            for (const entity of this.viewer2D.entities.values) {
              if (pickedEntity.id.id === entity.id) {
                this.selectedMarker = entity;
                this.oldPosition = pickedEntity.id.position;
                // 显示提示
                this.selectModel("pointer", null, "右键取消");
              }
            }
          }
        } else if (this.selectedMarker && this.modeltooltip === "右键取消") {
          // const material = new this.Cesium.PolylineArrowMaterialProperty(this.selectedMarker.point.color);
          console.log('this.viewer2D.entities.values :>> ', this.viewer2D.entities.getById(this.selectedMarker.id).position._value);
          let position = this.convertWorldToCartographic(this.viewer2D.entities.getById(this.selectedMarker.id).position._value)
        
          let name = ''
          for(let i = 0;i<this.nameIdList.length;i++){
          
            if(this.nameIdList[i].id == this.selectedMarker.id){
              name = this.nameIdList[i].name
            }
          }
          for(let i = 0;i<this.jsonData.blueunit.length;i++){
            if(name == this.jsonData.blueunit[i].name){
              this.jsonData.blueunit[i].pos.lat = position.latitude.toFixed(6)
              this.jsonData.blueunit[i].pos.lon = position.longitude.toFixed(6)
              this.jsonData.blueunit[i].pos.h = position.height.toFixed(2)
            }
          }
          for(let i = 0;i<this.jsonData.redunit.length;i++){
            if(name == this.jsonData.redunit.name){
              this.jsonData.redunit.component_movementjson.properties.launch_lon = position.longitude.toFixed(6)
              this.jsonData.redunit.component_movementjson.properties.launch_lat = position.latitude.toFixed(6)
              this.jsonData.redunit.component_movementjson.properties.launch_h = position.height.toFixed(2)
            }
          }
          for(let i = 0;i<this.jsonData.center.length;i++){
            if(name == this.jsonData.center[i].name){
              this.jsonData.center[i][name].properties.lon = position.longitude.toFixed(6)
              this.jsonData.center[i][name].properties.lat = position.latitude.toFixed(6)
              this.jsonData.center[i][name].properties.h = position.height.toFixed(2)
              for(let j = 0;j<this.jsonData.redunit.length;j++){
              this.jsonData.redunit[j].component_movementjson.properties.target_lon = position.longitude.toFixed(6)
              this.jsonData.redunit[j].component_movementjson.properties.target_lat = position.latitude.toFixed(6)
              this.jsonData.redunit[j].component_movementjson.properties.target_h = position.height.toFixed(2)
          }
// 新的终点坐标
const newEndPoint = this.Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height);
// 遍历所有的entity对象
this.viewer2D.entities.values.forEach(entity => {
  // 检查entity是否为Polyline类型
  if (entity instanceof this.Cesium.Entity && entity.polyline) {
    // 获取原始的Polyline坐标数组
    const positions = entity.polyline.positions.getValue(); // 得到一个Cartesian3数组

    // 修改终点坐标为新的坐标
    positions[positions.length - 1] = newEndPoint;

    // 更新entity的Polyline坐标
    entity.polyline.positions = new this.Cesium.CallbackProperty(time => positions, false);
  }
});
this.viewer3D.entities.values.forEach(entity => {
  // 检查entity是否为Polyline类型
  if (entity instanceof this.Cesium.Entity && entity.polyline) {
    // 获取原始的Polyline坐标数组
    const positions = entity.polyline.positions.getValue(); // 得到一个Cartesian3数组

    // 修改终点坐标为新的坐标
    positions[positions.length - 1] = newEndPoint;

    // 更新entity的Polyline坐标
    entity.polyline.positions = new this.Cesium.CallbackProperty(time => positions, false);
  }
});
            }
           
          }

          // this.viewer2D.entities.add({
          //   polyline: {
          //     positions: [
          //       this.oldPosition._value,
          //       this.viewer2D.entities.getById(this.selectedMarker.id).position._value
          //     ],
          //     width: 5, // 设置线的宽度
          //     material: material,
          //     followSurface: false // 设置为false，使连线保持在固定的高度，不会贴地显示
          //   }
          // });
          // this.viewer3D.entities.add({
          //   polyline: {
          //     positions: [
          //       this.oldPosition._value,
          //       this.viewer3D.entities.getById(this.selectedMarker.id).position._value
          //     ],
          //     width: 5, // 设置线的宽度
          //     material: material,
          //     followSurface: false // 设置为false，使连线保持在固定的高度，不会贴地显示
          //   }
          // });
          console.log('this.jsonData :>> ', this.jsonData);
          this.selectedMarker = null;
          this.selectModel();
        }
      }, this.Cesium.ScreenSpaceEventType.LEFT_CLICK);
      // 监听鼠标移动事件，用于移动标记点
      this.handler2D.setInputAction((event) => {
        if (this.selectedMarker && this.modeltooltip === "右键取消") {
          const screenPosition = new this.Cesium.Cartesian2(event.endPosition.x, event.endPosition.y);
          const position = this.viewer2D.scene.camera.pickEllipsoid(screenPosition);
          this.viewer2D.entities.getById(this.selectedMarker.id).position = position;
          this.viewer3D.entities.getById(this.selectedMarker.id).position = position;
        }
      }, this.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      // 监听右键
      this.handler2D.setInputAction(() => {
        if (this.selectedMarker && this.modeltooltip === "右键取消") {
          this.viewer2D.entities.getById(this.selectedMarker.id).position = this.oldPosition;
          this.selectedMarker = null;
          this.selectModel();
        }
      }, this.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      this.handler3D.setInputAction((event) => {
        if (!this.selectedMarker && !this.modeltooltip) {
          const screenPosition = new this.Cesium.Cartesian2(event.position.x, event.position.y);
          const pickedEntity = this.viewer3D.scene.pick(screenPosition);
          if (this.Cesium.defined(pickedEntity)) {
            for (const entity of this.viewer3D.entities.values) {
              if (pickedEntity.id.id === entity.id) {
                this.selectedMarker = entity;
                this.oldPosition = pickedEntity.id.position;
                // 显示提示
                this.selectModel("pointer", null, "右键取消");
              }
            }
          }
        } else if (this.selectedMarker && this.modeltooltip === "右键取消") {
          const material = new this.Cesium.PolylineArrowMaterialProperty(this.selectedMarker.point.color);
          this.viewer2D.entities.add({
            polyline: {
              positions: [
                this.oldPosition._value,
                this.viewer2D.entities.getById(this.selectedMarker.id).position._value
              ],
              width: 5, // 设置线的宽度
              material: material,
              followSurface: false // 设置为false，使连线保持在固定的高度，不会贴地显示
            }
          });
          this.viewer3D.entities.add({
            polyline: {
              positions: [
                this.oldPosition._value,
                this.viewer3D.entities.getById(this.selectedMarker.id).position._value
              ],
              width: 5, // 设置线的宽度
              material: material,
              followSurface: false // 设置为false，使连线保持在固定的高度，不会贴地显示
            }
          });
          this.selectedMarker = null;
          this.selectModel();
        }
      }, this.Cesium.ScreenSpaceEventType.LEFT_CLICK);
      // 监听鼠标移动事件，用于移动标记点
      this.handler3D.setInputAction((event) => {
        if (this.selectedMarker && this.modeltooltip === "右键取消") {
          const screenPosition = new this.Cesium.Cartesian2(event.endPosition.x, event.endPosition.y);
          const position = this.viewer3D.scene.camera.pickEllipsoid(screenPosition);
          this.viewer2D.entities.getById(this.selectedMarker.id).position = position;
          this.viewer3D.entities.getById(this.selectedMarker.id).position = position;
        }
      }, this.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      // 监听右键
      this.handler3D.setInputAction(() => {
        if (this.selectedMarker && this.modeltooltip === "右键取消") {
          this.viewer3D.entities.getById(this.selectedMarker.id).position = this.oldPosition;
          this.selectedMarker = null;
          this.selectModel();
        }
      }, this.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    }
  }
};
</script>
<style scoped>
::v-deep .cesium-infoBox {
  display: none !important;
}

::v-deep .cesium-infoBox-bodyless {
  display: none !important;
}

::v-deep .cesium-infoBox-visible {
  display: none !important;
}

.container{
  height: 100%;
}
.modeltooltip {
  position: absolute;
  padding: 5px;
  color: #fff;
  font-size: 20px;
  pointer-events: none;
  z-index: 999;
}

.myHeader {
  background-color: #1c222b !important;
  color: #fff;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  /*由于flex-direction: column，因此align-items代表的是水平方向*/
  justify-content: center;
  /*由于flex-direction: column，因此justify-content代表的是垂直方向*/
}

.myHeader .el-button {
  width: 100px;
  height: 20px;
  padding: 1px 23px;
}

.box-card {
  min-height: 100%;
  height: 100%;
}

::v-deep .el-card__body {
  height: 100% !important;
  padding: 0px !important;
}

.main-layout {
  height: 100%;
  width: 100%;
}

.map {
  width: 100%;
  height: 100%;
}

.menu {
  position: absolute;
  height: 400px;
  z-index: 999;
  left: 20px;
  top: 20px;
}

::v-deep .el-tabs--left .el-tabs__header.is-left {
  margin-right: 0px !important;
}

.buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-items: center;
  position: absolute;
  z-index: 999;
  right: 20px;
  top: 20px;
}

.el-button {
  margin: 5px !important;
}

::v-deep .el-tabs--border-card>.el-tabs__content {
  width: 300px;
  display: none;
}

.model {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.model>div {
  width: 50%;
  height: 120px;
  padding: 5px;
}

.model>div:hover {
  border: 2px solid blue;
}

.model>div:active {
  border: 2px solid red;
}

.active {
  border: 2px solid red !important;
}

.model .el-image {
  display: block !important;
}

::v-deep .el-image .el-image__inner {
  border: 1px solid #ddd;
  border-radius: 5px;
}

.item {
  font-size: 14px;
  /* right: 20px; */
}
</style>
