let index = 0

export function playAnimation(map,data,line,animateRate,view,itemIndex){
    console.log("playAnimation",line)
    if(data.animateMarker){
        map.remove(data.animateMarker)
    }
    data.animateMarker = new AMap.Marker({
        map: map,
        position: [0,0],
        icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
        offset: new AMap.Pixel(-13, -26),
        autoRotation: true
    })

    if(!data.infoWindow){
        data.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(6, -25),
            content: "",
            isCustom: true
        });
    }

    if(itemIndex !== view.animating){
        index = 0
    }

    let path = line.slice(index).map((item) => {
        return new AMap.LngLat(item.longitude, item.latitude)
    })

    data.animateMarker.stopMove();
    data.animateMarker.on("movealong",()=>{})
    let lastMovingIndex = 0
    data.animateMarker.on("moving",(e)=>{
        if(lastMovingIndex != e.index){
            index++
        }
        lastMovingIndex = e.index
        let lastLocation = e.passedPath[e.passedPath.length - 1];
        data.infoWindow.setPosition(lastLocation);
        let speed = ((line[index].speed||0) * 3.6).toFixed(2)
        data.infoWindow.setContent(`<div style="width:180px;background: #fff;border-radius: 5px">
            <div>${line[index].locationTime}</div>
            <div>${speed} km/h</div>
        </div>`);
        map.setCenter(e.target.getPosition(),true)
    })
    data.animateMarker.on("moveend",()=>{
        if(index >= line.length-2){
            setTimeout(()=>{
                view.animating = -1
                index = 0
                data.animateMarker.stopMove()
                map.remove(data.animateMarker)
                data.infoWindow.close()
            },100)
        }
    })
    let polyline = new AMap.Polyline({
        path: path,
    })
    data.animateMarker.moveAlong(polyline.getPath(),{
        duration: 1000/animateRate,
        autoRotation: true
    });
    data.infoWindow.open(map, data.animateMarker.getPosition())
}

export function stopAnimation(map,data,view){
    if(!data.animateMarker){
        return
    }
    pauseAnimation(data)
    view.animating = -1
    index = 0
}

export function pauseAnimation(data){
    if(!data.animateMarker){
        return
    }
    data.animateMarker.stopMove()
}
