<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;
//画测距属性
var graphicLayerPolyline;
var currentTimeInterval = null;

export default {
  name: 'mars3dViewer',
  
  mounted(){
    
  },

  data(){
    return{
      historyTrajectoryData:[],
      deviceId:'DESKTOP-L56LKGM',
      zuobianData:[],
      toJavaCoordinates:[],
      weilanName:[],
      carNumber:'',
      carPlaySpeed:1,
      stopPointData:[],
      leadTime:false,
    }
  },

  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(equipmentName,number,speed,bTime,eTime,stopPointData,leadTimeShow) {
      if(currentTimeInterval){
        clearInterval(currentTimeInterval)
        currentTimeInterval = null;
      }
      let that = this;
      that.deviceId = equipmentName;
      that.carNumber = number;
      that.carPlaySpeed = speed;
      that.stopPointData = stopPointData;
      that.leadTime = leadTimeShow;
      //获取历史轨迹
      if(number == ''){
        return
      }else{
        if(that.deviceId == '' || that.deviceId == undefined){
          this.$notify({
						title: '暂无轨迹数据！',
						type: 'warning',
						duration: 2500
					});
        }else{
          HttpReq.truckDispatching.getAllHistroyCarTrajectoryQuery({name:that.deviceId,bTime:bTime,eTime:eTime}).then((res) => {
            if(res.code == 200){
              if(res.data.line.length == 0){
                this.$notify({
                  title: '暂无轨迹数据！',
                  type: 'warning',
                  duration: 2500
                });
              }else{
                let obj1 = {};
                let array1 = [];
                res.data.line.forEach((item,index)=>{
                  let array2 = [];
                  array2.push(item.lon);
                  array2.push(item.lat);
                  array2.push(1000);
                  array2.push(new Date(item.time).toISOString());
                  array1.push(array2);
                })
                obj1.name = res.data.name;
                obj1.arrays = array1;
                let hisCenterData = [];
                hisCenterData.push(obj1);
                that.historyTrajectoryData = [...hisCenterData];

                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;

      const mapOptions = {
        ...options,
        ...this.options,
        control: {
          "homeButton": true,
          "baseLayerPicker": true,
          "sceneModePicker": false,
          "vrButton": false,
          "fullscreenButton": true,
          "navigationHelpButton": true,
          "animation": false,
          "timeline": false,
          "infoBox": false,
          "geocoder": false,
          "geocoderConfig": {
            "key": [
              "ae29a37307840c7ae4a785ac905927e0"
            ]
          },
          "selectionIndicator": false,
          "defaultContextMenu": false,
          "mouseDownView": true,
          "compass": {
            "bottom": "240px",
            "right": "2px"
          },
          "distanceLegend": {
            "left": "100px",
            "bottom": "0px"
          },
          "locationBar": {
            "fps": true,
            "template": "<div>经度:{lng}</div> <div>纬度:{lat}</div><div>海拔：{alt}米</div> <div>层级：{level}</div><div>方向：{heading}度</div> <div>俯仰角：{pitch}度</div><div>视高：{cameraHeight}米</div>"
          }
        },
        scene:{
          "clock":{
            currentTime: that.currentTime1(that.historyTrajectoryData[0].arrays[0][3]),
            shouldAnimate: true,
            multiplier:1,
          },
          "center": {"lat":37.4890,"lng":122.04659,"alt":1000,"heading":360,"pitch":-90},
          "scene3DOnly": false,
          "shadows": false,
          "removeDblClick": true,
          "sceneMode": 2,
          "showSun": true,
          "showMoon": true,
          "showSkyBox": true,
          "showSkyAtmosphere": true,
          "fog": true,
          "fxaa": true,
          "globe": {
            "depthTestAgainstTerrain": false,
            "baseColor": "#546a53",
            "showGroundAtmosphere": true,
            "enableLighting": false
          },
          "cameraController": {
            "zoomFactor": 3.0,
            "minimumZoomDistance": 100,
            "maximumZoomDistance": 50000000,
            "enableRotate": true,
            "enableTranslate": true,
            "enableTilt": true,
            "enableZoom": true,
            "enableCollisionDetection": true,
            "minimumCollisionTerrainHeight": 15000
          }
        },
      }

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

      //历史轨迹回放
      that.historyTrajectoryData.forEach(function(item,index){
        var graphicLayer2 = new mars3d.layer.GraphicLayer();
        map.addLayer(graphicLayer2);
        var itemText = `<table style="width: auto;">
                <tr>
                  <th scope="col" colspan="2" style="text-align:center;font-size:15px;">卡车号码：${that.carNumber}</th>
                </tr>
                <tr>
                  <td>设备名称：${that.deviceId}</td>
                </tr>
              </table>`;
        initGraphicManager(graphicLayer2,itemText);
        that.addGraphic_02(graphicLayer2,item.arrays,that.carNumber);
      })
     
      //停车区域
      that.stopPointData.forEach((item,index)=>{
        var graphicLayer2 = new mars3d.layer.GraphicLayer();
        map.addLayer(graphicLayer2);
        initGraphicManager(graphicLayer2);
        that.addDemoGraphic1(graphicLayer2,item.lon,item.lat,item.alarmTime,item.time);
      })

      //画测距
      //graphicLayerPolyline = new mars3d.layer.GraphicLayer();
      //that.bindLayerContextMenu(graphicLayerPolyline);
      //map.addLayer(graphicLayerPolyline);

      // 抛出事件
      this.$emit('onload', map)
    },
    //车辆轨迹1
    addGraphic_02(graphicLayer2,positions,truckName) {
        let that = this;
        var property = new Cesium.SampledPositionProperty();
        var tempTime;
        //起点
        tempTime = map.clock.currentTime; //开始时间
        property.addSample(tempTime, Cesium.Cartesian3.fromDegrees(positions[0][0],positions[0][1],positions[0][2]));
        for(let i = 1;i < positions.length;i++){
          tempTime = Cesium.JulianDate.addSeconds(tempTime, (Date.parse(new Date(positions[i][3])) - Date.parse(new Date(positions[i-1][3]))) / 1000, new Cesium.JulianDate());
          property.addSample(tempTime, Cesium.Cartesian3.fromDegrees(positions[i][0],positions[i][1],positions[i][2]));
        }

        //将当前进度时间传给父组件
        currentTimeInterval = setInterval(function(){
          that.$parent.progressTimeFn(that.currentTime1(map.clock.currentTime));
        },1000)

        var graphic = new mars3d.graphic.PathEntity({
          position: property,
          style: {
            width: 4,
            color: "rgb(251,84,48)",
            opacity: 1.0,
            leadTime: that.leadTime ? 9999 : 0, // 前方的路线不显示
            trailTime: that.leadTime ? 9999 : 0,
            //高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
            highlight: {
              type: mars3d.EventType.click,
              color: "#ff0000",
            },
          },
          label: {
            //text: truckName,
            font_size: 22,
            font_family: "楷体",
            color: Cesium.Color.AZURE,
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(10, -25), //偏移量
          },
          model: {
            url: '//data.mars3d.cn/gltf/mars/car/tufangche.glb',
            scale: 0.1,
            minimumPixelSize: 50,
          },
        });
        graphicLayer2.addGraphic(graphic); //还可以另外一种写法: graphic.addTo(graphicLayer)

    },
    //停车区域
    addDemoGraphic1(graphicLayer,x,y,alarmTime,time) {
      const graphic = new mars3d.graphic.CircleEntity({
        position: [x, y, 10000],
        style: {
          radius: 5.0,
          color: "#00ff00",
          opacity: 0.2,
          outline: true,
          outlineWidth: 3,
          outlineColor: "#ffffff",
          clampToGround: true,
          label: {
            text: alarmTime + "\n停车" + time + '分钟',
            font_size: 16,
            color: Cesium.Color.AZURE,
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            pixelOffsetY: 0,
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 500000,
            distanceDisplayCondition_near: 0
          }
        },
      })
      graphicLayer.addGraphic(graphic)
    },
    //测距画线
    startDrawGraphic(boo) {
      let that = this;
      if(boo){
        graphicLayerPolyline.startDraw({
          type: "polyline",
          //maxPointNum: 2, //可以限定最大点数，2个点绘制后自动结束
          style: {
            color: "#55ff33",
            width: 3,
            clampToGround: false,
            label: {
              font_size: 18,
              color: "#ffffff",
              distanceDisplayCondition: true,
              distanceDisplayCondition_far: 500000,
              distanceDisplayCondition_near: 0
            }
          },
          success: function (graphic){
            for(let i = 0,len = graphic._positions_draw.length;i <  len - 1;i++){
              //第一个坐标
              var cartographic1 = Cesium.Cartographic.fromCartesian(graphic._positions_draw[i]);
              var lat1 = Cesium.Math.toDegrees(cartographic1.latitude);
              var lon1 = Cesium.Math.toDegrees(cartographic1.longitude);
              //第二个坐标
              var cartographic2 = Cesium.Cartographic.fromCartesian(graphic._positions_draw[i + 1]);
              var lat2 = Cesium.Math.toDegrees(cartographic2.latitude);
              var lon2 = Cesium.Math.toDegrees(cartographic2.longitude);
              //中间坐标
              let position1 = that.getCenterLonLat(lon1,lat1,lon2,lat2);
              let distance1 = that.getDistance(lat1,lon1,lat2,lon2);
              //添加文字
              const graphicLabel = new mars3d.graphic.LabelEntity({
                position: position1,
                style: {
                  text: distance1 + '米',
                  font_size: 35,
                  scale: 0.5,
                  font_family: "楷体",
                  color: "#00ffff",
                  outline: true,
                  outlineColor: "#000000",
                  outlineWidth: 2,
                  horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  visibleDepth: false
                },
              })
              graphicLayerPolyline.addGraphic(graphicLabel)
            }

          }
        })
      }else{
        graphicLayerPolyline.stopDraw();
      }
      
    },
    //添加测距画线右键菜单
    bindLayerContextMenu(graphicLayer) {
      graphicLayer.bindContextMenu([
        // {
        //   text: "开始编辑对象",
        //   icon: "fa fa-edit",
        //   show: function (e) {
        //     const graphic = e.graphic
        //     if (!graphic || !graphic.hasEdit) {
        //       return false
        //     }
        //     return !graphic.isEditing
        //   },
        //   callback: (e) => {
        //     const graphic = e.graphic
        //     if (!graphic) {
        //       return false
        //     }
        //     if (graphic) {
        //       graphicLayer.startEditing(graphic)
        //     }
        //   }
        // },
        // {
        //   text: "停止编辑对象",
        //   icon: "fa fa-edit",
        //   show: function (e) {
        //     const graphic = e.graphic
        //     if (!graphic || !graphic.hasEdit) {
        //       return false
        //     }
        //     return graphic.isEditing
        //   },
        //   callback: (e) => {
        //     const graphic = e.graphic
        //     if (!graphic) {
        //       return false
        //     }
        //     if (graphic) {
        //       graphic.stopEditing()
        //     }
        //   }
        // },
        {
          text: "删除对象",
          icon: "fa fa-trash-o",
          show: (event) => {
            const graphic = event.graphic
            if (!graphic || graphic.isDestroy) {
              return false
            } else {
              return true
            }
          },
          callback: (e) => {
            // const graphic = e.graphic
            // if (!graphic) {
            //   return
            // }
            // const parent = graphic.parent // 右击是编辑点时
            // graphicLayer.removeGraphic(graphic)
            // if (parent) {
            //   graphicLayer.removeGraphic(parent)
            // }
            // map.removeLayer(graphicLayer);
          }
        },
        // {
        //   text: "计算长度",
        //   icon: "fa fa-medium",
        //   callback: (e) => {
        //     const graphic = e.graphic
        //     const strDis = mars3d.MeasureUtil.formatDistance(graphic.distance)
        //     alert("该对象的长度为:" + strDis)
        //   }
        // }
      ])
    },
    //两个点的经纬度得出中间点的经纬度
    getCenterLonLat(oneLon, oneLat, twoLon, twoLat) {
      //oneLon：第一个点的经度；oneLat：第一个点的纬度；twoLon：第二个点的经度；twoLat：第二个点的纬度；
        let aLon = 0, aLat = 0;
        let bLon = Number(oneLon) - Number(twoLon);
        let bLat = Number(oneLat) - Number(twoLat);
        //Math.abs()绝对值
        if( bLon > 0){
            aLon = Number(oneLon) - Math.abs(bLon) / 2;
        }else{
            aLon = Number(twoLon) - Math.abs(bLon) / 2;
        }
        if( bLat > 0){
            aLat = Number(oneLat) - Math.abs(bLat) / 2;
        }else{
            aLat = Number(twoLat) - Math.abs(bLat) / 2;
        }
        return [aLon, aLat ,1000];
    },
    //根据两个经纬度计算距离
		getDistance(lat1, lng1, lat2, lng2) {
			var radLat1 = lat1 * Math.PI / 180.0;
			var radLat2 = lat2 * Math.PI / 180.0;
			var a = radLat1 - radLat2;
			var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			s = s * 6378.137 // EARTH_RADIUS;
			s = Math.round(s * 10000) / 10;
			return s
		},
    currentTime1(time){
      var date = new Date(time);
      var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
      var hours = date.getHours();          //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes();      //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds();      //秒 ,返回 Date 对象的秒数 (0 ~ 59)   
      //修改月份格式
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      //修改日期格式
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      //修改小时格式
      if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
      }
      //修改分钟格式
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      //修改秒格式
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      //获取当前系统时间  格式(yyyy-mm-dd hh:mm:ss)
      let currentFormatDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      return currentFormatDate;
    },
    //暂停继续
    pauseResume(boo){
      map.clock.shouldAnimate = boo;
    },
    //改变倍速
    changeSpeed(num){
      map.clock.multiplier = parseInt(num);
    },
    //改变时间
    changeTime(time){
      let julian_time = Cesium.JulianDate.fromDate(new Date(time));
      map.clock.currentTime = julian_time;
    },
    //清除定时器
    closeInterval(){
      if(currentTimeInterval){
        clearInterval(currentTimeInterval)
        currentTimeInterval = null;
      }
    },
  }
}
</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: 100%;
  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>
