<template>
  <div class="box">
    <div class="box-title">最优路线规划</div>
    <div class="box-container">
        <div class="inputer">
            <span style="float:left;">起点：</span>
            <el-input size="mini" style="float:left;width:170px;" v-model="startPoint"></el-input>
            <el-button icon="el-icon-location-outline" size="mini" type="primary" style="float:left;position:relative;top:4px;left:4px;" @click="bindMapClick('start')"></el-button>
        </div>
        <div class="inputer">
            <span style="float:left;">终点：</span>
            <el-input size="mini" style="float:left;width:170px;" v-model="endPoint"></el-input>
            <el-button icon="el-icon-location-outline" size="mini" type="primary" style="float:left;position:relative;top:4px;left:4px;" @click="bindMapClick('end')"></el-button>
        </div>
        <div class="operate-container">
            <div style="background:orange;" @click="removePath">清除路线</div>
            <div @click="getRoutePath">规划路线</div>
            <div @click="tripFly(tripFlyArray)">开始漫游</div>
        </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { parse } from '../lib/handleGeojson.js';
import * as turf from '@turf/turf'
import AppConfig from '../../../../public/config/app.json'
  export default {
    name: 'routebox',
    props:['routeInfo'],
    data(){
        return {
            startPoint:null,
            endPoint:null,
            pathPointGraphicLayer:null,
            tripFlyArray:null,
            contourLine:null,
            contourLineAreaObj:null,
        }
    },
    watch:{
       
    },
    created(){
        
    },
    mounted(){

    },
    destroyed(){

    },
    methods:{
        bindMapClick(type){ //绑定点击事件 绘制获取起始点数据
            if(this.pathPointGraphicLayer == null){
                this.pathPointGraphicLayer = new mars3d.layer.GraphicLayer();
                window.globalmap.addLayer(this.pathPointGraphicLayer);
            }
            let _this = this;
            window.globalmap.setCursor(true)
            window.globalmap.once(mars3d.EventType.click, function (event) {
                window.globalmap.setCursor(false)
                const cartesian = event.cartesian
                const point = mars3d.LngLatPoint.fromCartesian(cartesian)
                point.format() 
                if(type == 'start'){
                    _this.startPoint = point.lng+","+point.lat;
                }else if(type == 'end'){
                    _this.endPoint = point.lng+","+point.lat;
                }
                _this.drawPoint(type, point.lng, point.lat, point.z);
            })
        },
        drawPoint(type, lng, lat, z) { // 绘制起点、终点
            let image = null;
            if (type == "start") {
                image = "/img/route-start.png"
            } else {
                image = "/img/route-end.png"
            }
            var graphic = new mars3d.graphic.BillboardEntity({
                position: [lng, lat, z],
                style: {
                    image: image,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    clampToGround: true
                },
                attr: { remark: type == 'start'?'起点':'终点' }
            })
            this.pathPointGraphicLayer.addGraphic(graphic) // 还可以另
        },
        getRoutePath(){ // 获取路线数据
            if(this.startPoint&&this.endPoint){
                let startCoor =  this.startPoint.split(",");
                let endCoor = this.endPoint.split(",");
                axios({
                    method: 'get',
                    url: AppConfig[localStorage.getItem('areaName')].baseUrl+'/api/FirePrevention/LoadRoad',
                    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{
                            let _this = this;
                            setTimeout(function () {
                               _this.drawRoutePath(parse(LineString));
                                // designPath(parse(LineString));
                            }, 1000)
                        }
        
                    }else{
                        
                    }
                })
            }else{

            }
        },
        drawRoutePath(geojson) { // 绘制路线
            if(geojson.type=="LineString"){
                geojson.coordinates = [geojson.coordinates]
            }

            // 虚线部分
            var startCoor = this.startPoint.split(",");
            var endCoor =this.endPoint.split(",");
            // 起始点坐标
            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;
                this.getContourArea(endNearestPointLngLat,endCoorArr);
                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: item,
                //   style: {
                //     width: 5,
                //     clampToGround: true,
                //     // materialType: mars3d.MaterialType.PolylineDash,
                //     materialOptions: {
                //       color: Cesium.Color.CYAN,
                //       dashLength: 8.0
                //     }
                //   },
                //   attr: { remark: "最优路线" }
                // })
            })

            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);
                }
            })
        
        },
        getContourArea(startCoor,endCoor){
            // 计算两点间的距离
            var from = turf.point(startCoor);
            var to = turf.point(endCoor);
            var options = {units: 'kilometers'};
            var distance = turf.distance(from, to, options);

            distance = distance*1000+200 > 500 ? distance*1000+200 : 500;
            const graphic = new mars3d.graphic.CircleEntity({
                position: endCoor,
                style: {
                radius: distance,
                color: "#00ff00",
                opacity: 0,
                outline: true,
                outlineWidth: 0,
                outlineColor: "#ffffff",
                clampToGround: true
                },
                attr: { remark: "示例1" }
            })
            this.pathPointGraphicLayer.addGraphic(graphic) 

            let _this = this;
            setTimeout(function(){
                _this.addContourLine(graphic.toGeoJSON({outline:true}).geometry.coordinates);
            },2000)
        },
        addContourLine(coordinates) {
            this.contourLine = new mars3d.thing.ContourLine({
                shadingType:"slope",
                spacing: 10,
                width: 1.5,
                color: "rgba(255,0,0,0.8)",
                minHeight: -414.0,
                maxHeight: 8777.0,
                shadingAlpha: 0.3, /// 地表渲染的透明度
                colorScheme: {
                // 地表渲染的配色方案
                elevation: {
                    step: [0.0, 0.045, 0.1, 0.15, 0.37, 0.54, 1.0],
                    color: ["#000000", "#2747E0", "#D33B7D", "#D33038", "#FF9742", "#FF9742", "#ffd700"]
                },
                slope: {
                    step: [0.0,0.15, 0.29, 0.5, Math.sqrt(2) / 2, 0.87, 0.91, 1.0],
                    color: ["#00ff00", "#00ff00", "#ffa500","#ff0000", "#ff0000", "#ff0000", "#ff0000", "#ff0000"]
                },
                aspect: {
                    step: [0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0],
                    color: ["#000000", "#2747E0", "#D33B7D", "#D33038", "#FF9742", "#FF9742", "#ffd700"]
                }
                }
            })
            window.globalmap.addThing(this.contourLine)
            // 演示的示例区域
            this.contourLineAreaObj = this.contourLine.addArea(coordinates[0])
        },
        tripFly(tripArr) {
            var fixedRoute = new mars3d.graphic.FixedRoute({
                name: "步行路线",
                frameRate: 1,
                speed: 500,
                autoStop: false, // 到达终点自动停止
                clockLoop: true, // 循环播放
                positions: tripArr,
                pauseTime: 0,
                camera: {
                type: "gs",
                radius: 2500
                },
                model: {
                url: "//data.mars3d.cn/gltf/mars/car/bus3.gltf",
                scale: 5,
                minimumPixelSize: 50,
                clampToGround: true
                },
                circle: {
                radius: 10,
                materialType: mars3d.MaterialType.CircleWave,
                materialOptions: {
                    color: "#ffff00",
                    opacity: 0.3,
                    speed: 10,
                    count: 3,
                    gradient: 0.1
                },
                clampToGround: true
                }
            })
            this.pathPointGraphicLayer.addGraphic(fixedRoute)
            // 开始漫游
            fixedRoute.start()
        },
        removePath(){  // 清空所有数据
            this.pathPointGraphicLayer.clear();

            if(this.contourLine){
                this.contourLine.removeArea(this.contourLineAreaObj);
            }

            this.startPoint = null;
            this.endPoint = null;
        },

    }
}
</script>

<style scoped>
  .box{
      width:325px;
      height:200px;
      background-image:url(/img/uav-bg.png);
      background-size:100% 100%;
      text-align: left;
  }
  .box-title{
        width:100%;
        height:50px;
        line-height:50px;
        text-indent:20px;
        color: #00FFF0;
    }
    .box-container{
        width:100%;
        height: calc( 100% - 50px);
        color:#fff;
    }
    .inputer{
        width:80%;
        height:40px;
        margin:0px auto;
        line-height:40px;
    }
    .operate-container{
        width: 84%;
        margin:10px auto;
        height:32px;
    }
    .operate-container div{
        float:left;
        width: calc( 33% - 8px);
        margin:0px 4px;
        text-align:center;
        cursor:pointer;
        background: #0E6AE5;
        padding:6px 0px;
        border-radius:5px;
    }

    ::v-deep .el-input__inner{
        background:none;
        border-color:#00fff0;
        color:#fff;
    }
</style>