<template>
    <div id="cartest" class="popup" style="display:none">
            <label for="speed" style="font-weight: bold;">
                运动速度:&nbsp;
                <input id="speed" type="range" min="1" max="8000" step="1" value="1000" ref="speed" />
            </label>
            <button id="start-animation" @click="start" ref="startButton">
                开始
            </button>
            <button id="pause-animation" @click="pause" ref="pauseButton">
                暂停
            </button>
            <!-- <button id="stop-animation" @click="stop" ref="stopButton" style="display:none">
                停止
            </button> -->
             <button id="pause-animation" @click="showNet" ref="pauseButton"
             style="display:none">
                路网
            </button>
     </div>
</template>
<script>
    import {
        Fill,
        Stroke,
        Style,
        Text,
        Icon,
        Circle
    } from 'ol/style'
    import {
        Vector as VectorLayer
    } from 'ol/layer'
    import {
        Vector as VectorSource
    } from 'ol/source'
    import {
        clearSpatial
    } from './poiQuery'
    import {
        addAlarmFlash,
        removeOverLayeById
    } from './alarmFlash'
    import Feature from 'ol/Feature'
    import LineString from 'ol/geom/LineString'
    // import turf_length from '@turf/length'
    import Point from 'ol/geom/Point'
    import axios from 'axios'
    import qs from 'qs'
    import turf_along from '@turf/along'
    import turf_linestring from 'turf-linestring'
    import turf_length from '@turf/length'

    //import rbush from 'ol/structs/RBush'
    import rbush from 'rbush'

    export default {
        name: 'carSZ',
        render() {},
        data() {
            return {
                animating: false,
                geoMarker: {},
                routeLength: 0,
                routeCoords: [],
                route: [],
                allPathArray: [],
                secondFlag: false,
                routeAll: [],
                colorIndex: 0,
                colors: ['red', 'green'],
                stopMakers: [],
                perDistance: 0,
                line_length: 0,
                lineAll_length: 0,
                routeFeature: {},
                routeAllFeature: {},
                movePos: {},
                lineArr: [],
                arr: [],
                rotation: 0,
                styles: {},
                countTwo: 0,
                stopFlag: false,
                start_index: null,
                startActive: false,
                vectorLayer: {},
                geoArray: [],
                initFlag: false,
                arrAll: [],
                currentIndex: 0,
                countIndex: 0,
                lenArray: [],
                lenCountArray: [],
                addLen: 0,
                indexCir: 0,
                startObj: {},
                timer: {},
                flashingArr: [],
                clearAllFlag: false,
                multiFlag: false,
                stylesBasic: {},
                // doubleNode: [],
                colorArr: [],
                nodeCountArr: [],
                frontObject: {},
                addCount: 0,
                reverseFlag: false,
                endArr: []
            }
        },
        props: {
            map: {
                type: Object
            },
            serverUrl: {
                type: String
            },
            tableName: {
                type: String
            }
        },
        watch: {
            position(val) { //父组件点击地图，将父组件的position传递给子组件，子组件监听父组件属性的变化
                this.pos = val
            }
        },
        //mixins: [commonMixin('overlay')],
        methods: {
            showNet(frontObj, carType) {
                this.colorArr.push({
                        "carType": carType,
                        "roadStyle": frontObj.roadStyle
                    }) //颜色区别
                    //节点区别
                this.nodeCountArr.push({
                        "carType": carType,
                        "roadArr": frontObj.routArr
                    }) //颜色区别
                var _this = this;
                _this.addCount = 0;
                _this.multiFlag = false;
                _this.reverseFlag = false;
                let routeContains = [];
                if (frontObj.map.getLayers().array_ != undefined) {
                    for (var i = 0; i < frontObj.map.getLayers().array_.length; i++) {
                        if (frontObj.map.getLayers().array_[i].values_.id != undefined) {
                            if (frontObj.map.getLayers().array_[i].values_.id == carType) { //包含不渲染
                                routeContains.push(frontObj.map.getLayers().array_[i].values_.id);
                            }
                        }
                    }
                }
                if (routeContains.includes(carType)) { //地图中含有已经渲染的路径不需要再渲染     
                } else {
                    _this.startObj = frontObj
                    _this.countTwo = 0;
                    _this.countIndex = 0;
                    _this.secondFlag = false
                    _this.arrAll.length = 0;
                    _this.lenCountArray.length = 0;
                    _this.currentIndex = 0;
                    _this.arr = frontObj.routArr
                    getImg()

                    function getImg() { //递归
                        if (_this.currentIndex >= _this.arr.length) {
                            return;
                        }
                        let x1 = _this.arr[_this.currentIndex].X;
                        let y1 = _this.arr[_this.currentIndex].Y;
                        let x2 = _this.arr[_this.currentIndex + 1].X;
                        let y2 = _this.arr[_this.currentIndex + 1].Y;
                        let postTable = _this.tableName
                        var initData = {
                            "posArray": [{
                                "X": x1,
                                "Y": y1,
                                "tableName": postTable
                            }, {
                                "X": x2,
                                "Y": y2,
                                "tableName": postTable
                            }]
                        }
                        axios.post(_this.serverUrl, qs.stringify(initData), {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                            }
                        }).then(res => {
                            console.log("请求数据成功...........")
                            _this.currentIndex = _this.currentIndex + 2;
                            _this.addCount = 0;
                            let geom = res.data[0].geom
                            let stringArray;
                            _this.geoArray.length = 0;
                            if (geom != null) {
                                if (geom.includes(("MULTI"))) { //为多线和线为空的情况下直接连接起始点和终点
                                    _this.multiFlag = true
                                    let geomMulti = "LINESTRING(" + y1 + " " + x1 + "," + y2 + " " + x2 + ")"
                                    stringArray = geomMulti.substring(geomMulti.indexOf("(") + 1, geomMulti.lastIndexOf(")")).split(",")
                                } else {
                                    stringArray = geom.substring(geom.indexOf("(") + 1, geom.lastIndexOf(")")).split(",")
                                }
                                for (var i = 0; i < stringArray.length; i++) { //每次将生成的最短路径形成路径数组geoArray
                                    _this.orderString(stringArray[i])
                                }
                                //此处重新判断---此处有可能会出现起点和终点倒置的情况(如有反转需要倒置)
                                let startLon = _this.geoArray[0][0]
                                let startLat = _this.geoArray[0][1]
                                let endLon = _this.geoArray[_this.geoArray.length - 1][0]
                                let endLat = _this.geoArray[_this.geoArray.length - 1][1]
                                if (Math.abs(_this.geoArray[0][0] - y1) <= Math.abs(_this.geoArray[_this.geoArray.length - 1][0] - y1)) {
                                    _this.geoArray.length = 0;
                                    for (var i = 0; i < stringArray.length; i++) {
                                        if (_this.multiFlag) {
                                            _this.roadStringArray(stringArray[i], y2, x2, y1, x1, stringArray)
                                            break;
                                        } else {
                                            _this.roadStringArray(stringArray[i], y2, x2, y1, x1, stringArray)
                                        }
                                    }
                                    if (_this.multiFlag) { //已经首位相接
                                        _this.multiFlag = false;
                                    }
                                    _this.reverseFlag = false;
                                } else { //翻转数组--反转的情况确实存在而且多次出现
                                    _this.geoArray.length = 0;
                                    _this.reverseFlag = true;
                                    for (var i = stringArray.length - 1; i >= 0; i--) {
                                        _this.roadStringArray(stringArray[i], y2, x2, y1, x1, stringArray)
                                    }
                                    if (_this.multiFlag) { //已经首位相接
                                        _this.multiFlag = false;
                                    }
                                }
                                _this.countTwo++;
                                //从第二个数据开始去除第一项，并将数组翻转
                                _this.initRoute(frontObj.map, _this.geoArray, _this.arrAll, initData, frontObj, carType);
                                _this.$emit('roadFinish', carType + "_" + _this.countTwo)
                                getImg()
                                let num = Math.round(_this.arr.length / 2);

                            } else { //当为null的时候之间连接起始点和终点坐标
                                let geomMulti = "LINESTRING(" + y1 + " " + x1 + "," + y2 + " " + x2 + ")"
                                stringArray = geomMulti.substring(geomMulti.indexOf("(") + 1, geomMulti.lastIndexOf(")")).split(",")
                                for (var i = 0; i < stringArray.length; i++) { //每次将生成的最短路径形成路径数组geoArray
                                    _this.orderString(stringArray[i])

                                }
                                _this.countTwo++;
                                //从第二个数据开始去除第一项，并将数组翻转
                                _this.initRoute(frontObj.map, _this.geoArray, _this.arrAll, initData, frontObj, carType, geom);
                                _this.$emit('roadFinish', carType + "_" + _this.countTwo)
                                getImg()
                                let num = Math.round(_this.arr.length / 2);
                            }
                        }, err => {
                            _this.currentIndex = _this.currentIndex + 2;
                            getImg()
                        })
                    }
                }
            },
            orderString(stringArray) {
                let arr = stringArray.split(" ");
                let lon = parseFloat(arr[0]);
                let lat = parseFloat(arr[1]);
                this.geoArray.push([lon, lat])
                    //this.arrAll.push([lon, lat]);    
            },
            buildArray(stringArray, y2, x2, y1, x1, array) {
                let arr = stringArray.split(" ");
                let lon = parseFloat(arr[0]);
                let lat = parseFloat(arr[1]);
                if (this.addCount == 0) {
                    this.arrAll.push([y1, x1]);
                    this.geoArray.push([y1, x1])
                    this.arrAll.push([lon, lat]);
                    this.geoArray.push([lon, lat])
                } else if (this.addCount == array.length - 1) {
                    this.arrAll.push([lon, lat]);
                    this.geoArray.push([lon, lat])
                    this.arrAll.push([y2, x2]);
                    this.geoArray.push([y2, x2])
                } else {
                    this.arrAll.push([lon, lat]);
                    this.geoArray.push([lon, lat])
                }
            },
            roadStringArray(stringArray, y2, x2, y1, x1, array) {
                if (this.multiFlag) { //多线——为直接连接起点和终点
                    this.arrAll.push([y1, x1]); //末尾
                    this.arrAll.push([y2, x2]); //首位
                    this.geoArray.push([y1, x1])
                    this.geoArray.push([y2, x2])
                } else { //-----单线情况
                    if (this.reverseFlag) { //为翻转情况
                        this.buildArray(stringArray, y2, x2, y1, x1, array)

                    } else { //正常情况
                        this.buildArray(stringArray, y2, x2, y1, x1, array)
                    }
                    this.addCount++;
                }
            },
            sum(arr) {
                var s = 0;
                for (var i = arr.length - 1; i >= 0; i--) {
                    s += arr[i];
                }
                return s;
            },
            timeStyle(time) {
                return new Style({
                    text: new Text({
                        // 对其方式
                        textAlign: 'center',
                        // 基准线
                        textBaseline: 'middle',
                        offsetY: -22,
                        offsetX: 72,
                        // 文字样式
                        font: 'normal 16px 黑体',
                        // 文本内容
                        text: time,
                        // 文本填充样式
                        fill: new Fill({
                            color: 'rgba(255,255,255,1)'
                        }),
                        padding: [5, 5, 5, 5],
                        backgroundFill: new Fill({
                            color: 'rgba(0,0,255,0.6)'
                        })
                    })
                })
            },
            styleFunction(feature) {
                let _style = null
                for (var i = 0; i < this.nodeCountArr.length; i++) {
                    if (feature.values_.id == this.nodeCountArr[i].carType) {
                        if (feature.get('type') === 'nodeCount') {
                            if (feature.values_.order == 1 || feature.values_.order == Math.round(this.nodeCountArr[i].roadArr.length / 2) + 1) {} else {
                                _style = this.stylesBasic[feature.get('type')]
                                if (feature.get("order")) {
                                    _style.getText().setText(feature.get("order") + '')
                                }
                            }
                        }
                        return _style
                    }
                }
            },
            addFeature(name, attr, geo, type, vectors) {
                //此处加个if判断
                let nodeMarkerCommon = new Feature({
                    type: type,
                    name: name,
                    geometry: geo,
                    attributes: attr
                })
                vectors.push(nodeMarkerCommon)
            },
            featureSymbol(id, order, type, name, geometry, attributes) {
                return new Feature({
                    id: id,
                    order: order,
                    type: type,
                    name: name,
                    geometry: geometry,
                    attributes: attributes
                })
            },
            vectorLayerSymbol(id, name, source, style) {
                return new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                    id: id,
                    name: name,
                    source: source,
                    style: style
                })
            },
            addMediumNode(carType, order, attr, arr, frontObj) {
                let data_medium = new VectorSource();
                data_medium.addFeature(this.featureSymbol(carType, order, 'nodeCount', 'nodeCount', new Point(arr), frontObj.routArr[this.countIndex].attributes));
                let node_layer = this.vectorLayerSymbol(carType, 'nodeCount', data_medium, this.styleFunction)
                node_layer.setZIndex(frontObj.nodeIndex)
                frontObj.map.addLayer(node_layer)
            },
              findRoad(map,tablename,name,name1,serverUrl,roadstyle){
                this.findlineAll.length = 0;
                this.lineArr.length = 0;
                this.lineArr2.length = 0;
                this.firstName = name;
                this.endName = name1;
                var _this = this;
                var postData = {
                    "data": [{
                        'name':name,
                        'name1':name1,
                        "tableName": tablename
                    }]
                }
                axios.post(serverUrl, qs.stringify(postData), {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                            }
                }).then(res => {
                    let firstname = _this.firstName
                    let endname = _this.endName
                    let linePointArr = res.data;
                    for(var i = 0;i<linePointArr.length;i++){
                        let x1 = linePointArr[i].y1
                        let y1 = linePointArr[i].x1
                        let x2 = linePointArr[i].y2
                        let y2 = linePointArr[i].x2
                        let route = new LineString([[y1,x1],[y2,x2]]);
                        // if(linePointArr[i].name==firstname){
                        //     _this.lineArr.push( turf_linestring([[y1,x1],[y2,x2]]))
                          
                        // }else{
                        //     _this.lineArr2.push( turf_linestring([[y1,x1],[y2,x2]]))
                        // }
                        if(linePointArr[i].name.indexOf(firstname)>-1){
                            _this.lineArr.push( turf_linestring([[y1,x1],[y2,x2]]))
                          
                        }else{
                            _this.lineArr2.push( turf_linestring([[y1,x1],[y2,x2]]))
                        }
                        let feature =  this.featureSymbol('findroad','',"route",'',route,'')
                        let find_line = new VectorSource()
                        find_line.addFeature(feature);
                        let line_layer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                            id: 'findroad',
                            source: find_line,
                            style: new Style({//线串的样式
                                stroke: new Stroke({
                                    color:roadstyle.lineColor,
                                    width:roadstyle.lineWidth
                                })
                            })
                        })
                        //map.getView().fit(find_line.getExtent(),15)
                        map.addLayer(line_layer)
                    }
                    for(var i= 0;i<_this.lineArr.length;i++){
                        for(var j = 0;j<_this.lineArr2.length;j++){
                            let intersects = line_intersect(_this.lineArr[i], _this.lineArr2[j]);//判断相交
                            if(intersects.features.length!=0){
                                _this.findlineAll.push(intersects);
                            }
                        }
                    }
                    let config =  {
                        "id":'intersectPoi',
                        "scale":0.9,
                        "zIndex":10,
                        "img":'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAAfCAYAAAAFkva3AAACd0lEQVR42qWU3UuTYRjG34iiw+gk6CAp2XRqsyazWRuz8c656UF/QV8URhQSNaMP5kzRudQ5Zy3zD+i0gygiZ44oogjDJJBqjMTS1Gxzm1s17+4rYmBzbXt38OPhue/r+jEG7yMQURoWZ2QHY2XGmBkm8ff0Y479er01F3N3eBPTzsQs7gQ1eJPUOETUOMzwiTvm2COH/LqyekdoK+Mz98ep4Q4XhzODPXKcH2W2rZGZupY2MiP17hWycDBXkOfec2ZzSlbXuWg39UXJPER5gx76BJmxY347EzPx/1HHy3xBD314BLF97qLYs0zG26uSQZ89VsHQ9mVUHFgh0ZuUDPrwCIfsM3OGmz/I4P0lGfTZMyvU2qaTtbd+UqHAI+ivBZf1gwnSs10q6LMnLOiuBsZ1rgjpeCCZ/gix542gvfLerXXM00FPXDJaxwKxxyMcuDSlqbEFSeNZkQz68Pz5Ampa3o3t75yl6oFY3qCHfupz0lgnS5i42hUmtTuaM8ijh35KBqovTLSp7Z+oqj+aM8ijl/YEqc+Pb2ECqq6vtM8VyQpyyKOXJgNVza8Pqy5PkbJvOSvIIZ/xpQWqcy9HKvnnV/SGM4I953zI/1e29+wLJZMs7w1RJrBHLqsMVJ55drfCFiBFz/c0MMceuZxkytNPy5hV+Y0l+hfMsc9ZBvY0+e+VtgZJ5vyWAnfMsc9LVn7qiahofkXFzsUUuGOet6zspG8D87G44zPt7l4gnLhjnrcMKE48tsmsb6mIXwWcfG/FXJKs9PijUnmTn3byE4UTd8kyUHLs4Yei69OEE/eCZPKjDwZ3tUwSzoJlsiP3RSbEGLNlfwPf80fNP6DL+QAAAABJRU5ErkJggg==',
                        }
                    if(_this.findlineAll!=undefined){
                         addVector(_this.findlineAll[0].features,map,config)
                    }
                }, err => {
                })
            },
            // findRoad(map, tablename, name, serverUrl, roadstyle) {
            //     var postData = {
            //         "data": [{
            //             'name': name,
            //             "tableName": tablename
            //         }]
            //     }
            //     axios.post(serverUrl, qs.stringify(postData), {
            //         headers: {
            //             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            //         }
            //     }).then(res => {
            //         let linePointArr = res.data;
            //         for (var i = 0; i < linePointArr.length; i++) {
            //             let x1 = linePointArr[i].y1
            //             let y1 = linePointArr[i].x1
            //             let x2 = linePointArr[i].y2
            //             let y2 = linePointArr[i].x2
            //             let route = new LineString([
            //                 [y1, x1],
            //                 [y2, x2]
            //             ]);
            //             let feature = this.featureSymbol('findroad', '', "route", '', route, '')
            //             let find_line = new VectorSource()
            //             find_line.addFeature(feature);
            //             //map.getView().fit(find_line.getExtent())
            //             let line_layer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
            //                 id: 'findroad',
            //                 source: find_line,
            //                 style: new Style({ // 线串的样式
            //                     stroke: new Stroke({
            //                         color: roadstyle.lineColor,
            //                         width: roadstyle.lineWidth
            //                     })
            //                 })
            //             })
            //             map.addLayer(line_layer)
            //         }
            //     }, err => {})
            // },
            addNode(vectors, arr, startName, endName, frontObj, num, carType) {
                for (var i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        this.addMediumNode(carType, this.arr[this.countIndex].attributes.index + 1, frontObj.routArr[this.countIndex].attributes, arr[i], frontObj)

                        let timeMarker = new Feature({
                            geometry: new Point(arr[i])
                        })
                        timeMarker.setStyle(this.timeStyle(frontObj.routArr[this.countIndex].attributes.throughTime))
                        let data_timer = new VectorSource()
                        data_timer.addFeature(timeMarker);
                        let time_layer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                                id: "time",
                                source: data_timer
                            })
                            //time_layer.setZIndex(frontObj.nodeIndex)
                        frontObj.map.addLayer(time_layer)



                        if (startName === "node") {
                            this.addFeature('startNode' + (this.countIndex).toString(), frontObj.routArr[this.countIndex].attributes, new Point(arr[i]), 'node', vectors)
                        } else {
                            if (num === 1) {
                                this.addFeature(startName + (this.countIndex).toString(), frontObj.routArr[this.countIndex].attributes, new Point(arr[i]), startName, vectors)
                            } else {
                                this.addFeature(startName + (this.countIndex).toString(), frontObj.routArr[this.countIndex].attributes, new Point(arr[i]), startName, vectors)
                            }
                        }
                    } else if (i == arr.length - 1) {
                        this.addMediumNode(carType, this.arr[this.countIndex + 1].attributes.index + 1, frontObj.routArr[this.countIndex + 1].attributes, arr[i], frontObj)
                        let timeMarkerNext = new Feature({
                            geometry: new Point(arr[i])
                        })
                        timeMarkerNext.setStyle(this.timeStyle(frontObj.routArr[this.countIndex + 1].attributes.throughTime))
                        let data_timer = new VectorSource()
                        data_timer.addFeature(timeMarkerNext);
                        let time_layer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                            id: "time",
                            source: data_timer
                        })
                        frontObj.map.addLayer(time_layer)

                        if (endName === "node") {
                            if (this.countIndex === 1) {
                                this.addFeature('endNode' + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), 'node', vectors)
                            } else {
                                this.addFeature('endNode' + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), 'node', vectors)
                            }
                        } else {
                            if (num === 1) {
                                this.addFeature(endName + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), endName, vectors)
                            } else {
                                this.addFeature(endName + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), endName, vectors)
                            }
                        }
                    }
                }
            },
            initRoute(map, arr, arrAll, initData, frontObj, carType) {
                let vectors = [];
                vectors.length = 0;
                if (arr.length != 1) {
                    this.route = new LineString(arr);
                    this.routeAll = new LineString(arrAll);
                    //获取直线的坐标
                    this.routeFeature = this.featureSymbol(carType, '', "route", '', this.route, '')
                    let data_line = new VectorSource()
                    data_line.addFeature(this.routeFeature);
                    // map.getView().fit(data_line.getExtent())
                    let line_layer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                        id: carType,
                        source: data_line,
                        style: this.styleLineFunction
                    })
                    map.addLayer(line_layer)
                    let popArray = this.routeFeature.getGeometry().getCoordinates();
                    let lengthArray = [];
                    for (var i = 0; i < popArray.length; i++) {
                        if (!popArray[i].includes(NaN)) {
                            lengthArray.push(popArray[i])
                        }
                    }
                    let turfString = turf_linestring(lengthArray)
                    let lineLength = turf_length(turfString, {
                        units: 'kilometers'
                    })
                    this.lenCountArray.push(lineLength);
                    let allLen = this.sum(this.lenCountArray)
                    this.lenArray.push({
                        "length": allLen,
                        "position": {
                            "X": initData.posArray[1].X,
                            "Y": initData.posArray[1].Y
                        },
                        "carType": carType
                    });
                    let obj = {
                        length: lineLength,
                        array: this.routeFeature.getGeometry().getCoordinates()
                    }
                    this.allPathArray.push(obj)
                    this.routeAllFeature = this.featureSymbol(carType, '', 'route', '', this.routeAll, '')
                    let num = Math.round(this.arr.length / 2);
                    if (num === 1) {
                        this.addNode(vectors, arr, 'startNode', 'endNode', frontObj, num, carType)
                    } else {
                        if (this.countIndex === 0) {
                            this.addNode(vectors, arr, 'startNode', 'node', frontObj, num, carType)
                        } else if (this.countIndex === this.arr.length - 2) {
                            this.addNode(vectors, arr, 'node', 'endNode', frontObj, num, carType)
                        } else {
                            this.addNode(vectors, arr, 'node', 'node', frontObj, num, carType)
                        }
                    }
                    this.countIndex = this.countIndex + 2
                    this.secondFlag = true
                        //获取直线的坐标
                    this.routeCoords = this.route.getCoordinates();
                    this.routeLength = this.routeCoords.length;
                    this.stylesBasic = {
                        'startNode': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: frontObj.startIcon
                            }),
                            text: new Text({
                                font: "bold 12px 黑体",
                                text: "起点",
                                fill: new Fill({
                                    color: "#aa3300"
                                }),
                                stroke: new Stroke({
                                    color: "#fff",
                                    width: 2
                                }),
                                textAlign: "left"
                            })
                        }),
                        'endNode': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: frontObj.endIcon
                            }),
                            text: new Text({
                                font: "bold 12px 黑体",
                                text: "终点",
                                fill: new Fill({
                                    color: "#aa3300"
                                }),
                                stroke: new Stroke({
                                    color: "#fff",
                                    width: 2
                                }),
                                textAlign: "left"
                            })
                        }),
                        'nodeCount': new Style({
                            image: new Circle({
                                radius: frontObj.nodeCircle,
                                stroke: new Stroke({
                                    color: "#FF5809",
                                    width: 2
                                }),
                                fill: new Fill({
                                    color: "#FF5809"
                                })
                            }),
                            text: new Text({
                                font: frontObj.nodeText,
                                text: "",
                                fill: new Fill({
                                    color: 'rgba(255,255,255,1)'
                                })
                            })
                        })
                    }
                    this.styles = {
                        'geoMarker': new Style({
                            image: new Icon({
                                src: frontObj.carIcon,
                                rotateWithView: false,
                                rotation: -Math.atan2(this.routeCoords[0][1] - this.routeCoords[1][1], this.routeCoords[0][0] - this.routeCoords[1][0]),
                                scale: this.startObj.carScale
                            })
                        })
                    };
                    var _this = this;
                    _this.vectorLayer = new VectorLayer({
                        id: carType,
                        style: function(feature) {
                            let _style = null
                            if (feature.get('type') === 'startNode') {
                                _style = _this.stylesBasic[feature.get('type')]
                            }
                            if (feature.get('type') === 'endNode') {
                                _style = _this.stylesBasic[feature.get('type')]
                            }
                            return _style
                        },
                        source: new VectorSource({
                            features: vectors
                        })
                    });
                    map.addLayer(_this.vectorLayer);
                } else {
                    if (this.countIndex == this.arr.length - 2) {
                        // this.doubleNode.push(arr)
                        let endMarker = this.featureSymbol('', '', "endNode", "endNode", new Point([this.arrAll[this.arrAll.length - 1][0], this.arrAll[this.arrAll.length - 1][1]]), frontObj.routArr[this.countIndex + 1].attributes)
                        let endNodeMarker = new VectorSource()
                        endNodeMarker.addFeature(endMarker);
                        let endLayer = new VectorLayer({
                            id: carType,
                            style: this.stylesBasic.endNode,
                            source: endNodeMarker
                        });
                        map.addLayer(endLayer);
                    } else {
                        // this.doubleNode.push(arr)
                    }
                    this.countIndex = this.countIndex + 2
                }
            },
            start(carType, carzIndex, frontObj) { //此处需要给出点击的是第几个小车，this.arr为前端传递过来的坐标值(需要找到对应的)
                if (this.arr.length == 0) {
                    alert("请先生成车辆路径");
                } else {
                    this.flashingArr.length = 0;
                    this.initObject_P()
                    this.frontObject = frontObj;
                    this.stopFlag = false;
                    this.indexCir = 0;
                    if (!this.animating) {
                        this.animating = true
                        let index = this.start_index || 1
                        this.startAnimation(index, carType, carzIndex);
                    }
                }
            },
            styleLineFunction(feature, res) {
                var trackLine = feature.getGeometry(); //轨迹线图形
                for (var i = 0; i < this.colorArr.length; i++) {
                    if (feature.values_.id == this.colorArr[i].carType) {
                        var styles = [
                            new Style({ // 线串的样式
                                stroke: new Stroke({
                                    color: this.colorArr[i].roadStyle.lineColor,
                                    width: this.colorArr[i].roadStyle.lineWidth
                                })
                            })
                        ];
                    }
                }
                //对segments建立btree索引
                let tree = new rbush(); //路段数
                trackLine.forEachSegment(function(start, end) {
                    var dx = end[0] - start[0];
                    var dy = end[1] - start[1];
                    //计算每个segment的方向，即箭头旋转方向
                    let rotation = Math.atan2(dy, dx);
                    let geom = new LineString([start, end]);
                    let extent = geom.getExtent();
                    var item = {
                        minX: extent[0],
                        minY: extent[1],
                        maxX: extent[2],
                        maxY: extent[3],
                        geom: geom,
                        rotation: rotation
                    };
                    tree.insert(item);
                });
                //轨迹地理长度
                let length = trackLine.getLength();
                let stpes = 40; //像素步长间隔
                //将像素步长转实际地理距离步长
                let geo_steps = stpes * res;
                //箭头总数
                let arrowsNum = parseInt(length / geo_steps);
                for (let i = 1; i < arrowsNum; i++) {
                    let arraw_coor = trackLine.getCoordinateAt(i * 1.0 / arrowsNum);
                    let tol = 0.0001; //查询设置的点的容差，测试地图单位是米。如果是4326坐标系单位为度的话，改成0.0001.
                    let arraw_coor_buffer = [arraw_coor[0] - tol, arraw_coor[1] - tol, arraw_coor[0] + tol, arraw_coor[1] + tol];
                    //进行btree查询
                    var treeSearch = tree.search({
                        minX: arraw_coor_buffer[0],
                        minY: arraw_coor_buffer[1],
                        maxX: arraw_coor_buffer[2],
                        maxY: arraw_coor_buffer[3]
                    });
                    let arrow_rotation;
                    //只查询一个，那么肯定是它了，直接返回
                    if (treeSearch.length == 1)
                        arrow_rotation = treeSearch[0].rotation;
                    else if (treeSearch.length > 1) {
                        let results = treeSearch.filter(function(item) {
                            //箭头点与segment相交，返回结果。该方法实测不是很准，可能是计算中间结果
                            //保存到小数精度导致查询有点问题
                            // if(item.geom.intersectsCoordinate(arraw_coor))
                            //   return true;
                            //换一种方案，设置一个稍小的容差，消除精度问题
                            let _tol = 1; //消除精度误差的容差
                            if (item.geom.intersectsExtent([arraw_coor[0] - _tol, arraw_coor[1] - _tol, arraw_coor[0] + _tol, arraw_coor[1] + _tol]))
                                return true;
                        })
                        if (results.length > 0)
                            arrow_rotation = results[0].rotation;
                    }
                    styles.push(new Style({
                        geometry: new Point(arraw_coor),
                        image: new Icon({
                            src: this.startObj.arrowIcon,
                            anchor: [0.75, 0.5],
                            scale: this.startObj.arrowScale,
                            rotateWithView: true,
                            rotation: -arrow_rotation
                        })
                    }));
                }
                return styles;
            },
            duplicate(arr) {
                let res = {}
                arr.forEach(item => {
                    item.sort((b, a) => b - a);
                    res[item] = item;
                });
                return Object.values(res)
            },
            delete(delIndex) {
                var temArray = [];
                for (var i = 0; i < this.length; i++) {
                    if (i != delIndex) {
                        temArray.push(this[i]);
                    }
                }
                return temArray;
            },
            flashingPoint(carType) {
                for (var i = 0; i < this.lenArray.length; i++) {
                    if (this.lenArray[i].carType == carType) {
                        this.flashingArr.push(this.lenArray[i])
                    }
                }
                if (this.indexCir >= this.flashingArr) {
                    return
                } else {
                    for (this.indexCir < this.flashingArr.length;;) {
                        removeOverLayeById(this.startObj.map, 'Alarm')
                        if (this.flashingArr[this.indexCir] == undefined) {
                            if (this.timer) {
                                clearTimeout(this.timer);
                            }
                            return
                        }
                        if (this.perDistance <= this.flashingArr[this.indexCir].length) {
                            let pos = this.flashingArr[this.indexCir].position;
                            removeOverLayeById(this.startObj.map, 'Alarm')
                            this.$emit('roadFinish', this.indexCir + 2)
                                //此次的pos亮
                            addAlarmFlash(this.startObj.map, {
                                geom: {
                                    points: "" + pos.Y + ", " + pos.X + "",
                                    type: 'Point'
                                },
                                attributes: {
                                    id: 'Alarm'
                                },
                                symbol: {
                                    image: {
                                        src: this.startObj.gifUrl,
                                        size: [0, 0]
                                    }
                                }
                            })
                            break;
                        } else {
                            this.indexCir++;
                            if (this.indexCir > this.flashingArr.length - 1) {
                                break;
                            }
                            //其余的pos不亮
                            removeOverLayeById(this.startObj.map, 'Alarm')
                        }
                    }
                }
            },
            startAnimation(index, carType, carzIndex) {
                var _this = this;
                let speed = _this.startObj.speed;
                if (!_this.animating) { //点击开始
                    _this.start_index = index;
                    return
                }
                //设置显示范围
                _this.timer = setTimeout(() => { //index为运行到的第几个位置
                    if (!_this.stopFlag) {
                        _this.perDistance = speed * index / 1000; //第一次0.1km,第二次0.2km......
                    }
                    _this.routeAll = new LineString(_this.arrAll);
                    let routeAllFea = new Feature({ //line_data
                        id: carType,
                        type: 'route',
                        geometry: _this.routeAll
                    });
                    let lineAll_str = turf_linestring(routeAllFea.getGeometry().getCoordinates())
                    let lineAll_length = turf_length(lineAll_str, {
                        units: 'kilometers'
                    })
                    _this.flashingPoint(carType)
                    if (_this.perDistance >= lineAll_length) { // 运动完毕32.22026489307822km
                        _this.start_index = null;
                        _this.animating = false;
                        var endPoint = new Point(_this.arrAll[this.arrAll.length - 1]);
                        var feature = new Feature(endPoint);
                        let data_end = new VectorSource()
                        data_end.addFeature(feature);
                        clearSpatial("car", _this.startObj.map)
                        let line_layer = _this.vectorLayerSymbol('car', '', data_end, _this.styles.geoMarker)
                        line_layer.setZIndex(carzIndex)
                        _this.startObj.map.addLayer(line_layer)
                        return;
                    } else {
                        let old_p = _this.movePos.getGeometry().getCoordinates();
                        let new_p = turf_along(lineAll_str, _this.perDistance, {
                            units: 'kilometers'
                        }).geometry.coordinates
                        _this.movePos.setGeometry(new Point(new_p)) //movePos初始位置
                        let dx = old_p[0] - new_p[0];
                        let dy = old_p[1] - new_p[1];
                        _this.rotation = Math.atan2(dy, dx); //从一个点移动到下一个点的旋转角度
                        _this.styles.geoMarker.getImage().setRotation(-_this.rotation); //carStyle对象已经初始化过了
                        var currentPoint = new Point(new_p);
                        var feature = new Feature(currentPoint);
                        let data_c = new VectorSource()
                        data_c.addFeature(feature);
                        clearSpatial("car", _this.startObj.map)
                        let line_layer = _this.vectorLayerSymbol('car', '', data_c, _this.styles.geoMarker)
                        line_layer.setZIndex(carzIndex)
                        _this.startObj.map.addLayer(line_layer)
                        index++
                        _this.startAnimation(index);
                    }
                }, 500)
                _this.$emit('timer', _this.timer)
            },
            pause() {
                this.animating = false
                if (this.timer) {
                    clearTimeout(this.timer);
                }
            },
            initObject_L() { //初始化线
                let vectors = [];
                this.route = new LineString(this.arr);
            },
            initObject_P() { //初始化点
                this.movePos = new Feature({ //第一个坐标值
                    geometry: new Point(this.arr[0])
                })
                let p_style = new Style({
                    // 设置一个标识
                    image: new Icon({
                        src: this.startObj.carIcon,
                        // 这个是相当于是进行切图了
                        // size: [50,50],
                        // 注意这个，竟然是比例 左上[0,0]  左下[0,1]  右下[1，1]
                        anchor: [0.5, 0.5],
                        // 这个直接就可以控制大小了
                        scale: 0.5,
                        // 开启转向
                        rotateWithView: true,
                        // rotation: 0,
                    }),
                    text: new Text({
                        // 对其方式
                        textAlign: 'center',
                        // 基准线
                        textBaseline: 'middle',
                        offsetY: -30,
                        // 文字样式
                        font: 'normal 16px 黑体',
                        // 文本内容
                        text: '车牌：陕A-0p1v6',
                        // 文本填充样式
                        fill: new Fill({
                            color: 'rgba(255,255,255,1)'
                        }),
                        padding: [5, 5, 5, 5],
                        backgroundFill: new Fill({
                            color: 'rgba(0,0,255,0.6)'
                        })
                    })
                })
                this.movePos.setStyle(p_style)
            },
            setTrackCoods(routeObj, carType) {
                this.flashingArr.length = 0;
                this.pause();
                let routeType = [];
                if (this.timer) {
                    clearTimeout(this.timer);
                }
                this.start_index = null //从头开始跑
                this.arr = routeObj.routArr //前端传递过来的节点数组
                this.initObject_P(routeObj) //初始化点的坐标
                let layersArray = routeObj.map.getLayers().array_;
                let lineAll = [];
                for (var i = 0; i < this.lenArray.length; i++) {
                    if (this.lenArray[i].carType == carType) {
                        this.flashingArr.push(this.lenArray[i])
                    }
                }
                //this.routeFeature.values_.geometry.flatCoordinates
                //清除一次图层再添加一次
                if (layersArray) {
                    for (var i = 0; i < layersArray.length; i++) { //先把source数据源清除一次
                        let type = routeObj.map.getLayers().array_[i].values_;
                        if (type.id == carType) {
                            for (var j = 0; j < type.source.getFeatures().length; j++) {
                                if (type.source.getFeatures()[j].values_.type != undefined && type.source.getFeatures()[j].values_.type == "route") {
                                    let arr = routeObj.map.getLayers().array_[i].values_.source.getFeatures()[j].getGeometry().getCoordinates()
                                    lineAll.push(arr);
                                }
                            }
                        }
                    }
                }
                let finalArr = []
                for (var i = 0; i < lineAll.length; i++) {
                    for (var j = 0; j < lineAll[i].length; j++) {
                        finalArr.push(lineAll[i][j])
                    }
                }
                this.arrAll.length = 0;
                this.arrAll = finalArr;
                if (this.routeAllFeature.setGeometry != undefined) {
                    this.routeAllFeature.setGeometry(new LineString(finalArr))
                }
            }
        }
    }
</script>
<style scoped>
    .popup {
        position: absolute;
        background-color: #e0e0e057;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        border: 1px solid #ACD6FF;
        top: 12px;
        left: 80px;
        min-width: 360px;
        height: 45px;
        padding-left: 7px;
        padding-top: 5px;
    }
</style>