<template>
    <div style="wight:100%;height:100%;position: relative;">
      <div :id="`mars3d-container${mapKey}`"
      :class="['mars3d-container', customClass, { 'mars3d-container-compare-rh' : compare }]"></div>
  
      <div class="infoview">
        <div style="display: inline-block;color:red;font-weight:bolder;">每次只允许提交保存一个关键点</div>
      </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'
  import zhuangchetubiao from '../../assets/images/cutGraph/zhuangchedian1.png'
  import xiechetubiao from '../../assets/images/cutGraph/xiechedian1.png'
  import kongzhidiantubiao from '../../assets/images/cutGraph/kongzhidian1.png'
  
  
  // 导入插件(其他插件类似，插件清单访问：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{
        zuobianData:[],
        toJavaCoordinates:[],
        controlPointId:0,
        lineData:[],
        weilanzuobianData:[],
        weilanName:[],
        areaColorData:[],
      }
    },
  
    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(data) {
        let that = this;
        this.zuobianData = data;
        HttpReq.truckDispatching.apiPathmapQuery({size:9999}).then((res) => {
          if(res.code == 200){
            let arr1 = [];
            HttpReq.truckDispatching.apiCpointQuery({size:9999}).then((res1) => {
              res.data.content.forEach((item1,index1)=>{
                let obj1 = {};
                obj1.text = item1.weight + '分钟';
                obj1.start = [];
                obj1.end = [];
                res1.data.content.forEach((item2,index2)=>{
                  if(item1.start == item2.name){
                    obj1.start.push(parseFloat(item2.lon));
                    obj1.start.push(parseFloat(item2.lat));
                    obj1.start.push(500);
                  }
                })
                res1.data.content.forEach((item2,index2)=>{
                  if(item1.end == item2.name){
                    obj1.end.push(parseFloat(item2.lon));
                    obj1.end.push(parseFloat(item2.lat));
                    obj1.end.push(500);
                  }
                })
                arr1.push(obj1);
              });
              this.lineData = arr1;

              //获取电子围栏
              HttpReq.truckDispatching.screenMapSetUpQuery({size:9999}).then((res) => {
                if(true){;
                  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.weilanzuobianData = data1

                  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)// 构建地图
                      })
                    }
                  })
                  
                }
              })
            })
          }
        })
        
      },
      //上传关键点数据
      uploaded(text,type,way,arr1){
        if(way == 'add'){
          if(JSON.stringify(this.toJavaCoordinates) == '[]'){
            this.$notify({
              title: '未选择'+ type +'位置！',
              type: 'error',
              duration: 2500
            })
          }else{
            if(type == '控制点'){
              let lastData = {};
              lastData.name = text;
              lastData.type = type;
              lastData.lon = this.toJavaCoordinates[0][0];
              lastData.lat = this.toJavaCoordinates[0][1];
              HttpReq.truckDispatching.apiCpointAdd(lastData).then((res) => {
                this.$notify({
                  title: '关键点信息上传中，请勿操作！',
                  type: 'success',
                  duration: 2000,
                  dangerouslyUseHTMLString: true,
                });
                if(res.code == 200){
                  arr1.forEach((item,index)=>{
                    HttpReq.truckDispatching.apiPathmapAdd(item).then((res1) => {})
                  })
                  this.$nextTick(()=>{
                    this.$notify({
                      title: '关键点信息上传成功！',
                      type: 'success',
                      duration: 2000,
                      dangerouslyUseHTMLString: true,
                    });
                    this.$parent.resetData();
                  })
                }
              })
            }else{
              let lastData = {};
              lastData.name = text;
              lastData.type = type;
              lastData.lon = this.toJavaCoordinates[0][0];
              lastData.lat = this.toJavaCoordinates[0][1];
              HttpReq.truckDispatching.apiCpointAdd(lastData).then((res) => {
                this.$notify({
                  title: '关键点信息上传中，请勿操作！',
                  type: 'success',
                  duration: 2000,
                  dangerouslyUseHTMLString: true,
                });
                this.$nextTick(()=>{
                  if(res.code == 200){
                    this.$notify({
                      title: '关键点信息上传成功！',
                      type: 'success',
                      duration: 2000,
                      dangerouslyUseHTMLString: true,
                    });
                    this.$parent.resetData();
                  }
                })
              })
            }
          }
        }else if(way == 'edit'){
          if(type == '控制点'){
            //获取起点为该控制点的数据
            HttpReq.truckDispatching.apiPathmapQuery({size:9999,start:text}).then((res1) => {
              if(res1.code == 200){
                let idArr1 = [];
                res1.data.content.forEach((item1,index1)=>{
                  idArr1.push(item1.id);
                })
                //获取终点为该控制点的数据
                HttpReq.truckDispatching.apiPathmapQuery({size:9999,end:text}).then((res2) => {
                  if(res2.code == 200){
                    res2.data.content.forEach((item2,index2)=>{
                      idArr1.push(item2.id);
                    })
                    //删除
                    HttpReq.truckDispatching.apiPathmapDel(idArr1).then((resDel1) => {
                      //重新添加
                      let lastData = {};
                      lastData.id = this.controlPointId;
                      lastData.name = text;
                      HttpReq.truckDispatching.apiCpointUpdate(lastData).then((res3) => {
                        this.$notify({
                          title: '关键点信息上传中，请勿操作！',
                          type: 'success',
                          duration: 2000,
                          dangerouslyUseHTMLString: true,
                        });
                        if(res3.code == 200){
                          arr1.forEach((itemAdd1,indexAdd1)=>{
                            HttpReq.truckDispatching.apiPathmapAdd(itemAdd1).then((res4) => {})
                          })
                          this.$nextTick(()=>{
                            this.$notify({
                              title: '关键点信息上传成功！',
                              type: 'success',
                              duration: 2000,
                              dangerouslyUseHTMLString: true,
                            });
                            this.$parent.resetData();
                          })
                        }
                      })
                    })
                  }
                })
              }
            })

          }else{
            let lastData = {};
            lastData.id = this.controlPointId;
            lastData.name = text;
            HttpReq.truckDispatching.apiCpointUpdate(lastData).then((res) => {
              this.$notify({
                title: '关键点信息上传中，请勿操作！',
                type: 'success',
                duration: 2000,
                dangerouslyUseHTMLString: true,
              });
              this.$nextTick(()=>{
                if(res.code == 200){
                  this.$notify({
                    title: '关键点信息上传成功！',
                    type: 'success',
                    duration: 2000,
                    dangerouslyUseHTMLString: true,
                  });
                  this.$parent.resetData();
                }
              })
            })
          }
        }
        
      },
      //创建地图
      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.weilanzuobianData.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]);
        })
        
        //关键点显示
        that.zuobianData.forEach(function(item,index){
          var graphicLayer = new mars3d.layer.GraphicLayer();
          map.addLayer(graphicLayer);
          initLayerManager(graphicLayer);
          that.bindLayerPopup(graphicLayer,item)
          that.addDemoGraphic1(graphicLayer,item);
        })

        //画线
        that.lineData.forEach(function(item,index){
          var graphicLayer = new mars3d.layer.GraphicLayer();
          map.addLayer(graphicLayer);
          initLayerManager(graphicLayer);
          that.addDemoGraphic2(graphicLayer,item);
        })
        
        //webgl渲染失败后，刷新页面
        map.on(mars3d.EventType.renderError,function(event){
          window.location.reload();
        });

        // 抛出事件
        this.$emit('onload', map)
      },
      //关键点位置
      addDemoGraphic1(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'},
          },
        })
        graphicLayer.addGraphic(graphic)
      },
      //围栏回显
      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,
              },
            },
          });
          graphicLayer.addGraphic(graphic); //还可以另外一种写法: graphic.addTo(graphicLayer)
      },
      //画线
      addDemoGraphic2(graphicLayer,item) {
        const graphic = new mars3d.graphic.PolylineEntity({
          positions: [item.start,item.end],
          style: {
            width: 6,
            materialType: mars3d.MaterialType.PolylineOutline,
            color: Cesium.Color.ORANGE,
            outlineWidth: 2,
            outlineColor: Cesium.Color.BLACK,
            label: {
              text: item.text,
              font_size: 18,
              color: "black",
              distanceDisplayCondition: true,
              distanceDisplayCondition_far: 500000,
              distanceDisplayCondition_near: 0
            }
          },
        })
        graphicLayer.addGraphic(graphic)
      },
      //关键点设置
      btnStartDraw(){
        this.toJavaCoordinates = [];
        let that = this;
        var graphicLayer3 = new mars3d.layer.GraphicLayer();
        map.addLayer(graphicLayer3);
        initLayerManager(graphicLayer3);
        graphicLayer3.startDraw({
          type: "point",
          style: {
            color: "red",
            outline: true,
            outlineColor: "red",
            outlineWidth: 10,
            label: {
              text: '新增关键点',
              font_size: 18,
              color: "blue",
              distanceDisplayCondition: true,
              distanceDisplayCondition_far: 500000,
              distanceDisplayCondition_near: 0,
              pixelOffset: new Cesium.Cartesian2(10, -25), //偏移量
            },
          },
          success: function (graphic){
            var mpt = mars3d.LatLngPoint.fromCartesian(graphic._position_draw);
            that.toJavaCoordinates.push(mpt.toString().split(','));
          }
        });
      },
      bindLayerPopup(graphicLayer,item) {
        let that = this;
        graphicLayer.bindPopup(function (event) {
          that.$parent.clickPointFn(item);
          that.controlPointId = item.id;
        })
      },
     
    }
  }
  </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: 10px;
    left: 10px;
    width: 50vw;
    z-index: 1000;
  }
  </style>
  