<template>
</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,lineShowDistant
    } from './poiQuery'
    import 
        lineListData 
     from './road.js'
    import Feature from 'ol/Feature'
    import LineString from 'ol/geom/LineString'
    import Point from 'ol/geom/Point'
    import {addVector} from '../base/poiQuery'
    import rbush from 'rbush'
    export default {
        name: 'constantSpeed2',
        render() {},
        data() {
            return {
                animating: false,
                geoMarker: {},
                routeLength: 0,
                map:{},
                routeLength:0,
                routeCoords:[],
                styles:{},
                receiveObj:{},
                initRouteObj:{}
            }
        },
        watch: {
            position(val) { //父组件点击地图，将父组件的position传递给子组件，子组件监听父组件属性的变化
                this.pos = val
            }
        },
        //mixins: [commonMixin('overlay')],
        methods: {
            initRoute(initRouteObj,map){
                this.initRouteObj = initRouteObj;
                this.initObject_car(this.initRouteObj.initPosArr,0,1,map);//渲染路径的时候加入小车
            },
            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 styles = [
                    new Style({ // 线串的样式
                           stroke: new Stroke({//箭头标识
                            width: this.initRouteObj.routeWidth, 
                            color: this.initRouteObj.routeColor,
                        })
                    })
                ];
                //对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.initRouteObj.arrowImage,
                            anchor: [0.75, 0.5],
                            scale:this.initRouteObj.arrowScale,
                            rotateWithView: true,
                            rotation: -arrow_rotation
                        })
                    }));
                }
                return styles;
            },
            testBus(map){
                // lineListData.forEach((item,index)=>{
                //     item.value.forEach((items)=>{
                //         //var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});
                //         this.arrToRoute(item.lineId,items[0],items[1],{"lineWidth":5,"lineColor":item.lineColor},10,map);
                //     })
                // })
                lineListData.forEach((item,index)=>{
                    //var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});
                    this.arrToRoute(item.lineId,item.value,{"lineWidth":5,"lineColor":item.lineColor},10,map);
                })
            },
            initObject_car(initPosArr,startIndex,endIndex,map) { //初始化点
                this.geoMaker = {};
                this.geoMarker = new Feature({ //第一个坐标值
                    geometry: new Point(initPosArr[startIndex])
                })
                let p_style = new Style({
                    // 设置一个标识
                    image: new Icon({
                        src: this.initRouteObj.carImage,
                        // 这个是相当于是进行切图了
                        // size: [50,50],
                        // 注意这个，竟然是比例 左上[0,0]  左下[0,1]  右下[1，1]
                        anchor: [0.5, 0.5],
                        // 这个直接就可以控制大小了
                        scale: this.initRouteObj.carScale,
                        rotation: -Math.atan2(initPosArr[startIndex][1]-initPosArr[endIndex][1], initPosArr[startIndex][0]-initPosArr[endIndex][0]),
                        // 开启转向
                        rotateWithView: true,
                        // rotation: 0,
                    }),
                })
                this.geoMarker.setStyle(p_style)
                var vectorLayer = new VectorLayer({
                    id:this.initRouteObj.initCarPosId,
                    source: new VectorSource({//一次放入四个feature
                        features: [this.geoMarker]
                    })
                });
                vectorLayer.setZIndex(this.initRouteObj.carAndNodeIndex)
                //将图层vectorLayer加入到map地图中
                map.addLayer(vectorLayer);
            },
            startAnimation(moveCarObject) {
                //如果小车刚开始没有跑动
                this.routeCoords = moveCarObject.routeCoords;//获取全部坐标
                this.receiveObj = moveCarObject
                this.routeLength = this.routeCoords.length;
                if(this.routeLength==undefined){
                     alert("请等待路网渲染完毕");
                     return;
                }
                if(this.routeCoords.length == 0){
                    // alert("请先绘制车辆路径");
                }else{
                    if (this.animating) {
                        this.stopAnimation(false);
                    } else {
                        this.animating = true;
                        this.now = new Date().getTime();
                        // this.speed = document.getElementById('constantSpeed').value;
                        this.speed =  this.receiveObj.speed;
                        // this.$refs.startButton.textContent = '退出回放';
                        // hide geoMarker
                        this.geoMarker.setStyle(null);
                        // just in case you pan somewhere else
                        // this.map.getView().setCenter(center);
                        this.receiveObj.map.on('postcompose', this.moveFeature);
                        this.receiveObj.map.render();
                    }
                }
            },
            moveFeature(event){
                // this.routeCoords = this.receiveObj.routeCoords
                var vectorContext = event.vectorContext;//HTML5 Canvas context，ol.render.canvas.Immediate的对象
                var frameState = event.frameState;//frame 的状态
                if (this.animating) {
                    var elapsedTime = frameState.time - this.now;
                    var index = Math.round(this.speed * elapsedTime / 1000);
                    if (index >= this.routeLength) {
                        this.initObject_car(this.routeCoords,this.routeLength-1,this.routeLength-2,this.receiveObj.map)  //初始化点
                        this.stopAnimation(true);
                        return;
                    }
                    var dx,dy,rotation,carStyle;
                    if(this.routeCoords[index] && this.routeCoords[index+1]){
                        // lineShowDistant(this.receiveObj.redLineId,[this.routeCoords[index][0],this.routeCoords[index][1]],[this.routeCoords[index+1][0],this.routeCoords[index+1][1]],{"lineWidth":this.receiveObj.redLineWidth,"lineColor":this.receiveObj.redLineColor},this.receiveObj.redLinezIndex,this.receiveObj.map)
                        dx=this.routeCoords[index][0]-this.routeCoords[index+1][0];
                        dy=this.routeCoords[index][1]-this.routeCoords[index+1][1];
                        rotation = Math.atan2(dy,dx);
                        carStyle= new Style({
                            image: new Icon({
                                src: this.receiveObj.carImage,
                                rotateWithView: false,
                                rotation: -rotation,
                                scale:this.receiveObj.carScale,
                            })
                        });
                        var currentPoint = new Point(this.routeCoords[index]);
                        var feature = new Feature(currentPoint);
                        vectorContext.drawFeature(feature, carStyle);
                    }
                }
                // tell OpenLayers to continue the postcompose animation
                this.receiveObj.map.render();
            },
            stopAnimation(ended){
                if(ended==undefined) return;
                if(this.routeCoords.length==0) return;
                this.animating = false;
                // this.$refs.startButton.textContent = '开始回放';
                // if animation cancelled set the marker at the beginning
                if(this.geoMarker.getGeometry!=undefined){
                     var coord = ended ? this.routeCoords[this.routeLength - 1] : this.routeCoords[0];
                    /** @type {ol.geom.Point} */ (this.geoMarker.getGeometry())
                        .setCoordinates(coord);
                    //remove listener
                    this.receiveObj.map.un('postcompose', this.moveFeature);
                }  
            }
        }
    }
</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>