<!-- 轨迹回放组件 -->
<template>
    <div class="sfdsc-TrackPlayback" :style="{ width: width, height: height + 'px' }">
        <el-amap
            vid="amap"
            ref="map"
            :resize-enable="true"
            :bubble="true"
            :zoom="map.zoom"
            :center="map.center"
        >
            <template v-for="(marker, index) in markerList">
                <el-amap-marker
                    v-if="marker.offset"
                    :key="index"
                    :position="marker.position"
                    :offset="marker.offset"
                    :draggable="true"
                    :icon="marker.icon"
                    :label="marker.markerLabel||''"
                ></el-amap-marker>
                <el-amap-marker
                    v-else
                    :key="index"
                    :position="marker.position"
                    :draggable="true"
                    :icon="marker.icon"
                    :label="marker.markerLabel||''"
                ></el-amap-marker>
            </template>
        </el-amap>
        <div class="btnBox" v-if="marker && btnShow">
            <div class="btn" :title="isPlaying ? '暂停' : '播放'" @click="play">
                <a-icon :type="isPlaying ? 'pause-circle' : 'play-circle'" />
            </div>
            <div class="btn" title="重置" @click="reset">
                <a-icon type="reload" />
            </div>
        </div>
        <div class="inputBox" v-if="marker && btnShow">
            <a-input-search
                suffix="km/h"
                placeholder="请输入回放速度"
                enter-button="回放"
                size="large"
                @search="handleSpeed"
                style="width: 300px"
                :defaultValue="actualSpeed"
                v-model="actualSpeed"
            />
        </div>
    </div>
</template>

<script>
    import { lazyAMapApiLoaderInstance } from "@/components/vueAMap";
    import { request } from "../../utils/request";

    export default {
        name: "GpsTrack",
        props: {
            // 地图宽
            width: {
                type: [String, Number],
                default: "100%"
            },
            // 地图高
            height: {
                type: [String, Number],
                default: 300
            },
            // 是否自动开始
            auto: {
                type: Boolean,
                default: false
            },
            // 速度
            speed: {
                type: Number,
                default: 200
            },
            // 图标配置
            iconOptions: {
                type: Object,
                default() {
                    return {};
                }
            },
            // 轨迹样式
            polylineOptions: {
                type: Object,
                default() {
                    return {};
                }
            },
            // 线路样式
            passedPolylineOptions: {
                type: Object,
                default() {
                    return {};
                }
            },
            // 门店数组
            markers: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                /**
                 * 高德地图相关参数配置
                 * */
                markerIcon: require("@/assets/img/car.png"),
                markerList: [],
                map: {
                    resizeEnable: true,
                    zoom: 99,
                    center: [116.478935, 39.997761]
                },
                marker: null,
                mapPolyline: null,
                passedPolyline: null,
                // 节点index
                index: 0,
                // 组件内用的speed
                actualSpeed: 0,
                //播放/暂停标识
                isPlaying: false,
                // 标识是否在原点
                atStart: true,
                btnShow: false,
                // 轨迹数组
                gpsList: [],
                lineArr: [],
                page: {pageNum:1,pageSize:3000},
                polylineData: {}
            };
        },
        watch: {
            speed(val) {
                this.actualSpeed = val;
                this.checkLoad();
            },
            markers: {
                handler(newVal) {
                    this.markerList = newVal
                },
                deep: true
            },
            iconOptions: {
                handler() {
                    this.checkLoad();
                },
                deep: true
            },
            polylineOptions: {
                handler() {
                    this.checkLoad();
                },
                deep: true
            },
            passedPolylineOptions: {
                handler() {
                    this.checkLoad();
                },
                deep: true
            },
            lineArr: {
                handler(newVal) {
                    if (newVal[0]) {
                        this.map.center = newVal[0];
                    }
                    this.checkLoad();
                },
                deep: true
            }
        },
        mounted() {
            this.actualSpeed = this.speed;
            this.markerList = this.markers;

            lazyAMapApiLoaderInstance.load().then(() => {
                /* eslint-disable */
                // 获取地图实例
                let map = this.$refs.map.$$getInstance();
                // 添加工具栏
                map.plugin(["AMap.Scale"], () => {
                    const scale = new AMap.Scale(); // 比例尺
                    map.addControl(scale);
                });
                /* eslint-disable */
            });
        },
        methods: {
            checkLoad(back) {
                lazyAMapApiLoaderInstance.load().then(() => {
                    this.startTrack(back);
                });
            },
            startTrack(back) {
                /* eslint-disable */
                // 获取地图实例
                let map = this.$refs.map.$$getInstance();
                let that = this;
                // 删除之前创建过的，防止多条重复
                if (this.marker) {
                    map.remove(this.marker);
                    map.remove(this.mapPolyline);
                    map.remove(this.passedPolyline);
                }
                // 轨迹点
                const {
                    auto,
                    actualSpeed,
                    iconOptions,
                    polylineOptions,
                    passedPolylineOptions,
                    lineArr
                } = this;
                if (lineArr.length == 0) {
                    console.log("没有轨迹数据");
                    return false;
                }
                // iconOptions可配置的参数
                let _iconOptions = {
                    position: [116.478935, 39.997761], // 图片起始位置
                    icon: "https://webapi.amap.com/images/car.png", // 图片路径
                    offset: [-26, -13], // 图片偏移量
                    autoRotation: true, // 图片是否自动旋转
                    angle: -90 // 图片旋转角度
                };
                // 判断是否有初始值，没有初始值默认为lineArr起点值
                if (!iconOptions.position) {
                    iconOptions.position = lineArr[0];
                }
                _iconOptions = {
                    ..._iconOptions,
                    ...iconOptions,
                    map
                };
                _iconOptions.offset = new AMap.Pixel(
                    _iconOptions.offset[0],
                    _iconOptions.offset[1]
                );
                this.marker = new AMap.Marker(_iconOptions);
                // 绘制轨迹可配置的参数
                let _polylineOptions = {
                    showDir: true, //线箭头
                    strokeColor: "#28F", //线颜色
                    strokeOpacity: 1, //线透明度
                    strokeWeight: 6, //线宽
                    strokeStyle: "solid" //线样式
                };
                _polylineOptions = {
                    ..._polylineOptions,
                    ...polylineOptions,
                    map,
                    path: lineArr
                };
                this.mapPolyline = new AMap.Polyline(_polylineOptions);

                // 回执经过的轨迹可配置的参数
                let _passedPolylineOptions = {
                    showDir: true, //线箭头
                    strokeColor: "#AF5", //线颜色
                    strokeOpacity: 1, //线透明度
                    strokeWeight: 6, //线宽
                    strokeStyle: "solid" //线样式
                };
                _passedPolylineOptions = {
                    ..._passedPolylineOptions,
                    ...passedPolylineOptions,
                    map
                };
                this.passedPolyline = new AMap.Polyline(_passedPolylineOptions);

                //经过轨迹的更新
                this.marker.on("moving", function(e) {
                    that.passedPolyline.setPath(e.passedPath);
                });

                this.marker.on("moveend", function(e) {
                    that.index++;
                    that.$emit("moveend", that.index);
                });
                this.marker.on("movealong", function(e) {
                    that.isPlaying = false;
                });

                // 自动适配视图
                map.setFitView();

                // 开始沿坐标移动
                if (auto) {
                    that.isPlaying = true;
                    this.marker.moveAlong(lineArr, actualSpeed);
                }

                back && back();
                /* eslint-disable */
            },
            // 开始
            startAnimation() {
                this.atStart = false;
                const { actualSpeed, lineArr } = this;
                this.marker.moveAlong(lineArr, actualSpeed);
                this.index = 0;
                this.$emit("moveend", this.index);
            },
            // 暂停
            pauseAnimation() {
                this.marker.pauseMove();
            },
            // 继续
            resumeAnimation() {
                this.marker.resumeMove();
            },
            // 停止
            stopAnimation() {
                this.marker.stopMove();
                this.index = 0;
            },
            // 播放/暂停
            play() {
                if (!this.isPlaying) {
                    this.run();
                    this.isPlaying = true;
                } else {
                    this.pause();
                    this.isPlaying = false;
                }
            },
            run() {
                // 开始运动
                if (this.atStart) {
                    //在开始位置
                    this.startAnimation();
                } else {
                    // 不在开始位置(恢复运动)
                    this.resumeAnimation();
                }
            },
            pause() {
                //暂停运动
                this.pauseAnimation();
            },
            // 重置
            reset() {
                this.isPlaying = false;
                this.atStart = true;
                this.index = 0;
                this.lineArr = [];
                this.gpsList = [];
                this.polylineData = null;
                this.btnShow = false;
                this.checkLoad();
            },
            // 回放速度
            handleSpeed(val) {
                if (!/(^[1-9]\d*$)/.test(val)) {
                    this.$message.warn("请输入正整数！");
                    return false;
                } else {
                    this.actualSpeed = val;
                    this.isPlaying = true;
                    this.startAnimation();
                }
            },
            // 获取lineArr
            polyline(d,back) {
                this.gpsList = [];
                this.lineArr = [];
                this.page = {pageNum:1,pageSize:3000};
                this.polylineData = d;
                this.selectGpsDataHistory(back);
            },
            selectGpsDataHistory(back) {
                const that = this;
                const {
                    device: {deviceId,licenceNumber,deviceNumber,deviceProvider},
                    beginTime:startTime,endTime
                } = this.polylineData;
                const {pageNum,pageSize} = this.page;
                const data = {
                    systemId: window._systemId,
                    startTime,endTime,deviceId,licenceNumber,deviceNumber,deviceProvider,
                    page: {pageNum,pageSize}
                };
                request({
                    url:'/gpsData/selectGpsDataHistory',
                    data
                }).then(res=>{
                    if(res.code == 20000) return res.data;
                }).then(res=>{
                    let {
                        device:{licenceNumber},
                        page:{total,lastPage, list = []}
                    } = res;

                    that.btnShow = parseInt(total) > 0;

                    list = list.map(item=>({...item, licenceNumber}));
                    that.gpsList = [...that.gpsList,...list];
                    if(lastPage) {
                        that.lineArr = that.gpsList.map(item=>([item.lng, item.lat]));
                        back&&back(that.gpsList,that.lineArr);
                    }else {
                        that.page.pageNum += 1;
                        that.selectGpsDataHistory(back);
                    }
                })
            },
            addMarker(arr) {
                if(arr.length) {
                    this.markerList = arr.map(item=>{
                        let {
                            marker: {id,position,icon,offset},
                            label: {offset: label_offset, content}
                        } = item;
                        return {
                            id,position,icon,offset,
                            markerLabel: {offset: label_offset, content}
                        }
                    });
                    console.log(this.markerList)
                }else {
                    this.markerList = [];
                }
            },
            subMarker(arr) {
                if(arr.length) {
                    arr.forEach(item=>{
                        let index = this.markerList.findIndex(i=>i.id==item.id);
                        if(index !== -1) {
                            this.markerList.splice(index,1);
                        }
                    })
                }
            },
            cleanMarkers() {
                this.markerList = [];
            }
        }
    };
</script>
