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

</template>

<script>
import Vue from 'vue'
import { Tools, HttpReq, CAMap} from '@/assets/js/common.js';

// 使用免费开源版本
import 'mars3d/dist/mars3d.css'
import * as mars3d from 'mars3d'
import * as Cesium from 'mars3d-cesium/Build/Cesium/Cesium'
import  { initGraphicManager,initLayerManager,bindLayerContextMenu } from './js/graphicManager'


// 导入插件(其他插件类似，插件清单访问：http://mars3d.cn/dev/guide/start/install.html)
// echarts插件
// import 'mars3d-echarts'

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

var map;
export default {
  name: 'mars3dViewer',

  created(){
    this.getCoordinate();
  },

  data(){
    return{
      historyTrajectoryData:[],
      persons:[
          ["122.128833", "37.526448", "500"],
          ["122.128638", "37.522818", "500"],
          ["122.128738", "37.522818", "500"],
          ["122.128638", "37.528518", "500"],
          ["122.128538", "37.528818", "500"],
          ["122.128538", "37.525818", "500"],
          ["122.121538", "37.523318", "500"],
          ["122.127833", "37.525448", "500"],
          
          ["122.128833", "37.526448", "500"],
          ["122.128638", "37.522818", "500"],
          ["122.128738", "37.522818", "500"],
          ["122.128638", "37.528518", "500"],
          ["122.128538", "37.528818", "500"],
          ["122.128538", "37.525818", "500"],
          ["122.121538", "37.523318", "500"],
          ["122.127833", "37.525448", "500"],
   
          ["122.128833", "37.526448", "500"],
          ["122.128638", "37.522818", "500"],
          ["122.128738", "37.522818", "500"],
          ["122.128638", "37.528518", "500"],
          ["122.128538", "37.528818", "500"],
          ["122.128538", "37.525818", "500"],
          ["122.121538", "37.523318", "500"],
          ["122.127833", "37.525448", "500"],

          ["122.128833", "37.526448", "500"],
          ["122.128638", "37.522818", "500"],
          ["122.128738", "37.522818", "500"],
          ["122.128638", "37.528518", "500"],
          ["122.128538", "37.528818", "500"],
          ["122.128538", "37.525818", "500"],
          ["122.121538", "37.523318", "500"],
          ["122.127833", "37.525448", "500"],

          ["122.128833", "37.526448", "500"],
          ["122.128638", "37.522818", "500"],
          ["122.128738", "37.522818", "500"],
          ["122.128638", "37.528518", "500"],
          ["122.128538", "37.528818", "500"],
          ["122.128538", "37.525818", "500"],
          ["122.121538", "37.523318", "500"],
          ["122.127833", "37.525448", "500"],

      ],
      deviceId:'DESKTOP-L56LKGM',
      zuobianData:[],
      toJavaCoordinates:[],
      weilanName:[],
    }
  },

  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: {
    //后台获取数据——获取电子围栏
    getCoordinate() {
      let that = this;
      HttpReq.truckDispatching.screenMapSetUpQuery({size:9999}).then((res) => {
				if(true){;
          let data1 = [];
          for(let key  in res){
            that.weilanName.push(key);
            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); 
          
          this.getlishiguijiFn();

				}
			})

    },
    //后台获取数据——获取实时位置
    getlishiguijiFn() {
      let that = this;
      HttpReq.truckDispatching.getCarTrajectoryQuery().then((res) => {
        //console.log(res);
				if(res.code == 200){
          that.historyTrajectoryData = res.data;

          this.$nextTick(()=>{
            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.historyTrajectoryData.forEach((item,index)=>{
      //   var graphicLayer4 = new mars3d.layer.GraphicLayer();
      //   map.addLayer(graphicLayer4)
      //   that.addDemoGraphics(graphicLayer4,item);
      // })

      // 抛出事件
      this.$emit('onload', map)
    },
    //围栏回显
    addGraphic_01(graphicLayer,positions,weilanName){
      let graphic = new mars3d.graphic.PolygonEntity({
          positions: positions,
          style: {
            color: "red",
            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,
            },
          },
        });
        graphicLayer.addGraphic(graphic); //还可以另外一种写法: graphic.addTo(graphicLayer)
    },
    getSampledPositionProperty(points){
      let property = new Cesium.SampledPositionProperty();
      let start = this.map.clock.currentTime;
      let positions = mars3d.LatLngArray.toCartesians(points);
      for (let i = 0; i < positions.length; i++) {
        let time = Cesium.JulianDate.addSeconds(start, i * 20, new Cesium.JulianDate());
        let position = positions[i];
        property.addSample(time, position);
      }
      return property;
    },
    //实时位置
    addDemoGraphics(graphicLayer4,item) {
      let that = this;
      const graphic = new mars3d.graphic.ModelPrimitive({
        style: {
          url: "//data.mars3d.cn/gltf/mars/car/tufangche.glb",
          scale: 0.1,
          minimumPixelSize: 50,
          // 高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
          highlight: {
            type: mars3d.EventType.click,
            silhouette: true,
            silhouetteColor: "#ff0000",
            silhouetteSize: 4
          },
          label: {
            // 不需要文字时，去掉label配置即可
            text: item.name,
            font_size: 16,
            color: "#ffffff",
            outline: true,
            outlineColor: "#000000",
            pixelOffsetY: -20,
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 50000,
            distanceDisplayCondition_near: 0
          }
        },
      })
      graphicLayer4.addGraphic(graphic)

      // 设置动态位置
      graphicLayer4.eachGraphic((graphic) => {
        graphic.addDynamicPosition(Cesium.Cartesian3.fromDegrees(item.lat, item.lon, 500)) // 首次出现的位置
      })
      graphicLayer4.eachGraphic((graphic) => {
        graphic.addDynamicPosition(that.randomPoint(item.name), 6) // 按6秒运动至指定位置
      })

      // 定时更新动态位置（setInterval为演示）
      // setInterval(() => {
      //   graphicLayer4.eachGraphic((graphic) => {
      //     graphic.addDynamicPosition(that.randomPoint(item.name), 6)
      //   })
      // }, 6000)
    },
    // 取区域内的随机点
    randomPoint(name) {
      HttpReq.truckDispatching.getCarTrajectoryQuery({name:name}).then((res) => {
				if(res.code == 200){
          return Cesium.Cartesian3.fromDegrees(res.data[0].lat, res.data[0].lon, 500)
        }
			})
    },
    
  }
}
</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>
