<template>
  <div id="cesiumContainer">
  </div>
</template>

<script>
import cesiumEntityUtils from "@/utils/cesiumEntityUtils";
import GlobleCountryLine from "../../assets/MapData/GlobleCountryLine.json";

let viewer;
export default {
  name: "cesiumViewer",
  data() {
    return {
      globleLines: GlobleCountryLine,
      locationLonLat: [],
      rwxxztVis: null,
      projectEntitys: {},
      showAll: true
    };
  },
  computed: {
    mapPoint() {
      return this.$store.state.xqglMapPointVisible
    },
    mapRectangle() {
      return this.$store.state.xqglMapRectangleVisible
    },
    clickedTargetRow() {
      return this.$store.state.xqglClickedTargetRowForCesiumSetView
    },
    currentRouteName() {
      return this.$route.name;
    }
  },
  watch: {
    currentRouteName: {
      handler(newValue) {
        if (viewer) {
          this.displayTimeLine(newValue === 'rwjsPage' && this.rwxxztVis);
          return;
        }
        const t = setInterval(() => {
          if (viewer) {
            this.displayTimeLine(newValue === 'rwjsPage' && this.rwxxztVis);
            clearInterval(t);
          }
        }, 10);
      },
      immediate: true,
    },
    locationLonLat: {
      deep: true,
      handler(newval) {
        this.$store.dispatch("xqglMapPointLonLat", newval)
      }
    },
    mapPoint(newPoint) {
      // this.moveEntities(this.thisviewer);
      this.moveMapLeftEventMonitor(window.viewer);
      console.log("地图上得到点击,地图点选的信息：", newPoint);
      this.mapClickPointAdd(window.viewer)
    },
    mapRectangle(newRec) {
      // this.moveEntities(this.thisviewer);
      this.moveMapLeftEventMonitor(window.viewer)
      console.log("地图上得到点击,地图框选的信息：", newRec);
      this.mapDrawRectangle(window.viewer)
    },
    clickedTargetRow(newClickedRow) {
      //测试点位添加
      const viewer = window.viewer;
      cesiumEntityUtils.removeCustomLayer(viewer, "xqgl");
      cesiumEntityUtils.addCustomLayer(viewer, "xqgl")
      let datasource = cesiumEntityUtils.getCustomLayer(viewer, "xqgl");
      newClickedRow.forEach((item, index) => {
        let lon = null;
        let lat = null;
        if (item.pointDTOList.length === 1) {
          lon = item.pointDTOList[0].lng;
          lat = item.pointDTOList[0].lat;
        }
        // cesiumEntityUtils.controlLayer(viewer, "xqgl", false)
        if (datasource) {
          let position = Cesium.Cartesian3.fromDegrees(lon, lat);
          datasource.entities.add({
            id: 'target' + index,
            position: position,
            billboard: {
              image: './static/icon/target_red.svg',
              width: 16,
              height: 16
            }
          });
        }
      })
      return
      // ----------------------------------------------
      let lon = null;
      let lat = null;
      if (newClickedRow.pointDTOList.length === 1) {
        lon = newClickedRow.pointDTOList[0].lng;
        lat = newClickedRow.pointDTOList[0].lat;
        this.addClickTargetPoint(lon, lat, true);
      }
      if (newClickedRow.pointDTOList.length === 4) {
        // lon = (newClickedRow.pointDTOList[0].lng + newClickedRow.pointDTOList[3].lng) / 2;
        // lat = (newClickedRow.pointDTOList[0].lat + newClickedRow.pointDTOList[3].lat) / 2;
        let polygon = [];
        let pointsSort = newClickedRow.pointDTOList.sort((a, b) => a.sequence - b.sequence);
        pointsSort.forEach(item => {
          polygon.push(item.lng);
          polygon.push(item.lat);
        });
        let polygonObj = {
          id: newClickedRow.targetId,
          name: newClickedRow.targetName,
          material: Cesium.Color.fromCssColorString('rgba(255,0,0,0.5)'),
          polygon,
        };
        this.addClickTargetRectangle([polygonObj]);
      }
      // this.addClickTargetPoint(lon, lat, true)
      // console.log("地图上得到目标列表被单击的行数据：", newClickedRow);
    },
  },
  mounted() {
    this.initViewer();
    this.componentsEvents();
  },
  methods: {
    initViewer() {
      viewer = new Cesium.Viewer("cesiumContainer", {
        // 连接地图服务
        // imageryProvider: new Cesium.UrlTemplateImageryProvider({
        //   // url: "http://192.168.1.188:9109/map/?z={z}&x={x}&y={y}",
        //   url: window.mapUrl,
        //   tilingScheme: new Cesium.WebMercatorTilingScheme(),
        //   maximumLevel: 7,
        //   show: false
        // }),
				imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
					// url: window.mapUrl + ":9109/map/?z={z}&x={x}&y={y}",
					url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
					tilingScheme: new Cesium.WebMercatorTilingScheme(),
					maximumLevel: 7,
					show: false
				}),
        animation: true,//true
        baseLayerPicker: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        timeline: true,//true
        navigationHelpButton: false,
        fullscreenButton: false
      });
      // viewer.dataSources.add(
      //     Cesium.GeoJsonDataSource.load("MapData/GlobleCountryLine.json")
      // )
      viewer.clock.shouldAnimate = true;
      viewer._cesiumWidget._creditContainer.style.display = "none";
      viewer.scene.globe.enableLighting = true;
      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(115.48, 32.67, 40000000.0),
        orientation: {
          pitch: Cesium.Math.toRadians(-88)
        }
      });
      cesiumEntityUtils.formatterDateToUTC8(viewer, true);
      cesiumEntityUtils.polylineMaterial();
      window.viewer = viewer
      // this.addGlobleLine()
      document.oncontextmenu = function () {
        return false
      }

      let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      let tempStore = this.$store
      handler.setInputAction(function (click) {
        tempStore.dispatch("xqglContentVisible", true)
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    },
    componentsEvents() {
      let self = this;
      //需求解译窗口列表添加
      this.$events.on("xqjy-addwindow", function (datas) {
        self.addWindowsOrPointByXqjy(datas, "windows")
      })
      //需求解译窗口列表删除
      this.$events.on("xqjy-deletewindow", function (datas) {
        self.deleteWindowByXqjy(datas)
      })
      //需求解译目标任务点展示
      this.$events.on("xqjy-target", function (data) {
        cesiumEntityUtils.controlLayer(viewer, 'xqgl', false)
        self.addWindowsOrPointByXqjy(data, "target")
      });
      //需求管理目标点添加
      this.$events.on('xqgl-targetList', function (datas) {
        //移除临时绘制图形
        let datasource = cesiumEntityUtils.getCustomLayer(viewer, "xqgl");
        if (datasource) {
          datasource.entities.removeById("selectTarget");
        }
        self.addTargetList("xqgl", datas)
      })
      this.$events.on('xqgl-cancelselect', function () {
        //移除临时绘制图形
        let datasource = cesiumEntityUtils.getCustomLayer(viewer, "xqgl");
        if (datasource) {
          datasource.entities.removeById("selectTarget");
        }
      })
      //专题切换通知
      this.$events.on("topic-switch", function (data) {
        if (!self.showAll)
          return
        const viewer = window.viewer;
        cesiumEntityUtils.controlLayer(viewer, data.from, false)
        cesiumEntityUtils.controlLayer(viewer, data.to, true)
      })
      this.$events.on("rwjs-hideall", function () {
        const viewer = window.viewer;
        self.showAll = !self.showAll
        cesiumEntityUtils.controlLayer(viewer, ['rwjs', 'rwjs-satelliteTracks', 'rwjs-stations', 'xqgl', 'jcfw', 'xqjy', 'xqch'], self.showAll)
      })
      this.$events.on("rwjs-targetshow", function (data) {
        cesiumEntityUtils.controlLayer(viewer, 'rwjs', data)
      })
      //任务监视地面站添加
      this.$events.on("rwjs-addStation", data => {
        cesiumEntityUtils.addCustomLayer(viewer, "rwjs-stations");
        cesiumEntityUtils.addModels(viewer, "rwjs-stations", data);
      })
      //任务监视目标点添加
      this.$events.on('rwjs-targetList', function (datas) {
        // console.log("@datas", datas);
        //移除临时绘制图形
        // viewer.entities.remove(viewer.entities.getById('selectTarget'));
        self.addTargetList("rwjs", datas);
      })
      this.$events.on('rwjs-wxgcxxStripe', function (datas) {
        // debugger
        self.addTargetList("rwjs", datas, true);
      })
      this.$events.on("rwjs-wxyxzt", (datas) => {
        self.addTracks("rwjs-satelliteTracks", datas);
      })
      this.$events.on("sys-initView", (type) => {
        this.initView(viewer, type);
      })
      this.$events.on("sys-change2D3D", () => {
        self.changeViewerModel();
      })
      this.$events.on("sys-showTimeLine", (show) => {
        self.rwxxztVis = show;
        self.displayTimeLine(show);
      })
      this.$events.on("sys-showTrack", (type) => {
        this.initView(viewer, type);
        this.isTrackShow(undefined, type);
      })

    },
    changeViewerModel() {
      viewer.scene.mode == Cesium.SceneMode.SCENE3D ? (viewer.scene.mode = Cesium.SceneMode.SCENE2D) : (viewer.scene.mode = Cesium.SceneMode.SCENE3D);
    },
    displayTimeLine(show) {
      if (viewer) {
        if (show) {
          viewer.animation.container.style.display = "block"
          viewer.timeline.container.style.display = "block"
          viewer.animation.container.style.zIndex = 9
          viewer.timeline.container.style.zIndex = 9
        } else {
          viewer.animation.container.style.display = "none"
          viewer.timeline.container.style.display = "none"
        }
      }
    },
    initView(viewer, type = "all") {
      const heights = {
        "lowTrack": 20000000,
        "highTrack": 25000000,
        "all": 40000000,
      }
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(115.48, 32.67, heights[type]),
        orientation: {
          pitch: Cesium.Math.toRadians(-88)
        }
      });
    },
    moveEntities(viewer) {
      viewer.entities.removeAll();
    },
    moveMapLeftEventMonitor(viewer) {
      viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    mapClickPointAdd(viewer) {
      let self = this;
      let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(function (event) {
        cesiumEntityUtils.addCustomLayer(viewer, "xqgl")
        let datasource = cesiumEntityUtils.getCustomLayer(viewer, "xqgl");
        let clickPosition = viewer.scene.camera.pickEllipsoid(event.position);
        let radiansPos = Cesium.Cartographic.fromCartesian(clickPosition);
        cesiumEntityUtils.flyToTargetPoint(viewer, Cesium.Math.toDegrees(radiansPos.longitude), Cesium.Math.toDegrees(radiansPos.latitude), 20000000);
        if (datasource) {
          datasource.entities.removeById("selectTarget");
          datasource.entities.add({
            id: 'selectTarget',
            position: clickPosition,
            point: {
              color: Cesium.Color.YELLOW,
              pixelSize: 10
            }
          })
        }
        self.locationLonLat = [];
        self.locationLonLat.push(Cesium.Math.toDegrees(radiansPos.longitude));
        self.locationLonLat.push(Cesium.Math.toDegrees(radiansPos.latitude));
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    mapDrawRectangle(viewer) {
      if (viewer) {
        const self = this;
        let clickPoint = [];
        let sefstore = this.$store
        // 鼠标左键绘制
        let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction(function (movement) {
          const earthPosition = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid); //当前世界坐标笛卡尔积
          if (Cesium.defined(earthPosition)) {
            // 判断现在是第几个点
            if (clickPoint.length === 0) { //还没有点，添加第一个点
              clickPoint.push(earthPosition)
            } else {
              //绘制矩形
              clickPoint.push(earthPosition)
              // 绘制矩形
              const rectangleHand = Cesium.Rectangle.fromCartesianArray(clickPoint)
              cesiumEntityUtils.addCustomLayer(viewer, "xqgl")
              let datasource = cesiumEntityUtils.getCustomLayer(viewer, "xqgl");
              if (datasource) {
                datasource.entities.removeById("selectTarget");
                datasource.entities.add({
                  id: 'selectTarget',
                  name: 'drawRectangle',
                  rectangle: {
                    coordinates: rectangleHand,
                    height: 0,
                    material: Cesium.Color.RED.withAlpha(0.4),
                    outline: true,
                    outlineColor: Cesium.Color.BLUE.withAlpha(0.5),
                  },
                });
              }


              const northwest = Cesium.Rectangle.northwest(rectangleHand); //西北角弧度坐标（左上）
              const southwest = Cesium.Rectangle.southwest(rectangleHand); //西南角弧度坐标（左下）
              const northeast = Cesium.Rectangle.northeast(rectangleHand); //东北角弧度坐标（右上）
              const southeast = Cesium.Rectangle.southeast(rectangleHand); //东南角弧度坐标（右下）

              // 转换为经纬度
              const leftTop = [Cesium.Math.toDegrees(northwest.longitude), Cesium.Math.toDegrees(northwest.latitude)]; //左上角经度
              const leftBottom = [Cesium.Math.toDegrees(southwest.longitude), Cesium.Math.toDegrees(southwest.latitude)]; //左下角经度
              const rightTop = [Cesium.Math.toDegrees(northeast.longitude), Cesium.Math.toDegrees(northeast.latitude)]; //右上角经度
              const rightBottom = [Cesium.Math.toDegrees(southeast.longitude), Cesium.Math.toDegrees(southeast.latitude)]; //右下角经度
              cesiumEntityUtils.flyToTargetPoint(viewer, (leftTop[0] + rightBottom[0]) / 2, (leftTop[1] + rightBottom[1]) / 2, 20000000);
              const data = {
                leftTop: leftTop,
                leftBottom: leftBottom,
                rightTop: rightTop,
                rightBottom: rightBottom,
              }
              const dataarr = [leftTop, rightTop, rightBottom, leftBottom]
              sefstore.dispatch('xqglMapRectangleLonLats', dataarr)
              // console.log("矩形四角坐标：",data);
              console.log("矩形四角坐标arr：", sefstore.state.xqglMapRectangleLonLats);
              clickPoint = []; //清空
            }
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }
    },
    addGlobleLine() {
      const features = this.globleLines.geometries;
      const instances = [];
      for (let i = 0; i < features.length; i++) {
        const polygonArr = features[i].coordinates;
        const polygon = new Cesium.PolylineGeometry({
          positions: Cesium.Cartesian3.fromDegreesArray(polygonArr.toString().split(',')),
          width: 3,
          vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT
        })
        instances.push(new Cesium.GeometryInstance({
          geometry: polygon,
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color.fromCssColorString("rgba(217,212,85,1)"))
          }
        }))
      }
      const primitive = new Cesium.Primitive({
        geometryInstances: instances,
        appearance: new Cesium.PolylineColorAppearance(),
        asynchronous: false
      })
      window.viewer.scene.primitives.add(primitive)
    },
    addClickTargetRectangle(polygons) {
      const viewer = window.viewer;
      cesiumEntityUtils.removeCustomLayer(viewer, "xqgl");
      cesiumEntityUtils.addCustomLayer(viewer, "xqgl");
      // cesiumEntityUtils.controlLayer(viewer, "xqgl", true)
      cesiumEntityUtils.addCustomPolygons(viewer, "xqgl", polygons);
      cesiumEntityUtils.flyToTargetPolygon(viewer, polygons[0].polygon, 8000000);
    },
    addClickTargetPoint(lon, lat, isLocation) {
      const viewer = window.viewer;
      cesiumEntityUtils.removeCustomLayer(viewer, "xqgl");
      cesiumEntityUtils.addCustomLayer(viewer, "xqgl")
      // cesiumEntityUtils.controlLayer(viewer, "xqgl", false)
      let datasource = cesiumEntityUtils.getCustomLayer(viewer, "xqgl");
      if (datasource) {
        datasource.entities.removeById("target");
        let position = Cesium.Cartesian3.fromDegrees(lon, lat);
        datasource.entities.add({
          id: 'target',
          position: position,
          billboard: {
            image: './static/icon/target_red.svg',
            width: 16,
            height: 16
          }
        });
        if (isLocation) {
          cesiumEntityUtils.flyToTargetPoint(viewer, lon, lat, 20000000);
        }
      }
    },

    addWindowsOrPointByXqjy(datas, type) {
      const viewer = window.viewer;
      // cesiumEntityUtils.controlAllLayer(viewer, false);
      // if (type === 'target') {
      //   cesiumEntityUtils.removeCustomLayer(viewer, 'xqjy')
      // }
      cesiumEntityUtils.addCustomLayer(viewer, "xqjy")
      // cesiumEntityUtils.controlLayer
      if (type === 'target') {
        const targetType = datas.type;
        const target = datas.data;
        if (target === null)
          return;
        if (targetType === 'point') {
          cesiumEntityUtils.addCustomPoints(viewer, "xqjy", target);
          cesiumEntityUtils.flyToTargetPoint(viewer, target.lon, target.lat, 8000000)
        } else {
          cesiumEntityUtils.addCustomPolygons(viewer, "xqjy", target);
          cesiumEntityUtils.flyToTargetPolygon(viewer, target.polygon, 8000000)
        }
      } else {
        if (datas.length == 0) {
          return
        }
        cesiumEntityUtils.addCustomPolygons(viewer, "xqjy", datas);
        // let polygon = [];
        // datas.forEach(data => {
        //   polygon = polygon.concat(data.polygon)
        // });
        // cesiumEntityUtils.flyToTargetPolygon(viewer, polygon, 20000000)
      }
    },
    deleteWindowByXqjy(datas) {
      const viewer = window.viewer;
      cesiumEntityUtils.removeCustomLayerEntitysById(viewer, "xqjy", datas)
    },
    addTargetList(dsId, datas, isStripe = false) {
      // debugger
      const viewer = window.viewer;
      if (datas.length == 0) {
        // cesiumEntityUtils.removeCustomLayer(viewer, "xqgl")
        cesiumEntityUtils.removeCustomLayer(viewer, dsId)
        return
      }
      // cesiumEntityUtils.addCustomLayer(viewer, "xqgl")
      cesiumEntityUtils.addCustomLayer(viewer, dsId)
      let targetPoints = [];
      let targetPoylgons = []
      datas.forEach(data => {
        const id = data.id;
        const name = data.targetName
        let points = data.pointDTOList;
        if (points.length == 1) {
          targetPoints.push({
            id: id,
            name: name,
            lon: points[0].lng,
            lat: points[0].lat,
            size: 10,
            style: {
              color: 'red',
            },
            color: Cesium.Color.fromCssColorString('#f10808')
          })
          cesiumEntityUtils.addCustomPoints(viewer, dsId, targetPoints)
          dsId === 'rwjs' && cesiumEntityUtils.flyToTargetPoint(viewer, points[0].lng, points[0].lat, 8000000)
        }
        if (points.length > 1) {
          let polygon = [];
          points.forEach(point => {
            polygon.push(point.lng || point.longitude)
            polygon.push(point.lat || point.latitude)
          })
          targetPoylgons.push({
            id: id,
            name: name,
            isRhumb: true,//矩形按照贴经纬线形状绘制
            polygon: polygon,
            height: 10,
            style: {
              color: 'red',
              size: 5
            },
            material: isStripe ? Cesium.Color.fromCssColorString('rgba(237,245,11,0.5)') : Cesium.Color.fromCssColorString('#f10808'),
          })
          cesiumEntityUtils.addCustomPolygons(viewer, dsId, targetPoylgons)
          dsId === 'rwjs' && cesiumEntityUtils.flyToTargetPolygon(viewer, polygon, 8000000)
        }
      })

    },
    addTracks(dsId, tracks) {
      const {trackData, startTime, endTime, satelliteList, tasks} = tracks
      const viewer = window.viewer;
      cesiumEntityUtils.createCZML(viewer, dsId, startTime, endTime, trackData);
      //绘制投影
      let self = this;
      let _viewer = viewer;
      let timer = setInterval(() => {
        if (window.trackShow) {
          self.addSatelliteProjection(satelliteList, tasks);
          // this.setCurrentTime(_viewer, "2022-04-09T15:06:10")
          clearInterval(timer);
          window.trackShow = false;
        }
      }, 500);
    },
    //添加卫星投影
    addSatelliteProjection(satelliteList, tasks) {
      const viewer = window.viewer;
      satelliteList.forEach(item => {
        const wxSource = viewer.dataSources.getByName(item.wxSourceId)[0];
        if (!wxSource) return;
        const itemEntity = cesiumEntityUtils.getEntityByIdDS(wxSource, item.name);
        if (itemEntity) {
          this.projectEntitys[item.name] = cesiumEntityUtils.drawProjection(viewer, 1, itemEntity, false, item);
        }
      });

      this.taskRun(tasks);
    },
    //任务执行监听
    taskRun(tasks) {
      const stationDsId = "rwjs-stations"
      const satelliteDsId = "rwjs-satelliteTracks"
      const lineId = "rwjs-taskSimulationLine"

      tasks.cdTasks.forEach((taskItem, index) => {
        let times = [];
        times.push({
          start: Cesium.JulianDate.fromDate(new Date(taskItem.startTime)),
          stop: Cesium.JulianDate.fromDate(new Date(taskItem.endTime))
        });
        const station = cesiumEntityUtils.getEntityByIdDS(viewer.dataSources.getByName(stationDsId)[0], taskItem.stationCode);
        const satellite = cesiumEntityUtils.getEntityByIdDS(viewer.dataSources.getByName(satelliteDsId)[0], taskItem.satelliteCode);
        if (times.length > 0) {
          const option = {
            viewer: viewer,
            dsId: satelliteDsId,
            lineId: lineId + index,
            satellite,
            station,
            times,
            direction: taskItem.type, //可选 'SC' 和 'CK'， 不传，默认为 'SC'
          };
          cesiumEntityUtils.addLineBetweenTwoEntity(option);
        }
      });
      // 投影可见任务，相机开关机
      // console.log("this.projectEntitys:", this.projectEntitys);
      tasks.proTasks.forEach(proTask => {
        proTask.startTime = this.timeToUTM(proTask.startTime)
        proTask.endTime = this.timeToUTM(proTask.endTime)
        cesiumEntityUtils.projectionVisible(viewer, this.projectEntitys[proTask.satelliteCode], proTask)
      })

    },
    timeToUTM(strTime) {
      let d = this.$moment(strTime)
      return d.subtract(8, 'h').format("YYYY-MM-DD HH:mm:ss")
    },
    isTrackShow(dsId = "rwjs-satelliteTracks", type = "all", show = true) {
      // type 的可选项：lowTrack,highTrack,all
      const tracksLayer = viewer.dataSources.getByName(dsId)[0];
      if (!tracksLayer) {
        return
      }
      tracksLayer.entities.values.forEach(et => {
        if (et.description) {
          const tempType = et.description.getValue();
          if (type === 'all') {
            et.show = true;
          } else {
            et.show = tempType === type;
          }
        }
      });
    },

  },

};
</script>

<style lang="scss" scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
}
</style>
