<template>
  <div class="container">
    <div id="modeltooltip">左键单击确认</div>
    <el-row style="height: 40px">
      <div class="myHeader">
        <el-button :type="this.dimension == 2 ? 'success' : 'danger'" @click="dimensionswitch(2)" round>二维</el-button>
        <el-button :type="this.dimension == 3 ? 'success' : 'danger'" @click="dimensionswitch(3)" round>三维</el-button>
        <el-button :type="this.dimension == 5 ? 'success' : 'danger'" @click="dimensionswitch(5)" round>
          一体化
        </el-button>
      </div>
    </el-row>
    <el-row id="map" style="height: 790px; width: 100%; display: flex; position: relative">
      <el-col style="height: 100%; position: relative" :span="this.leftwidth">
        <div class="main-layout" v-on:mouseover="changeActive('3D')">
          <div id="3DcesiumContainer" class="map"></div>
        </div>
      </el-col>
      <el-col style="height: 100%; position: relative" :span="24 - this.leftwidth">
        <div class="main-layout" v-on:mouseover="changeActive('2D')">
          <div id="2DcesiumContainer" class="map"></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">
          <span slot="label">
            <el-modeltooltip class="item" effect="dark" content="标绘" placement="left">
              <i class="el-icon-wind-power"></i>
            </el-modeltooltip>
          </span>
        </el-tab-pane>
        <el-tab-pane name="second">
          <span slot="label">
            <el-modeltooltip class="item" effect="dark" content="模型" placement="left">
              <i class="el-icon-receiving"></i>
            </el-modeltooltip>
          </span>
          <el-radio-group v-model="whosmodel" style="margin: 0 auto" size="mini">
            <el-radio-button label="red">红方</el-radio-button>
            <el-radio-button label="blue">蓝方</el-radio-button>
          </el-radio-group>
          <div v-if="whosmodel == 'blue'" class="model">
            <div :class="{ active: this.modelType == 'ThadRocket' }" @click="selectmodel('ThadRocket')">
              <el-image style="width: 100px; height: 80px; margin: 0 auto" :src="url" fit="fill"></el-image>
              <div style="text-align: center">Thad拦截导弹</div>
            </div>
            <div :class="{ active: this.modelType == 'interceptRadar' }" @click="selectmodel('interceptRadar')">
              <el-image style="width: 100px; height: 80px; margin: 0 auto" :src="url" fit="fill"></el-image>
              <div style="text-align: center">拦截雷达</div>
            </div>
            <div :class="{ active: this.modelType == 'interceptSatellite' }" @click="selectmodel('interceptSatellite')">
              <el-image style="width: 100px; height: 80px; margin: 0 auto" :src="url" fit="fill"></el-image>
              <div style="text-align: center">拦截卫星</div>
            </div>
          </div>
          <div v-else class="model">
            <div :class="{ active: this.modelType == 'rocket' }" @click="selectmodel('rocket')">
              <el-image style="width: 100px; height: 80px; margin: 0 auto" :src="url" fit="fill"></el-image>
              <div style="text-align: center">弹道导弹</div>
            </div>
            <div :class="{ active: this.modelType == 'radarTrap' }" @click="selectmodel('radarTrap')">
              <el-image style="width: 100px; height: 80px; margin: 0 auto" :src="url" fit="fill"></el-image>
              <div style="text-align: center">雷达诱饵</div>
            </div>
            <div :class="{ active: this.modelType == 'GRradar' }" @click="selectmodel('GRradar')">
              <el-image style="width: 100px; height: 80px; margin: 0 auto" :src="url" fit="fill"></el-image>
              <div style="text-align: center">干扰雷达</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane name="third">
          <span slot="label">
            <el-modeltooltip class="item" effect="dark" content="测量" placement="left">
              <i class="el-icon-discount"></i>
            </el-modeltooltip>
          </span>
        </el-tab-pane>
        <el-tab-pane name="fouth">
          <span slot="label">
            <el-modeltooltip class="item" effect="dark" content="测想定" placement="left">
              <i class="el-icon-house"></i>
            </el-modeltooltip>
          </span>
          <el-table :data="situation">
            <el-table-column label="名称" prop="xdname"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="getJson(scope.row)">导入</el-button>
                <el-button type="primary" @click="saveJson(scope.row)">保存</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-coin" circle></el-button> -->
        <!-- <el-button icon="el-icon-bangzhu" @click="Fly()" circle></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>
      </div>
    </el-row>
  </div>
</template>
<script>
import screenfull from "screenfull";
import fireController from "../../api/fireController";
import { getToken } from "@/utils";
import axios from "axios";
export default {
  computed: {},
  data() {
    return {
      situation: [],
      unit: [],
      satellite: [],
      center: [],
      viewer2D: null,
      viewer3D: null,
      dimension: 3,
      leftwidth: 24,
      mousevalue: null,
      shouldAnimate: false,
      activeName: null,
      currentLab: {
        index: -1,
        isActive: false
      },
      whosmodel: "red",
      modelType: null,
      url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
    };
  },
  created() {
    this.getData();
  },
  mounted() {
    this.cesiumInit();
  },

  methods: {
    async saveJson(row) {
      await axios
        .post("http://localhost:8084/admin/online/onlineOperation/updateDatasource/main", {
          params: {
            datasourceId: "1656243335922192384",
            masterData: row,
            slaveData: {}
          }
        })
        .then((res) => {
          console.log("update successfully ");
        });
    },
    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
      };
      console.log("jsonData :>> ", jsonData);
    },
    //获取所有数据
    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);
    },
    removeAllModel() {
      this.viewer.entities.removeAll(); // 移除全部模型
    },
    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);
        console.log(position);
        // 判断中心点是否在椭球体上
        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)
          });
          console.log(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);
        console.log(position);
        // 判断中心点是否在椭球体上
        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)
          });
          console.log(this.viewer2D.scene.camera.positionWC);
        }
      }
    },
    // 将世界坐标系转换为经纬度坐标系
    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;
      console.log(value);
    },
    dimensionswitch(value) {
      this.dimension = value;
      if (value == 3) {
        this.leftwidth = 24;
      } else if (value == 2) {
        this.leftwidth = 0;
      } else {
        this.leftwidth = 12;
      }
    },
    // 全屏缩小
    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.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.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.viewer3D : this.viewer2D;
      viewer.camera.flyTo({
        destination: this.Cesium.Cartesian3.fromDegrees(117.918977, 25.0, 1500000),
        duration: 2.0
      });
    },
    Fly() {
      this.shouldAnimate = !this.shouldAnimate;
      this.viewer2D.clock.shouldAnimate = true;
      this.viewer3D.clock.shouldAnimate = true;
      if (this.shouldAnimate == true) {
        this.startRun({ multiplier: 2000 });
      } else {
        this.stopRun();
      }
    },
    startRun(option = { multiplier: 1 }) {
      // 监听每次渲染前执行矩阵求解
      this.viewer3D.scene.postUpdate.addEventListener(this.rotateSetting);
      // 根据option修改一些参数
      if (this.viewer3D.clock) {
        const keys = Object.keys(option);
        for (let k of keys) {
          this.viewer3D.clock[k] = option[k];
        }
      }
    },
    stopRun() {
      let viewer = this.viewer3D;
      viewer.clock.multiplier = 1;
      viewer.scene.postUpdate.removeEventListener(this.rotateSetting);
    },
    rotateSetting() {
      let Cesium = this.Cesium;
      let viewer = this.viewer3D;
      if (!viewer || viewer.scene.mode !== Cesium.SceneMode.SCENE3D) {
        return;
      }
      const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(viewer.clock.currentTime);
      // icrfToFixed 在上面的方法中，若没加载好所需的计算资源会返回undefined，判断下
      if (Cesium.defined(icrfToFixed)) {
        const camera = viewer.camera;
        const offset = Cesium.Cartesian3.clone(camera.position);
        const transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
        camera.lookAtTransform(transform, offset);
      }
    },
    /// / tabs 切换点击
    legendClick(tab, event) {
      var tab_content = document.querySelectorAll(".menu .el-tabs__content");
      if (this.currentLab.index == tab.index) {
        tab_content[0].style.display == "none" || ""
          ? (tab_content[0].style.display = "block")
          : (tab_content[0].style.display = "none");
      }
      if (this.currentLab.index != tab.index) {
        this.currentLab.index = tab.index;
        tab_content[0].style.display = "block";
      }
    },

    selectmodel(modelType) {
      if (this.modelType == modelType) {
        this.modelType == null;
      } else {
        this.modelType = modelType;
        var map = document.getElementById("map");
        map.style.cursor = "crosshair";
        document.addEventListener("mousemove", function (event) {
          var modeltooltip = document.getElementById("modeltooltip");
          modeltooltip.style.display = "block";
          modeltooltip.style.left = event.clientX - 180 + "px";
          modeltooltip.style.top = event.clientY - 100 + "px";
        });

        document.addEventListener("mouseout", function () {
          var modeltooltip = document.getElementById("modeltooltip");
          modeltooltip.style.display = "none";
        });
      }
    }
  }
};
</script>
<style scoped>
.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%;
}

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

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

.container {
  height: 100%;
}

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

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

/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;
}

/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;
}

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

#modeltooltip {
  position: absolute;
  display: none;
  padding: 5px;
  color: #fff;
  font-size: 20px;
  pointer-events: none;
  z-index: 999;
}
</style>
