
import { Loading } from 'element-ui';

export default {
    props:{
        //运输订单号
        orderNumber:'', 
        //车牌号
        capacityNumber:'',
    },
    data() {
        return {
            //地图对象
            map:{},
            //加载消息
            loading : null,
            //运输详情
            transportDetails:{
                //车牌号
                capacityNumber:'',
                //规划路线
                planeRoute:[],
                //已行驶轨迹
                routeTraveled:[],
                //当前位置
                currentPoint:{
                    currentPointLat:"",
                    currentPointLon:""
                },
                //起点位置
                startPoint:{
                    currentPointLat:"",
                    currentPointLon:""
                },
                //重点位置
                endPoint:{
                    currentPointLat:"",
                    currentPointLon:""
                },
                //自定义标记
                content:[],
                //异常位置
                abnormalLocation:[],
            }
        };
    },
    watch:{
        //监听车牌号变化
        orderNumber:{
            deep: true,
            handler(val, oldVal) {
                this.reloadData();
            }
        },
        //进度条速度
        sliderVal(newVal) {
            if (!this.isOnSlider) {
                return false;
            }
            this.sliderChange(newVal)
        },
    },
    created(){
        //加载数据
        this.reloadData();
    },
    mounted: function () {
                
    },
    methods: {
        //加载中提示
        startLoading (){
            this.loading = Loading.service({ lock: true, text: '加载中……', background: 'rgba(0, 0, 0, 0.7)' });
        },
        //加载数据
        reloadData() {
            let resultData = {
                orderNumber: this.orderNumber,
            };
            this.startLoading(this.orderNumber);
            this.$axios.post(
                "api/v1/getway/fullPathVisualization",resultData
                ).then((res) => {
                this.loading.close(); 
                if(res.data.startAndEndRoutes!=null){
                    this.initMap(res.data);
                }else{
                    this.$message('车辆未入网或没有开启定位，不能访问');
                    this.newMap();
                }
            }).catch(error => {
                    this.loading.close(); 
                
                if((error+"").indexOf("500") !== -1){
                        this.$message('车辆未入网或没有开启定位，不能访问');
                        this.newMap();
                }
            });    
        },
        //初始化一个地图
        initMap1(){
            lazyAMapApiLoaderInstance.load().then(() => {
                this.map = new AMap.Map('test-map', {
                  zooms: [13, 18], // 地图缩放范围
                  center: new AMap.LngLat(116.397428, 39.90923)
                })
                this.initPathSimplifier()
            })
            let that = this;
            let el = document.getElementsByClassName("el-slider__button-wrapper")[0];
            let el2 = document.getElementsByClassName("el-slider__runway")[0];
            el2.addEventListener("click", that.sliderChange,false);
            el.addEventListener("mousedown", that.openSlider,false);
            // 此处用document是因为，滑动较为随意时，mouseup可能不是作用在el上
            document.addEventListener("mouseup",that.closeSlider,false);
        },
        // 初始化组件实例
        initPathSimplifier() {
            let that = this
            AMapUI.load(['ui/misc/PathSimplifier'], (PathSimplifier) => {
            if (!PathSimplifier.supportCanvas) {
                alert('当前环境不支持 Canvas！')
                return
            }
            //创建一个巡航轨迹路线
            that.pathSimplifierIns = new PathSimplifier({
                zIndex: 100,//地图层级，
                map: this.map, //所属的地图实例
                //巡航路线轨迹列表
                getPath: (pathData, pathIndex) => {
                    return pathData.path;
                },
                //hover每一个轨迹点，展示内容
                getHoverTitle: function(pathData, pathIndex, pointIndex) {
                    if (pointIndex >= 0) {
                        return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
                    }
                    return pathData.name + '，点数量' + pathData.path.length;
                    },
                    //自定义样式，可设置巡航器样式，巡航轨迹样式，巡航轨迹点击、hover等不同状态下的样式，不设置则用默认样式，详情请参考api文档 renderOptions:{}
                    //绘制路线节点
                    renderOptions: {
                    renderAllPointsIfNumberBelow: 100 //绘制路线节点，如不需要可设置为-1
                }
            });

            //设置数据
            that.pathSimplifierIns.setData([{
                name: '1',
                path: that.actualList
            }]);
            //对第一条线路（即索引 0）创建一个巡航器
            that.navgtr = that.pathSimplifierIns.createPathNavigator(0, {
                loop: false, //循环播放
                speed: that.navgtrSpeed //巡航速度，单位千米/小时
            });

            that.navgtr.on("start resume", function() {
                that.navgtr._startTime = Date.now();
                that.navgtr._startDist = this.getMovedDistance();
            });
            that.navgtr.on("stop pause", function() {
                that.navgtr._movedTime = Date.now() - that.navgtr._startTime;
                that.navgtr._movedDist = this.getMovedDistance() - that.navgtr._startDist;
            });
            that.navgtr.on("move", function(data,position) {
                let idx = position.dataItem.pointIndex //走到了第几个点
                let tail = position.tail //至下一个节点的比例位置
                let totalIdx = idx + tail
                let len = position.dataItem.pathData.path.length

                // 计算下一个距离速度
                if (idx < len - 1) {
                that.navgtr.setSpeed(that.navgtrSpeed * that.times);
                }
                // 进度条实时展示tail
                !that.isOnSlider && (that.sliderVal = (totalIdx / len) * 100);
                // 如果到头了，回到初始状态
                if (that.navgtr.isCursorAtPathEnd()) {
                that.playIcon = "start";
                that.isPlay = false;
                that.sliderVal = 0;
                that.passedTime = that.totalTime;
                }
            });
            })
        },
        //控制车辆跟随进度条移动
        sliderChange(val){
            let newVal = typeof(newVal)==='number' ? val : this.sliderVal
            let num = parseInt((newVal / 100) * this.actualList.length);
            let decimal = String((newVal / 100) * this.actualList.length).split('.')[1]||0
            this.navgtr.moveToPoint(num, Number('0.'+decimal));
            this.pathSimplifierIns.renderLater();
        },
         //创建一个地图
        newMap(){
            var currentPointLat='32.483276';//默认的中心点的纬度
            var currentPointLon='114.03629';//默认的中心点的经度
            this.map = new AMap.Map('container', {
                zoom:11,//级别
                center: [currentPointLon,currentPointLat],//中心点坐标
                viewMode:'3D'//使用3D视图
            });
            //自定义的标记点
            var content = [
                    "<div  style='top:1px;width: 180px; background-color: rgba(0, 0, 0, 1);' ><b>"+this.capacityNumber+")</b>",
                    "<div style='background-color:rgba(255, 255, 255, 0.5);'>提示 :"+'GPS没有开启'+"</div></div>"
            ];
            // 创建 infoWindow 实例	
            var infoWindow = new AMap.InfoWindow({
                content: content.join("<br>")  //传入 dom 对象，或者 html 字符串
            });
            // 打开信息窗体
            infoWindow.open(this.map,[currentPointLon,currentPointLat]);
        },
        initMap(data) {
            var currentPointLat='32.483276';
            var currentPointLon='114.03629';
            var polyline=[];
            //初始化地图
            if (data.startAndEndRoutes[0].currentPoint!=null){
                currentPointLat=data.startAndEndRoutes[0].currentPoint.lat;
                currentPointLon=data.startAndEndRoutes[0].currentPoint.lon;
            }
            this.map = new AMap.Map('container', {
                zoom:11,//级别
                center: [currentPointLon,currentPointLat],//中心点坐标
                viewMode:'3D'//使用3D视图
            });
            var limeList= [];
            data.startAndEndRoutes.forEach((element,index) => {
                var startPaths=[];
                element.runRoute.forEach((element,index) => {
                    var path= [element.lon,element.lat];
                    startPaths.push(path);
                });
                var endPaths=[];
                if(element.estimateRoute!=null){
                    element.estimateRoute.forEach((element,index) => {
                        var path= [element.lon,element.lat]
                        endPaths.push(path);
                    });
                }
                if (element.startPoint!=null){
                    //当前点图标标记点
                    let startPointicon = new AMap.Icon({
                        size: new AMap.Size(25, 35), // 图标尺寸
                        image: require('@/assets/img/start.png'), // Icon的图像
                        imageOffset: new AMap.Pixel(0,0), // 图像相对展示区域的偏移量，适于雪碧图等
                        imageSize: new AMap.Size(25, 35) // 根据所设置的大小拉伸或压缩图片
                    });
                    // 创建一个 Marker 实例：
                    var startPointmarker = new AMap.Marker({
                        position: new AMap.LngLat(element.startPoint.lon, element.startPoint.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                            icon: startPointicon, 
                        title: '北京'
                    });
                    // 将创建的点标记添加到已有的地图实例：
                    this.map.add(startPointmarker);
                }
                //终点
                if (element.endPoint!=null){
                    //当前点图标标记点
                    let endPointicon = new AMap.Icon({
                        size: new AMap.Size(25, 35), // 图标尺寸
                        image: require('@/assets/img/end.png'), // Icon的图像
                        imageOffset: new AMap.Pixel(0,0), // 图像相对展示区域的偏移量，适于雪碧图等
                        imageSize: new AMap.Size(25, 35) // 根据所设置的大小拉伸或压缩图片
                    });
                    // 创建一个 Marker 实例：
                    var endPointmarker = new AMap.Marker({
                        position: new AMap.LngLat(element.endPoint.lon, element.endPoint.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                        icon: endPointicon, 
                        title: '北京'
                    });

                    // 将创建的点标记添加到已有的地图实例：
                    this.map.add(endPointmarker);
                }
                //已行驶轨迹
                if(startPaths.length>0){
                    var startLine = new AMap.Polyline({
                        map:this.map,
                        path: startPaths,
                        isOutline: true,
                        outlineColor: '#00FF00',
                        borderWeight: 0,
                        strokeColor: "#00FF00", 
                        strokeOpacity: 1,
                        strokeWeight: 5,
                        // 折线样式还支持 'dashed'
                        strokeStyle: "solid",
                        // strokeStyle是dashed时有效
                        strokeDasharray: [10, 5],
                        lineJoin: 'round',
                        lineCap: 'round',
                        zIndex: 50,
                    })
                    limeList.push(startLine);
                }

            if(endPaths.length>0){
                //预计轨迹
                var endLine = new AMap.Polyline({
                    map:this.map,
                    path: endPaths,
                    isOutline: true,
                    outlineColor: '#FF0000',
                    borderWeight: 0,
                    strokeColor: "#FF0000", 
                    strokeOpacity: 1,
                    strokeWeight: 5,
                    // 折线样式还支持 'dashed'
                    strokeStyle: "solid",
                    // strokeStyle是dashed时有效
                    strokeDasharray: [10, 5],
                    lineJoin: 'round',
                    lineCap: 'round',
                    zIndex: 50,
                })
                limeList.push(endLine);
            }
                
            });
            var content = [
                    "<div  style='top:1px;width: 180px; background-color: rgba(0, 0, 0, 1);' ><font color='white'>"+this.capacityNumber+'('+data.startAndEndRoutes[0].miled+")</font>",
                    "<div style='background-color:rgba(255, 255, 255, 0.5);'><font color='white'>地址 :"+data.startAndEndRoutes[0].currentPointName+"</font></div></div>"
            
            ];
            data.startAndEndRoutes.forEach((element,index) => {
                // 创建 infoWindow 实例	
                var infoWindow = new AMap.InfoWindow({
                content: content.join("<br>")  //传入 dom 对象，或者 html 字符串
                });

                //当前点图标标记点
                let currentPointicon = new AMap.Icon({
                    size: new AMap.Size(40, 40), // 图标尺寸
                    image: require('@/assets/img/car1.png'), // Icon的图像
                    imageOffset: new AMap.Pixel(0,0), // 图像相对展示区域的偏移量，适于雪碧图等
                    imageSize: new AMap.Size(40, 40) // 根据所设置的大小拉伸或压缩图片
                });

                // 创建一个 Marker 实例：
                var currentPointmarker = new AMap.Marker({
                    position: new AMap.LngLat(element.runRoute[element.runRoute.length-1].lon,element.runRoute[element.runRoute.length-1].lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                        icon: currentPointicon, 
                    title: '北京'
                });
                // 将创建的点标记添加到已有的地图实例：
                this.map.add(currentPointmarker);
                    // 打开信息窗体
                    infoWindow.open(this.map,[element.runRoute[element.runRoute.length-1].lon,element.runRoute[element.runRoute.length-1].lat]);
            });
            
            this.map.setFitView([ limeList ])
        }
    }
};