<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: 'carTestZL',
        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: {},
                colorArr: [],
                nodeCountArr: [],
                frontObject: {},
                addCount:0,
                reverseFlag:false,
                endArr:[],
                drawRouteCompleted:false,
                nodeType:'',
                startNode:{},
                endNode:{},
                nodeCount:{},
                _styleNode:{},
                finished:false
            }
        },
        props: {
            map: {
                type: Object
            },
            stopRendingFlag:{
                type:Boolean
            }
        },
        watch: {
            position(val) { //父组件点击地图，将父组件的position传递给子组件，子组件监听父组件属性的变化
                this.pos = val
            }
        },
        //mixins: [commonMixin('overlay')],
        methods: {
            showNet(frontObj, carType,typeObject,type) {
                this.nodeType = typeObject.nodeCount
                this.$emit('drawLineCompleteZL3',false)
                if(!this.drawRouteCompleted){//开始画线
                    //此处先把中间点渲染出来,后面等真实的点线出来后再把此处渲染的中间点清除
                    this.showMediumNode(frontObj.routArr,carType,frontObj,typeObject);
                    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) {
                                if(type=="constantLine"){//匀速行动返回长度和时间
                                    var line = turf_linestring(_this.arrAll);
                                    let lineLength = turf_length(line, {
                                            units: 'kilometers'
                                    })
                                    _this.$emit('drawLineCompleteZL3',{'roadArr':_this.arrAll,'length':lineLength,'type':typeObject.carType})
                                    // resolve({'roadArr':_this.arrAll,'length':lineLength});
                                }
                                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
                                }]
                            }
                            _this.currentIndex = _this.currentIndex + 2;
                            _this.addCount = 0;
                            let geom = null
                            let stringArray;
                            _this.geoArray.length = 0;
                            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, typeObject);
                            _this.$emit('roadFinish3', carType + "_" + _this.countTwo)
                            let num = Math.round(_this.arr.length / 2);
                            if (_this.countTwo === num) {//画线完成
                                //显示出来
                                _this.drawRouteCompleted = false
                            } else {
                                    _this.drawRouteCompleted = true
                            }
                            if(!_this.stopRendingFlag){
                                getImg()
                            }else{
                                _this.drawRouteCompleted = false
                            }
                        }
                    }
                }
            },
            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,typeObject){
                let arr = stringArray.split(" ");
                let lon = parseFloat(arr[0]);
                let lat = parseFloat(arr[1]);
                 if(this.addCount==0){
                    this.geoAndarr([y1,x1],[lon,lat])
                }else if(this.addCount==array.length-1){
                     this.geoAndarr([lon,lat],[y2,x2])
                }else if(!typeObject.isDirectConnect){//非直连的话走路网
                    this.arrAll.push([lon,lat]);
                    this.geoArray.push([lon,lat])
                }
            },
            geoAndarr(pos,pos1){
                this.arrAll.push(pos);
                this.geoArray.push(pos);
                this.arrAll.push(pos1);
                this.geoArray.push(pos1);
            },
            roadStringArray(stringArray,y2,x2,y1,x1,array,typeObject){
                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,typeObject)

                    }else{//正常情况
                       this.buildArray(stringArray,y2,x2,y1,x1,array,typeObject)
                    }
                    this.addCount++;
                }
            },
            sum(arr) {
                var s = 0;
                for (var i = arr.length - 1; i >= 0; i--) {
                    s += arr[i];
                }
                return s;
            },
            styleFunction(feature) {
                //let _style = null
                for (var i = 0; i < this.nodeCountArr.length; i++) {
                    // if (feature.values_.id == this.nodeCountArr[i].carType) {
                    if (feature.values_.id ==  this.nodeType) {
                        if (feature.get('type') === this.nodeType) {
                            if (feature.values_.order == 1 || feature.values_.order == Math.round(this.nodeCountArr[i].roadArr.length / 2)+1) {} else {
                                this._styleNode = this.nodeCount
                                if (feature.get("order")) {
                                    this._styleNode.getText().setText(feature.get("order") + '')
                                }
                            }
                        }
                        return this._styleNode
                    }
                }
            },
            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
                        })
            },
            vectorLayerSymbolNode(id,name,source,frontObj,order){
                return new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                            id: id,
                            name: name,
                            source: source,
                            style:  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: order+"",
                                        fill: new Fill({
                                            color: 'rgba(255,255,255,1)'
                                        })
                                    })
                        })
                        })
            },
            addMediumNode(carType,order,attr,arr,frontObj,typeObject){
                let data_medium = new VectorSource();
                data_medium.addFeature(this.featureSymbol(carType,order,typeObject.nodeCount,typeObject.nodeCount,new Point(arr),attr));
                let node_layer;
               if(typeObject.isNumber){//在此处直接添加序号，不用回调
                    //node_layer = this.vectorLayerSymbolNode(carType,typeObject.nodeCount,data_medium,this.styleFunction)
                    node_layer = this.vectorLayerSymbolNode(carType,typeObject.nodeCount,data_medium,frontObj,order)
                }else{
                     let iconStyle = new Style({
                        image: new Icon({
                            src: frontObj.nodeIcon,    // 设置Image对象
                            scale: frontObj.nodeScale    // 及图标大小
                        })
                    })
                    node_layer = this.vectorLayerSymbol(carType,typeObject.nodeCount,data_medium,iconStyle)
                }
                node_layer.setZIndex(frontObj.nodeIndex)
                frontObj.map.addLayer(node_layer)
            },
            addNode(vectors, arr, startName, endName, frontObj, num, carType,typeObject) {
                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,[parseFloat(frontObj.routArr[this.countIndex].attributes.info.longitude),parseFloat(frontObj.routArr[this.countIndex].attributes.info.latitude)],frontObj)
                        if (startName === "node") {
                            this.addFeature(typeObject.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,[parseFloat(frontObj.routArr[this.countIndex+1].attributes.info.longitude),parseFloat(frontObj.routArr[this.countIndex+1].attributes.info.latitude)],frontObj)
                        if (endName === "node") {
                            if (this.countIndex === 1) {
                                this.addFeature(typeObject.endNode + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), 'node', vectors)
                            } else {
                                this.addFeature(typeObject.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)
                            }
                        }
                    }
                }
            },
             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
                                })
                            })
                        ];
                    }
                }
                var _this = this;
                //对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 = 10; //像素步长间隔
                //将像素步长转实际地理距离步长
                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({//arrow图标
                        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;
            },
            initRoute(map, arr, arrAll, initData, frontObj, carType,typeObject) {
                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);
                    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, typeObject.startNode, typeObject.endNode, frontObj, num, carType,typeObject)
                    } else {
                        if (this.countIndex === 0) {
                            this.addNode(vectors, arr, typeObject.startNode, 'node', frontObj, num, carType,typeObject)
                        } else if (this.countIndex === this.arr.length - 2) {
                            this.addNode(vectors, arr, 'node', typeObject.endNode, frontObj, num, carType,typeObject)
                        } else {
                            this.addNode(vectors, arr, 'node', 'node', frontObj, num, carType,typeObject)
                        }
                    }
                    this.countIndex = this.countIndex + 2
                    this.secondFlag = true
                        //获取直线的坐标
                    this.routeCoords = this.route.getCoordinates();
                    this.routeLength = this.routeCoords.length;
                    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') === typeObject.startNode) {
                                _style = _this.startNode
                            }
                            if (feature.get('type') === typeObject.endNode) {
                                _style =  _this.endNode
                            }
                            return _style
                        },
                        source: new VectorSource({
                            features: vectors
                        })
                    });
                    map.addLayer(_this.vectorLayer);
                } else {
                    if(this.countIndex==this.arr.length-2){
                        let endMarker = this.featureSymbol('','',typeObject.endNode,typeObject.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.endNode,
                           source: endNodeMarker
                    });
                     map.addLayer(endLayer);
                    }else{
                    }
                    this.countIndex = this.countIndex + 2
                }
            },
            start(carType, carzIndex, frontObj,carFlag) { //此处需要给出点击的是第几个小车，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,carFlag);
                    }
                }
            },
            // 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
            //                     })
            //                 })
            //             ];
            //         }
            //     }
            //     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;
            },
            showMediumNode(nodeArr,carType,frontObj,typeObject){
                this.startNode = typeObject.startNode
                this.startNode  = typeObject.endNode
                this.startNode  = typeObject.nodeCount
                this.startNode = new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: frontObj.startIcon,
                                scale:frontObj.startScale
                            }),
                            text: new Text({
                                font: "bold 12px 黑体",
                                text: "起点",
                                fill: new Fill({
                                    color: "#aa3300"
                                }),
                                stroke: new Stroke({
                                    color: "#fff",
                                    width: 2
                                }),
                                textAlign: "left"
                            })
                        })
                this.endNode = new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: frontObj.endIcon,
                                scale:frontObj.endScale
                            }),
                            text: new Text({
                                font: "bold 12px 黑体",
                                text: "终点",
                                fill: new Fill({
                                    color: "#aa3300"
                                }),
                                stroke: new Stroke({
                                    color: "#fff",
                                    width: 2
                                }),
                                textAlign: "left"
                            })
                        })
                this.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)'
                                })
                            })
                        })
                for(let i = 0;i<nodeArr.length;i=i+1){
                    if(i==(nodeArr.length-1)){//终点
                        let endMarker = this.featureSymbol('','',typeObject.endNode,typeObject.endNode,new Point([nodeArr[nodeArr.length-1].Y,nodeArr[nodeArr.length-1].X]),frontObj.routArr[i].attributes)
                        let endNodeMarker = new VectorSource()
                        endNodeMarker.addFeature(endMarker);
                        let endLayer = new VectorLayer({
                            id: typeObject.endNode,
                            style: this.endNode,
                           source: endNodeMarker
                        });
                        endLayer.setZIndex(frontObj.endIndex)
                        frontObj.map.addLayer(endLayer);
                    }else if(i==0){//起点
                        let startMarker = this.featureSymbol('','',typeObject.startNode,typeObject.startNode,new Point([nodeArr[0].Y,nodeArr[0].X]),frontObj.routArr[i].attributes)
                        let startNodeMarker = new VectorSource()
                        startNodeMarker.addFeature(startMarker);
                        let startLayer = new VectorLayer({
                            id: typeObject.startNode,
                            style: this.startNode,
                           source: startNodeMarker
                        });
                        startLayer.setZIndex(frontObj.startIndex)
                        frontObj.map.addLayer(startLayer);
                    }else{
                        this.addMediumNode(typeObject.nodeCount,nodeArr[i].attributes.index + 1,nodeArr[i].attributes,[parseFloat(nodeArr[i].attributes.info.longitude),parseFloat(nodeArr[i].attributes.info.latitude)],frontObj,typeObject)
                        //this.addMediumNode(typeObject.nodeCount,nodeArr[i+1].attributes.index + 1,nodeArr[i + 1].attributes,[parseFloat(nodeArr[i+1].attributes.info.longitude),parseFloat(nodeArr[i+1].attributes.info.latitude)],frontObj,typeObject)
                    }
                }
            },
            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('roadFinish3', 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')
                        }
                    }
                }
            },
            addCar(point,source,carzIndex,carFlag){
                var feature = new Feature(point);
                //let data_end = new VectorSource()
                source.addFeature(feature);
                clearSpatial('car2', this.startObj.map)//import直接引入的不需要加this
                let line_layer = this.vectorLayerSymbol('car2','',source,this.styles.geoMarker)
                line_layer.setZIndex(carzIndex)
                this.startObj.map.addLayer(line_layer)
            },
            startAnimation(index, carType, carzIndex,carFlag) {
                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]);
                        let data_end = new VectorSource()
                        _this.finished = true
                        _this.addCar(endPoint,data_end,carzIndex,carFlag)
                         _this.$emit('finish3', _this.finished)
                        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);
                        let data_c = new VectorSource()
                        _this.addCar(currentPoint,data_c,carzIndex,carFlag)
                        index++
                        _this.finished = false
                        _this.startAnimation(index);
                        _this.$emit('finish3', _this.finished)
                    }
                }, 500)
                _this.$emit('timer3', _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>