<template>
  <div class="box">
    <div class="box-name">水源</div>
    <div class="close-button" @click="close">
          <i class='el-icon el-icon-close'></i>
      </div>
    <div class="box-container">
        <div class="flex" style="margin:10px 0">
          <span style="width:80px;text-align:right;color: #fff;">距离：</span>
          <div>
            <el-radio-group v-model="distanceradio" @input="radioChange">
              <el-radio :label="1" class="mr-1">1km内</el-radio>
              <el-radio :label="2" class="mr-1">5km内</el-radio>
              <el-radio :label="3" class="mr-1">10km内</el-radio>
              <el-radio :label="5">全部</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="table-body">
            <div class="item" v-for="(item,index) in nestWaterPoints" :key="index">
                <div>{{item.name ? item.name:'水源地'}}</div>
                <div>{{item.xsl ? item.xsl : '未知'}}</div>
                <div>{{item.distance}}km</div>
                <div class="float:right;text-align:right;">
                  <i class="el-icon el-icon-position" @click="flyToPosition([item.lngLat[0],item.lngLat[1]])"></i>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import appConfig from '../../../../public/config/app.json'
import {transformGCJ2WGS} from '../lib/GCJ02ToWGS84.js'
import * as turf from '@turf/turf'
import { parse } from '../lib/handleGeojson'
import axios from "axios";
  export default {
    name: 'monitorbox',
    props:['globalmap','waterCenter'],
    data(){
        return{
            startLngLat: null,
            list:[],
            waterPoints:null,
            nestWaterPoints:[],
            echartsLayer:null,
            waterGraphicLayer: null,
            waterGraphicLayerArr:[],
            pathPointGraphicLayer:null,
            allData:[],
            distanceradio:5
        }
    },
    watch:{
      waterCenter:{
        handler(newVal,oldVal) {
          this.getWaterList();
        },
        immediate: true,
        // 开启深度监听 deep
        deep: true
      }
    },
    created(){
        this.getWaterList();
    },
    methods:{
      handleGaodeData(gaodePath){
            let lineString = "MULTILINESTRING(";
            gaodePath.route.paths[0].steps.forEach((item,index)=>{
                if(index == gaodePath.route.paths[0].steps.length-1){
                lineString+="("+item.polyline+")"

                }else{
                lineString+="("+item.polyline+")-"

                }
            })
           lineString+=")";

           let a = lineString.replace(/,/g," ");
           let b = a.replace(/;/g,",");
           let c = b.replace(/-/g,',');
           console.log("ccc",parse(c));
           let geojson  = parse(c);
           let geojson2 ={...geojson}
           geojson.coordinates.forEach((item,index)=>{
            item.forEach((it,idx)=>{
               let a =  transformGCJ2WGS(it[1],it[0]);
                geojson.coordinates[index][idx]=[a.lon,a.lat]     
               console.log("aaa",a);
            })
           })
            this.drawRoutePath(geojson);
        },
      close(){
        if(this.waterGraphicLayer){
          this.waterGraphicLayer.clear();
        }
        if(this.echartsLayer){
          this.echartsLayer.remove(true);
        }
          this.waterGraphicLayerArr.forEach(item =>{
            this.waterGraphicLayer.removeGraphic(item)
          })
          this.$emit('close')
          this.drawRoutePath()
      },
      radioChange(e){
          let arr = this.allData
          let newArr = []
          if(this.distanceradio == 1){
            arr.forEach(item =>{
              if(item.distance < 1){
                newArr.push(item)
              }
            })
            this.nestWaterPoints = newArr
          }
          if(this.distanceradio == 2){
            arr.forEach(item =>{
              if(item.distance >= 1 && item.distance < 5){
                newArr.push(item)
              }
            })
            this.nestWaterPoints = newArr
          }
          if(this.distanceradio == 3){
            arr.forEach(item =>{
              if(item.distance >= 5 && item.distance < 10){
                newArr.push(item)
              }
            })
            this.nestWaterPoints = newArr
          }
          if(this.distanceradio == 4){
            arr.forEach(item =>{
              if(item.distance >= 10){
                newArr.push(item)
              }
            })
            this.nestWaterPoints = newArr
          }
          if(this.distanceradio == 5){
            this.nestWaterPoints = arr
          }
          this.nestWaterPoints.sort((a,b)=>{
            return a.distance - b.distance
          })

          if(this.waterGraphicLayer == null){
              this.waterGraphicLayer = new mars3d.layer.GraphicLayer();
              this.globalmap.addLayer(this.waterGraphicLayer);
          }
          this.waterGraphicLayerArr.forEach(item =>{
            this.waterGraphicLayer.removeGraphic(item)
          })
        
          this.waterGraphicLayerArr = [] 
          this.nestWaterPoints.forEach((item,index)=>{
              let graphic = new mars3d.graphic.BillboardEntity({
                  position: [item.lngLat[0],item.lngLat[1]],
                  style: {
                      image: "img/water.png",
                      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 200000), // 按视距距离显示
                      scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 200000, 0.2),
                      clampToGround: true
                  },
                  attr: { remark: "" },
                  pointerEvents: true
              })
              this.waterGraphicLayerArr.push(graphic)

              this.waterGraphicLayer.addGraphic(graphic);

          })

        },
        getWaterList(){
            axios({
                method: 'get',
                url: appConfig['pingyixian'].waterUrl,
            }).then(res => {
                this.waterPoints = res.data;
                console.log("waterPoints",this.waterPoints);
                this.getNestPoint(this.waterCenter[0],this.waterCenter[1]);
                setTimeout(()=>{
                    this.radioChange()
                },1000)
            })
        },
        getNestPoint(lng,lat){
          console.log("lng,lat",lng,lat);
          let from = turf.point([lng,lat]);
          this.nestWaterPoints = [];

          this.waterPoints.features.forEach((item,index)=>{
            let to = turf.point(item.geometry.coordinates);
            let options = {units: 'kilometers'};
            let distance = turf.distance(from, to, options);
            let obj = {
              lngLat:item.geometry.coordinates,
              distance:distance.toFixed(2),
              name:item.properties.name,
              xsl:item.properties.xsl
            }
            this.nestWaterPoints.push(obj);
          })
          // 
          this.nestWaterPoints.sort((a,b)=>{
            return a.distance - b.distance;
          })

          this.nestWaterPoints = this.nestWaterPoints.slice(0,15);
          this.allData = this.nestWaterPoints

          if(this.waterGraphicLayer == null){
              this.waterGraphicLayer = new mars3d.layer.GraphicLayer();
              this.globalmap.addLayer(this.waterGraphicLayer);
          }
          this.waterGraphicLayerArr.forEach(item =>{
            this.waterGraphicLayer.removeGraphic(item)
          })
        
          this.waterGraphicLayerArr = [] 
          this.nestWaterPoints.forEach((item,index)=>{
              let graphic = new mars3d.graphic.BillboardEntity({
                  position: [item.lngLat[0],item.lngLat[1]],
                  style: {
                      image: "img/water.png",
                      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 200000), // 按视距距离显示
                      scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 200000, 0.2),
                      clampToGround: true
                  },
                  attr: { remark: "示例11" },
                  pointerEvents: true
              })
              this.waterGraphicLayerArr.push(graphic)

              this.waterGraphicLayer.addGraphic(graphic);

          })
          
          let options = this.getEchartsOption(lng,lat,this.nestWaterPoints)
          if(this.echartsLayer){
            this.echartsLayer.remove(true);
          }
          this.echartsLayer = new mars3d.layer.EchartsLayer(options)
          this.globalmap.addLayer(this.echartsLayer)
          this.echartsLayer.flyTo();
        },
        getEchartsOption(lng,lat,nestWaterPoints) {
          const beijinCoord = [lng, lat]
          const symbolPoint = "image://img/symbol1.png"
          const linePoint = "image://img/linePoint1.png"

          const pointArr = []
          const pathArr = [];
          console.log("nestWaterPoints",nestWaterPoints)
          for(let i=0;i<15;i++){
            pointArr.push({
              name: nestWaterPoints[i].distance+"km",
              value: nestWaterPoints[i].lngLat,
              symbol: symbolPoint
            })
            pathArr.push({
              name: i,
              toname: "当前位置",
              coords: [nestWaterPoints[i].lngLat, beijinCoord]
            })
          }

          const option = {
            animation: false,
            clampToGround:true,
            series: [
              {
                name: "",
                type: "lines",
                coordinateSystem: "mars3dMap",
                zlevel: 1,
                data: pathArr,
                // 线上面的动态特效
                effect: {
                  show: true,
                  smooth: false,
                  trailLength: 0,
                  symbol: linePoint,
                  symbolSize: [10, 30],
                  period: 4
                },
                lineStyle: {
                  normal: {
                    width: 3,
                    color: "#1c67d6",
                    curveness: 0.2
                  }
                }
              },
              {
                type: "effectScatter",
                coordinateSystem: "mars3dMap",
                zlevel: 3,
                data: [
                  {
                    name: "当前位置",
                    value: beijinCoord.concat(200)
                  }
                ],
                rippleEffect: {
                  period: 10,
                  scale: 5,
                  brushType: "fill"
                }
              },
              {
                type: "effectScatter",
                coordinateSystem: "mars3dMap",
                symbolSize: [20, 20],
                symbolOffset: [0, -10],
                zlevel: 3,
                circular: {
                  rotateLabel: true
                },
                label: {
                  normal: {
                    show: true,
                    position: "bottom",
                    formatter: "{b}",
                    fontSize: 14,
                    color: "#fff",
                    textBorderColor: "#2aa4e8",
                    offset: [0, 10]
                  }
                },
                itemStyle: {
                  normal: {
                    shadowColor: "none"
                  }
                },
                data: pointArr
              }
            ]
          }
          return option
        },
        flyToPosition(lngLat){
          this.startLngLat = lngLat;
          // this.getRoutePath()
          this.globalmap.flyToPoint(lngLat,{radius:400,"pitch":-90});
          // {"lat":34.984709,"lng":118.253932,"alt":6066,"heading":354,}
        },
        getRoutePath(){ // 获取路线数据
                let startCoor =  this.startLngLat;
                let endCoor = this.waterCenter;
                let _this = this;

                axios({
                    method:"get",
                    url:"https://restapi.amap.com/v3/direction/driving",
                    params:{
                        origin:this.startLngLat.join(","),
                        destination:this.waterCenter.join(","),
                        extensions:"all",
                        key:"583375a3c88c211967c1e924a91a97ef"
                    },
                }).then(res=>{
                    this.handleGaodeData(res.data);
                })

                // axios({
                //     method: 'get',
                //     url: 'http://123.132.248.154:9210/api/FirePrevention/LoadRoad',
                //     headers:{
                //         "X-Token":localStorage.getItem("X-Token"),
                //     },
                //     params: {
                //         startlng: parseFloat(startCoor[0]),
                //         startlat: parseFloat(startCoor[1]),
                //         endlng: parseFloat(endCoor[0]),
                //         endlat: parseFloat(endCoor[1]),
                //     }
                // }).then(data => {
                //     if (data.data.data.length > 0) {
                //         let LineString = data.data.data[0].route;
                //         if(LineString == null || LineString == "null"){
                            
                //         }else{
                //             setTimeout(function () {
                //               console.log("LineStringing",LineString);
                //                _this.drawRoutePath(parse(LineString));
                //                console.log('2222222222')
                //             }, 1000)
                //         }
        
                //     }else{
                        
                //     }
                // })
        },
        drawRoutePath(geojson) { // 绘制路线
            if(this.pathPointGraphicLayer == null){
                this.pathPointGraphicLayer = new mars3d.layer.GraphicLayer();
                this.globalmap.addLayer(this.pathPointGraphicLayer);
            }
            console.log("geojson",geojson);
            this.pathPointGraphicLayer.clear();

            if(geojson && geojson.type=="LineString"){
                geojson.coordinates = [geojson.coordinates]
            }

            // 虚线部分
            var startCoor = this.startLngLat;
            var endCoor =this.waterCenter;
            // 起始点坐标
            var startCoorArr = [parseFloat(startCoor[0]), parseFloat(startCoor[1])]
            // 终点坐标
            var endCoorArr = [parseFloat(endCoor[0]), parseFloat(endCoor[1])]

            var startTurfPoint = turf.point(startCoorArr);
            var endTurfPoint = turf.point(endCoorArr);

            // 起始路线部分
            var startPath = [];
            geojson.coordinates[0].forEach((item, index) => {
                startPath.push(turf.point([item[0], item[1]]));
            })

            var startTurfPath = turf.featureCollection(startPath);
            var startNearestPoint = turf.nearestPoint(startTurfPoint, startTurfPath);

            var startNearestPointLngLat = null;
            if (startNearestPoint) {
                startNearestPointLngLat = startNearestPoint.geometry.coordinates;
                var graphic = new mars3d.graphic.PolylineEntity({
                positions: [
                    startCoorArr,
                    startNearestPointLngLat,
                ],
                style: {
                    width: 5,
                    clampToGround: true,
                    materialType: mars3d.MaterialType.PolylineDash,
                    materialOptions: {
                    color: Cesium.Color.YELLOW,
                    dashLength: 8.0
                    }
                },
                attr: { remark: "虚线" }
                })
                this.pathPointGraphicLayer.addGraphic(graphic)
            }

            // 终点路线部分
            var endPath = [];
            geojson.coordinates[geojson.coordinates.length - 1].forEach((item, index) => {
                endPath.push(turf.point([item[0], item[1]]));
            })
            var endTurfPath = turf.featureCollection(endPath);
            var endNearestPoint = turf.nearestPoint(endTurfPoint, endTurfPath);

            var endNearestPointLngLat = null;
            if (endNearestPoint) {
                endNearestPointLngLat = endNearestPoint.geometry.coordinates;
                var graphic = new mars3d.graphic.PolylineEntity({
                positions: [
                    endCoorArr,
                    endNearestPointLngLat,
                ],
                style: {
                    width: 5,
                    clampToGround: true,
                    materialType: mars3d.MaterialType.PolylineDash,
                    materialOptions: {
                    color: Cesium.Color.YELLOW,
                    dashLength: 8.0
                    }
                },
                attr: { remark: "虚线" }
                })
                this.pathPointGraphicLayer.addGraphic(graphic)
            }

            // 漫游数据
            var tripArr = [];
            // 实线路线部分
            geojson.coordinates.forEach((item, index) => {
                tripArr = tripArr.concat(item);
            })

            var graphic = new mars3d.graphic.PolylineEntity({
                positions: tripArr,
                style: {
                width: 5,
                clampToGround: true,
                materialType: mars3d.MaterialType.LineFlow,
                materialOptions: {
                    color: Cesium.Color.CYAN,
                    image: "/img/line-colour.png",
                    speed: 10
                }
                },
                attr: { remark: "示例13" }
            })
            this.pathPointGraphicLayer.addGraphic(graphic)

            this.pathPointGraphicLayer.flyTo();

            this.tripFlyArray = [];
            tripArr.forEach((item, index) => {
                if (index % 20 == 0) {
                    this.tripFlyArray.push(item);
                }
            })
        
        },
    }
  }
</script>

<style scoped>
  .box{
        width: 100%;
        height: calc( 100% - 5px);;
        overflow: hidden;
        text-align:left;
        z-index: 99;
  }
  .box-name{
      height: 47px;
      line-height: 47px;
      color: #fff;
      font-size: 20px;
      font-weight: bold;
      padding: 0 40px;
    }
  .box-title{
        width:100%;
      height:45px;
      overflow: hidden;
      line-height:40px;
      color:#eee;
      text-align: center;
      font-size:18px;
    }
    .box-container{
        width: calc( 100% - 0px);
        padding:10px 12px;
        height: calc( 100% - 60px);
    }
    .table-header{
        width: calc( 100% - 10px);
        height:25px;
        color:#fff;
        text-align: center;
    }
    .table-header div{
        float:left;
        width:25%;
        border-bottom:1px dashed #008cff;
        padding-bottom:8px;
    }
    .table-body{
        width:100%;
        height: calc( 100% - 25px);
        overflow-y: auto;
    }

     .table-body .item{
         width:100%;
         height:36px;
         background: #00a2ff2f;
         font-size:12px;
         text-align: center;
         line-height:36px;
         cursor:pointer;
     }

     .table-body .item:nth-child(2n){
         background:#00b7ff50;
     }
    
    .table-body .item div{
        float:left;
        width:25%;
        color:#eee;
    }

     ::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb {
  border: 0
}
.close-button{
  position:absolute;
  right:20px;
  top:14px;
  cursor:pointer;
  color:#fff;
  font-weight: bold;
  width:20px;
  height:20px;
  background:#0a43bfcc;
  line-height:20px;
  text-align:center;
}

.el-radio{
    margin-right: 10px;
    color: #fff;
    margin-bottom: 0;
  }

::-webkit-scrollbar {
  height: 10px;
  width: 10px;
  background: transparent;
  border-radius: 5px
}

::-webkit-scrollbar-thumb {
  padding-top: 100px;
  -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px -1px 0 rgba(0, 0, 0, .07);
  background-color: #797979;
  min-height: 28px;
  border-radius: 4px;
  background-clip: padding-box
}

::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb {
  border: 0
}

::-webkit-scrollbar-thumb:hover {
  -webkit-box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25);
  background-color: rgba(0, 0, 0, .4)
}

::-webkit-scrollbar-thumb:active {
  -webkit-box-shadow: inset 1px 1px 3px rgba(0, 0, 0, .35);
  background-color: rgba(0, 0, 0, .5)
}

</style>