import _ from "lodash";
import {getImages} from '@/plugins/images.js'
import store from '@/store'
//图标

let cheliangtuli_tingche1 = getImages('/assetsMobile/svg/icon-cheliangtuli_tingche1.svg') //停留报警
let cheliangtuli_baojing1 = getImages('/assetsMobile/svg/icon-cheliangtuli_baojing1.svg') //违规报警
let origin = getImages('/assetsMobile/svg/origin.svg') //起点
let destination = getImages('/assetsMobile/svg/destination.svg') //终点
// 经过点类型 1.标注点 2.收集点 3.转运站 4.处理厂 5.公厕 6.投放点 7.垃圾桶 途径点不同类型图标
let vehis1Icon = getImages('/assetsMobile/svg/icon-cheliangtuli_biaozhudian.svg') 
let vehis2Icon = getImages('/assetsMobile/svg/icon-cheliang_shoujidian.svg') 
let vehis3Icon = getImages('/assetsMobile/svg/icon-cheliangtuli_zhuanyunzhan.svg')
let vehis4Icon = getImages('/assetsMobile/svg/icon-cheliang_chulichang.svg')
let vehis5Icon = getImages('/assetsMobile/svg/icon-cheliang_toufangdian.svg')
let vehis6Icon = getImages('/assetsMobile/svg/icon-cheliang_toufangdian.svg')
let vehis7Icon = getImages('/assetsMobile/svg/icon-cheliangtuli_lajitong.svg')


/**创建弧线*/
export function createPulseLinkLayer(map) {

    // 创建 Loca 实例
    let loca = new Loca.Container({
        map: map
    });

    // 弧线
    var pulseLink = new Loca.PulseLinkLayer({
        // loca,
        zIndex: 10,
        opacity: 1,
        visible: true,
        zooms: [2, 22],
        depth: true,
    });

    var geo = new Loca.GeoJSONSource({
        url: 'https://a.amap.com/Loca/static/loca-v2/demos/mock_data/data-line-out.json',
    });

    pulseLink.setSource(geo);
    pulseLink.setStyle({
        unit: 'meter',
        dash: [40000, 0, 40000, 0],
        lineWidth: function () {
            return [10000, 1000];
        },
        height: function (index, feat) {
            return feat.distance / 3 + 10;
        },
        // altitude: 1000,
        smoothSteps: 30,
        speed: function (index, prop) {
            return 1000 + Math.random() * 200000;
        },
        flowLength: 100000,
        lineColors: function (index, feat) {
            return ['rgb(255,228,105)', 'rgb(255,164,105)', 'rgba(1, 34, 249,1)'];
        },
        maxHeightScale: 0.3, // 弧顶位置比例
        headColor: 'rgba(255, 255, 0, 1)',
        trailColor: 'rgba(255, 255,0,0)',
    });
    loca.add(pulseLink);
    loca.animate.start();
}


/**创建聚合点*/
export function createMarkerCluster(map, data, callBack) {
    let { points } = data
    /**完全自定义点样式*/
    function _renderMarker(context) {
        // console.log(context,'context')
        // var content = `<img style="width: 28px;"  src="${context.data[0].item.img}" />`;
        var content = `
                <div style="position: relative;">
                    <img src="${context.data[0].item.img}" 
                        style="width: 28px; transform:rotate(${context.data[0].item.direction}deg)"/></br>
                    <div style="
                        border:solid 1px #00a0e9; 
                        background-color:#ffffff;
                        position: absolute;
                        padding: 2px;
                        white-space: nowrap;
                        left: 50%;
                        top: 100%;
						font-size: 12px;
                        transform: translate(-50%,0%);
                    "
                       
                    >
                        ${context.data[0].item.label}
                    </div>
                </div>
        `;
        var offset = new AMap.Pixel(-14, -14);
        context.marker.setContent(content)
        context.marker.setOffset(offset)
        // context.marker.setAngle(context.data[0].item.direction)
    }
    let cluster = new AMap.MarkerCluster(map, points, {
        gridSize: 60, // 设置网格像素大小
        renderMarker: _renderMarker,
        clusterByZoomChange: false
    });
	
	let handleClickData = _.throttle((e) => {
		// console.log('testeeee',e)
		callBack(e)
	},500, {leading: true,trailing: false})
    cluster.on('click', (e) => {
		handleClickData(e)
    })

    return cluster
}

/**创建标注点*/
let allmarkerArr = [];
export function createMarker(map, data, callBack) {
    console.log('参', data)
    let iconMap = {
        'vehStop': cheliangtuli_tingche1,
        'veAlarm': cheliangtuli_baojing1,
        // 经过点类型 1.标注点 2.收集点 3.转运站 4.处理厂 5.公厕 6.投放点 7.垃圾桶
        'vehis1': vehis1Icon,
        'vehis2': vehis2Icon,
        'vehis3': vehis3Icon,
        'vehis4': vehis4Icon,
        'vehis5': vehis5Icon,
        'vehis6': vehis6Icon,
        'vehis7': vehis7Icon,
    }
    let markerArr = data.list.map(e => {
        let icontype=data.type
        if(icontype==='vehis'){ //途径点
            icontype=`${icontype}${e.type}`
            e.cloneType = e.type
        }
        // 创建一个 Icon
        let startIcon = new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(31, 40),
            // 图标的取图地址
            image: iconMap[icontype],//'//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            // 图标所用图片大小
            imageSize: new AMap.Size(31, 40),
        });
        let marker
        if (e.option) {
            marker = new AMap.Marker({
                ...e.option
            });
        } else {
            marker = new AMap.Marker({
                icon: startIcon,
                position: [e.lng02, e.lat02],
                offset: new AMap.Pixel(0, 6),
                anchor: 'bottom-center'
            });
        }

        marker.on('click', function (el) {
            console.log('点击', e)
            callBack('click', { ...e, type: data.type})
        })
        return marker
    })
    map.add(markerArr);
    // 实例方法
    allmarkerArr = allmarkerArr.concat(markerArr)
    const removeAllMarkers = () => {
        for (var i = 0; i < allmarkerArr.length; i++) {
            allmarkerArr[i].setMap(null); // 从地图上移除标记点
        }
        allmarkerArr = []; // 清空存储标记点的数组
    }

    return { removeAllMarkers };
}

/**创建轨迹回放 */
let marker, originMarker, destinationMarker, polyline, passedPolyline, startAnimation, removeShowSpeed;
const setCenterDebounce = _.throttle((map, e) => {
    var isVisible = map.getBounds().contains(e.target.getPosition());
    if (!isVisible) {
        map.setCenter(e.target.getPosition(), true)//自动聚焦
    }
    // map.setCenter(e.target.getPosition(), true)//自动聚焦
}, 0);

export function createMoveAlong(map, data, callBack) {
    console.log(marker, 'marker数据', data)
    let pointsData = data.points
    let points = pointsData.map(e => {
        return [Number(e.lng02), Number(e.lat02)]
    })
    let resetIdx;
    //清空已有实例
    if (marker) {
        marker.stopMove();
        marker.off('moving', markerMoving);
        marker.setMap(null);
        marker = null;
    }
    //清空起点和终点
    if (originMarker) {
        originMarker.setMap(null);
        originMarker = null
    }
    if (destinationMarker) {
        destinationMarker.setMap(null);
        destinationMarker = null
    }

    if (polyline) {
        polyline.setMap(null);
        polyline = null;
    }
    if (passedPolyline) {
        passedPolyline.setMap(null);
        passedPolyline = null;
    }
    if (removeShowSpeed) {
        removeShowSpeed();
    }

    if (pointsData.length <= 0) return; //无数据
    let duration = pointsData[0].duration //传入的速度
    let tabStyle = pointsData[0].tabStyle //传入的类型 人员车辆

    // 1、创建图标
	

    let icons
	if (store.state.pastRoute.mapImg) {
		icons = new AMap.Icon({
		    image: store.state.pastRoute.mapImg, // 图标的图片地址
		    size: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
		    imageSize: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
		})
	} else {
		icons = "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png"
	}
	

    marker = new AMap.Marker({
        map: map,
        position: points[0], //points[0],
        icon: icons,
        zIndex: 18,
        offset: new AMap.Pixel(-13, -26),
    });
    //创建起点终点图标显示
    let originicons = new AMap.Icon({
        image: origin, // 图标的图片地址
        size: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
        imageSize: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
    })
    originMarker = new AMap.Marker({
        map: map,
        position: points[0], //points[0],
        icon: originicons,
        zIndex: 16,
        offset: new AMap.Pixel(-13, -26),
    });
    let destinationicons = new AMap.Icon({
        image: destination, // 图标的图片地址
        size: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
        imageSize: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
    })
    destinationMarker = new AMap.Marker({
        map: map,
        position: points[points.length - 1], //points[0],
        icon: destinationicons,
        zIndex: 16,
        offset: new AMap.Pixel(-13, -26),
    });

    // 2、创建路线

    polyline = new AMap.Polyline({
        map: map,
        path: points,
        zIndex: 10,
        showDir: true,
        strokeColor: "#28F",  //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6,      //线宽
        // strokeStyle: "solid"  //线样式
    });
    // 3、创建行驶路线
    passedPolyline = new AMap.Polyline({
        zIndex: 13,
        map: map,
        strokeColor: "#AF5",  //线颜色
        strokeWeight: 6,      //线宽
    });


    // 4、事件监听
    marker.on('moving', markerMoving);
    function markerMoving(e) {
        console.log('更新轨迹', e)
        // 更新轨迹
        let passedPath = e.passedPath
        if (resetIdx) {
            e.index = e.index + resetIdx //拖拽
            passedPath = [...points.slice(0, resetIdx), ...e.passedPath]  //points.slice(0,index+1).concat(e.passedPath)
        }
        if (tabStyle === 'vehicle') {
            marker.setAngle(pointsData[e.index + 1].direction) //手动设置方向
        }
        passedPolyline.setPath(passedPath);//聚焦
        setCenterDebounce(map, e)
        callBack('moving', e)
    }
    marker.on('click', function (e) {
        if (resetIdx) {
            e.resetIdx = resetIdx
        }
        
        callBack('click', e)
    })

    map.setFitView(marker,false,[60,60,160,60],10);
    // 开始
    startAnimation = function startAnimation() {
        let resetPoints;
        if (resetIdx) { //拖拽
            resetPoints = points.slice(resetIdx, points.length)
            if (resetPoints.length < 2) return; //moveAlong必须两点
        }
        marker.moveAlong(resetPoints || points, {
            // 每一段的时长
            duration: duration || 500,//可根据实际采集时间间隔设置
            // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
            autoRotation: false, //设置后setAngle无效BUG 
        });
    };

    // 销毁事件

    const pauseAnimation = function () {
        marker.pauseMove();
    };

    const resumeAnimation = function () {
        marker.resumeMove();
    };

    const stopAnimation = function () {
        marker.stopMove();
    };


    const moveTo = function ({ lnglat, angle, index }) {
        stopAnimation()
        resetIdx = index
        marker.setPosition(lnglat)
        // console.log('设置方向', angle)
        if (tabStyle === 'vehicle') {
            marker.setAngle(angle)
        }
        passedPolyline.setPath(points.slice(0, index + 1));
        callBack('moveTo', { lnglat, angle, index })

        // marker.moveTo(lnglat) //卡顿BUG
    }

    const resetMoveAlong = function () {
        startAnimation()
    }

    // 显示速度
    let polylineArr = []
    const showSpeed = function () {
        for (var i = 0; i < points.length - 1; i++) {
            let itempolyline = new AMap.Polyline({
                path: [points[i], points[i + 1]],
                showDir: true,
                strokeColor: speedColor(pointsData[i].speed),
                strokeOpacity: 1,
                zIndex: 11,
                strokeWeight: 6,// 线宽
                map: map
            });
            polylineArr.push(itempolyline)
        }
        function speedColor(e) { //速度颜色
            let speed = Number(e)
            let itemColor = '#16B92A'
            if (speed > 60 && speed <= 80) {
                itemColor = '#0000FE'
            } else if (speed > 80 && speed <= 100) {
                itemColor = '#F98202'
            } else if (speed > 100) {
                itemColor = '#FE0100'
            }
            return itemColor
        }
    }
    removeShowSpeed = () => {
        for (var i = 0; i < polylineArr.length; i++) {
            polylineArr[i].setMap(null); // 从地图上移除标记点
        }
        polylineArr = []; // 清空存储标记点的数组
    }


    return {
        startAnimation,
        pauseAnimation,
        resumeAnimation,
        stopAnimation,
        moveTo,
        resetMoveAlong,
        showSpeed, //显示速度
        removeShowSpeed //关闭速度
    }
}

/**创建一条展示路线 */
let PolylineShow,lineShoworiginMarker,lineShowdestinationMarker;
export function createPolylineShow(map, data) {
    if (PolylineShow) {
        PolylineShow.setMap(null);
        PolylineShow = null;
    }
    if (lineShoworiginMarker) {
        lineShoworiginMarker.setMap(null);
        lineShoworiginMarker = null;
    }
    if (lineShowdestinationMarker) {
        lineShowdestinationMarker.setMap(null);
        lineShowdestinationMarker = null;
    }
    let { points } = data
    let pointsArr = points.map(e => {
       return [Number(e.lng02), Number(e.lat02)]
    })
    PolylineShow = new AMap.Polyline({
        map: map,
        path: pointsArr,
        strokeStyle: "solid",
        strokeColor: "#027AFF",  //线颜色
        strokeWeight: 6,      //线宽
    });
     //创建起点终点图标显示
     let originicons = new AMap.Icon({
        image: origin, // 图标的图片地址
        size: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
        imageSize: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
    })
    lineShoworiginMarker = new AMap.Marker({
        map: map,
        position: pointsArr[0], //points[0],
        icon: originicons,
        zIndex: 16,
        offset: new AMap.Pixel(-13, -26),
    });
    let destinationicons = new AMap.Icon({
        image: destination, // 图标的图片地址
        size: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
        imageSize: new AMap.Size(28, 28), // 设置图标的大小，这里是宽度和高度均为48像素
    })
    lineShowdestinationMarker = new AMap.Marker({
        map: map,
        position: pointsArr[pointsArr.length - 1], //points[0],
        icon: destinationicons,
        zIndex: 16,
        offset: new AMap.Pixel(-13, -26),
    });
}