<template>
  <div style="wight: 100%; height: 100vh; position: absolute">
    <div
      :id="`mars3d-container${mapKey}`"
      :class="[
        'mars3d-container',
        customClass,
        { 'mars3d-container-compare-rh': compare },
      ]"
    ></div>
  </div>
</template>

<script>
import Vue from "vue";
import { httpGet, httpPostForJson } from "@/common/httpBean.js";
import {
  screenMapSetUpQuery,
  carRealTimeLocationQuery2,
  vehicleInformationQuery,
  apiCarClassQuery,
  apiCpointQuery,
} from "@/axios/api.js";

// 使用免费开源版本
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";
import * as Cesium from "mars3d-cesium/Build/Cesium/Cesium";
import {
  initGraphicManager,
  initLayerManager,
  bindLayerContextMenu,
  bindLayerPopup,
} from "./js/graphicManager";
import ddd from "../../assets/images/truckTuPian/qiche1.png";
import zhuangchetubiao from "../../assets/images/truckTuPian/zhuangchedian1.png";
import xiechetubiao from "../../assets/images/truckTuPian/xiechedian1.png";
import kongzhidiantubiao from "../../assets/images/truckTuPian/kongzhidian1.png";
import luzhangtubiao from "../../assets/images/truckTuPian/luzhang.png";

// 为了方便使用,绑定到原型链，在其他vue文件，直接 this.mars3d 来使用
Vue.prototype.mars3d = mars3d;
Vue.prototype.Cesium = mars3d.Cesium;

var map;
//画导航线
var graphicLayerZ;
var graphicZ;
//路障展示图层
var graphicLayerR;

export default {
  name: "mars3dViewer",

  created() {},

  data() {
    return {
      zuobianData: [],
      toJavaCoordinates: [],
      weilanName: [],
      areaColorData: [],
      allCarInforData: [],
      defaultjd: 140.71212,
      defaultwd: 52.158,
      realjd: 140.71212,
      realwd: 52.158,
      carnumber: "",
      //装车点卸车点数据
      mapControlPointData: [],
    };
  },

  props: {
    // 初始化配置参数
    url: String,

    // 地图唯一性标识
    mapKey: {
      type: String,
      default: "",
    },

    // 自定义参数
    options: Object,

    // 是否分屏显示
    compare: {
      type: Boolean,
      default: false,
    },

    // 是否插入到body元素上
    appendToBody: {
      type: Boolean,
      default: false,
    },

    // 自定义css类名
    customClass: {
      type: String,
      default: "",
    },
  },

  destroy() {
    this[`map${this.mapKey}`].destroy();
    delete this[`map${this.mapKey}`];
  },

  methods: {
    //获取车辆设备名和车牌号
    getCarInforFn(carnumber) {
      this.carnumber = carnumber;
      //获取车辆类型
      httpGet(apiCarClassQuery, { size: 9999 }).then((res) => {
        if (res.code == 200) {
          let arr11 = [];
          //获取车辆信息
          httpGet(vehicleInformationQuery, { size: 9999 }).then((res1) => {
            if (res.code == 200) {
              res1.data.content.forEach((item1, index1) => {
                let obj1 = { ...item1 };
                res.data.content.forEach((item, index) => {
                  if (item1.carclass == item.name) {
                    obj1.pic = item.card;
                    arr11.push(obj1);
                    return;
                  }
                });
              });
              this.allCarInforData = arr11;

              //获取所有关键控制点信息
              httpGet(apiCpointQuery, { size: 9999 }).then((res2) => {
                if (res2.code == 200) {
                  let arr2 = [];
                  res2.data.content.forEach((item2, index2) => {
                    if (item2.type != "控制点") {
                      arr2.push(item2);
                    }
                  });
                  this.mapControlPointData = arr2;
                  this.getCoordinate();
                }
              });
            }
          });
        }
      });
    },
    //后台获取数据
    getCoordinate() {
      let that = this;
      httpGet(screenMapSetUpQuery, { size: 9999 }).then((res) => {
        if (true) {
          //console.log(res);
          let data1 = [];
          for (let key in res) {
            that.weilanName.push(key);
            that.areaColorData.push(res[key][0].color);
            let arrays = [];
            res[key].forEach(function (item) {
              var arr = [];
              arr[0] = item.lon;
              arr[1] = item.lat;
              arr[2] = "500";
              arrays.push(arr);
            });
            data1.push(arrays);
          }
          that.zuobianData = data1;
          //console.log("zuobianData",that.zuobianData);
          //console.log("weilanName",that.weilanName);

          if (this.appendToBody) {
            document.body.appendChild(this.$el);
          }

          if (this.mapKey) {
            this.initMars3d(this.options);
          } else {
            mars3d.Resource.fetchJson({ url: this.url }).then((data) => {
              this.initMars3d(data.map3d); // 构建地图
            });
          }
        }
      });
    },
    //创建地图
    initMars3d(options) {
      let that = this;
      if (this[`map${this.mapKey}`]) return;

      const mapOptions = {
        ...options,
        ...this.options,
        control: {
          defaultContextMenu: false, //右键菜单
        },
      };

      // 创建三维地球场景
      map = new mars3d.Map(`mars3d-container${this.mapKey}`, mapOptions);
      this[`map${this.mapKey}`] = map;

      //围栏回显
      that.zuobianData.forEach(function (item, index) {
        var graphicLayer = new mars3d.layer.GraphicLayer();
        map.addLayer(graphicLayer);
        initLayerManager(graphicLayer, that.weilanName[index]);
        that.addGraphic_01(
          graphicLayer,
          item,
          that.weilanName[index],
          that.areaColorData[index]
        );
      });

      //实时位置1
      that.allCarInforData.forEach((item, index) => {
        var graphicLayer4 = new mars3d.layer.GraphicLayer();
        map.addLayer(graphicLayer4);
        that.bindLayerPopup(graphicLayer4, item.number);
        that.addDemoGraphics(
          graphicLayer4,
          item.number,
          item.equipmentName,
          item.carclass,
          item.pic,
          item.status
        );
      });

      //装车点卸车点位置
      that.mapControlPointData.forEach(function (item, index) {
        var graphicLayer = new mars3d.layer.GraphicLayer();
        map.addLayer(graphicLayer);
        that.addDemoGraphic4(graphicLayer, item);
      });

      // 抛出事件
      this.$emit("onload", map);
    },
    //围栏回显
    addGraphic_01(graphicLayer, positions, weilanName, color) {
      let graphic = new mars3d.graphic.PolygonEntity({
        positions: positions,
        style: {
          color: color,
          opacity: 0.5,
          outline: true,
          outlineWidth: 3,
          outlineColor: "#ffffff",
          label: {
            text: weilanName,
            font_size: 18,
            color: "#ffffff",
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 500000,
            distanceDisplayCondition_near: 0,
          },
        },
        allowDrillPick: true,
      });
      graphicLayer.addGraphic(graphic); //还可以另外一种写法: graphic.addTo(graphicLayer)
    },
    //实时位置1
    addDemoGraphics(
      graphicLayer4,
      number,
      equipmentName,
      carclass,
      pic,
      status
    ) {
      let that = this;

      //模型配置
      const graphic = new mars3d.graphic.BillboardEntity({
        style: {
          image: pic ? "http://8.143.203.103:9092/avatar/" + pic : ddd,
          // image: pic ? 'http://120.224.103.84:9092/avatar/' + pic : ddd,
          width: 35,
          height: 35,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          scaleByDistance: new Cesium.NearFarScalar(10000, 1.0, 500000, 0.1),
          highlight: {
            type: mars3d.EventType.click,
            silhouette: true,
            silhouetteColor: "#ff0000",
            silhouetteSize: 4,
          },
          label: {
            text: status == "1" ? "⚠\n" + number : number,
            font_size: 18,
            color:
              status == "1"
                ? "#ff0000"
                : number == that.carnumber
                ? "green"
                : "blue",
            outline: true,
            outlineColor: "#000000",
            pixelOffsetY: -50,
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 50000,
            distanceDisplayCondition_near: 0,
          },
        },
      });

      //载入图层
      graphicLayer4.addGraphic(graphic);
      //初始位置
      graphicLayer4.eachGraphic((graphic) => {
        graphic.addDynamicPosition(
          Cesium.Cartesian3.fromDegrees(that.defaultjd, that.defaultwd, 1000)
        );
      });
      //三秒后位置
      graphicLayer4.eachGraphic((graphic) => {
        graphic.addDynamicPosition(
          Cesium.Cartesian3.fromDegrees(that.defaultjd, that.defaultwd, 1000),
          3
        );
      });
      //定时更新动态位置
      setInterval(() => {
        httpGet(carRealTimeLocationQuery2, { name: equipmentName }).then(
          (res) => {
            if (res.data) {
              graphicLayer4.eachGraphic((graphic) => {
                graphic.addDynamicPosition(
                    Cesium.Cartesian3.fromDegrees(
                        res.data.location.x,
                        res.data.location.y,
                        1000
                    ),
                    2
                );
              });
            } else {
              graphicLayer4.eachGraphic((graphic) => {
                graphic.addDynamicPosition(
                  Cesium.Cartesian3.fromDegrees(
                    that.defaultjd,
                    that.defaultwd,
                    1000
                  ),
                  2
                );
              });
            }
          }
        );
      }, 4000);
    },
    //装车箭头线 graphicLayer.removeGraphic(graphic);
    addArrowGraphic3(boo, points) {
      graphicLayerZ = new mars3d.layer.GraphicLayer();
      map.addLayer(graphicLayerZ);
      if (boo) {
        graphicLayerZ.removeGraphic(graphicZ);
        graphicZ = new mars3d.graphic.PolylineEntity({
          positions: points,
          style: {
            width: 6,
            materialType: mars3d.MaterialType.PolylineOutline,
            color: Cesium.Color.ORANGE,
            outlineWidth: 2,
            outlineColor: Cesium.Color.BLACK,
          },
        });
        graphicLayerZ.addGraphic(graphicZ);
      } else {
        graphicLayerZ.removeGraphic(graphicZ);
      }
    },
    //装车点卸车点位置
    addDemoGraphic4(graphicLayer, item) {
      const graphic = new mars3d.graphic.BillboardEntity({
        name: item.name,
        position: [item.lon, item.lat, 1000],
        style: {
          image:
            item.type == "装车点"
              ? zhuangchetubiao
              : item.type == "卸车点"
              ? xiechetubiao
              : kongzhidiantubiao,
          scale: 0.15,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true,
          label: {
            text: item.name,
            pixelOffsetY: -40,
            color: "blue",
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 30000,
            distanceDisplayCondition_near: 0,
          },
        },
      });
      graphicLayer.addGraphic(graphic);
    },
    //路障展示
    roadblockShowFn(arr) {
      map.removeLayer(graphicLayerR);
      graphicLayerR = new mars3d.layer.GraphicLayer();
      map.addLayer(graphicLayerR);
      arr.forEach((item, index) => {
        const graphic = new mars3d.graphic.BillboardEntity({
          name: item.carcode + index,
          position: [item.lon, item.lat, 1000],
          style: {
            image: luzhangtubiao,
            scale: 1,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            clampToGround: true,
            label: {
              text: "路障",
              pixelOffsetY: -40,
              color: "yellow",
              distanceDisplayCondition: true,
              distanceDisplayCondition_far: 30000,
              distanceDisplayCondition_near: 0,
            },
          },
        });
        graphicLayerR.addGraphic(graphic);
      });
    },
    //视角跟随车辆
    changeView1(lat, lng) {
      if (map) {
        map.setCameraView({ lat: lat, lng: lng });
      }
    },
    // 在图层绑定Popup弹窗
    bindLayerPopup(graphicLayer, number) {
      let that = this;
      graphicLayer.bindPopup(function (event) {
        that.$parent.smallWinFn(number);
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style >
.cesium-viewer-toolbar {
  display: none !important;
}
.mars3d-compass {
  display: none !important;
}
.mars3d-locationbar {
  display: none !important;
}
.mars3d-distance-legend {
  display: none !important;
}
.mars3d-container {
  height: 100%;
  width: 100vw;
  overflow: hidden;
}

/* 重写Cesium的css */

/**cesium按钮背景色*/
.cesium-button {
  background-color: #3f4854;
  color: #e6e6e6;
  fill: #e6e6e6;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
  line-height: 32px;
}

.cesium-viewer-geocoderContainer .cesium-geocoder-input {
  background-color: rgba(63, 72, 84, 0.7);
}

.cesium-viewer-geocoderContainer .cesium-geocoder-input:focus {
  background-color: rgba(63, 72, 84, 0.9);
}

.cesium-viewer-geocoderContainer .search-results {
  background-color: #3f4854;
}

.cesium-geocoder-searchButton {
  background-color: #3f4854;
}

.cesium-infoBox-title {
  background-color: #3f4854;
}

.cesium-infoBox {
  background: rgba(63, 72, 84, 0.9);
}

.cesium-toolbar-button img {
  height: 100%;
}

.cesium-performanceDisplay-defaultContainer {
  top: auto;
  bottom: 35px;
  right: 50px;
}
.cesium-performanceDisplay-ms,
.cesium-performanceDisplay-fps {
  color: #fff;
}

/**cesium工具栏位置*/
.cesium-viewer-toolbar {
  top: auto;
  left: auto;
  right: 12px;
  bottom: 35px;
}

.cesium-viewer-toolbar > .cesium-toolbar-button,
.cesium-navigationHelpButton-wrapper,
.cesium-viewer-geocoderContainer {
  margin-bottom: 5px;
  float: right;
  clear: both;
  text-align: center;
}

.cesium-baseLayerPicker-dropDown {
  bottom: 0;
  right: 40px;
  max-height: 700px;
  margin-bottom: 5px;
}

.cesium-navigation-help {
  top: auto;
  bottom: 0;
  right: 40px;
  transform-origin: right bottom;
}

.cesium-sceneModePicker-wrapper {
  width: auto;
}

.cesium-sceneModePicker-wrapper .cesium-sceneModePicker-dropDown-icon {
  float: left;
  margin: 0 3px;
}

.cesium-viewer-geocoderContainer .search-results {
  left: 0;
  right: 40px;
  width: auto;
  position: absolute;
  z-index: 999;
}

.cesium-infoBox-title {
  background-color: #3f4854;
}

.cesium-infoBox {
  top: 50px;
  background: rgba(63, 72, 84, 0.9);
}

/**左下工具栏菜单*/
.toolbar-dropdown-menu-div {
  background: rgba(43, 44, 47, 0.8);
  border: 1px solid #2b2c2f;
  z-index: 999;
  position: absolute;
  right: 60px;
  bottom: 40px;
  display: none;
}

.toolbar-dropdown-menu {
  min-width: 110px;
  padding: 0;
}
.toolbar-dropdown-menu > li {
  padding: 0 3px;
  margin: 2px 0;
}
.toolbar-dropdown-menu > li > a {
  color: #edffff;
  display: block;
  padding: 4px 10px;
  clear: both;
  font-weight: normal;
  line-height: 1.6;
  white-space: nowrap;
  text-decoration: none;
}

.toolbar-dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
  color: #fff;
  background-color: #444d59;
}

.toolbar-dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
  color: #fff;
  background-color: #444d59;
}

.toolbar-dropdown-menu i {
  padding-right: 5px;
}

.infoview {
  position: absolute;
  top: 100px;
  left: 500px;
  width: 50vw;
  z-index: 1000;
}
</style>
