<template>
  <div class="flex">
    <div :id="dom" class="row" tabindex="0">
      <div class="input-card" >
        <h5>轨迹回放</h5>
        <div class="input-item">
          <input type="button" class="btn btn-info" value="开始动画" id="start" @click="playTrajectory()" style="width: 50%"/>
          <input  type="button" class="btn btn-info" value="暂停动画" id="stop" @click="stop()" style="width: 50%"/>
        </div>
        <div class="input-item">
          <input type="button" class="btn btn-info" value="重新播放" id="again" @click="again()" style="width: 50%"/>
          <input type="button" class="btn btn-info" :value=`倍速×${speed}` id="speed" @click="setSpeed(speed)" style="width: 50%"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

export default {
  title: '高德地图轨迹回放',
  props: {
    // 需要绘制的轨迹点的点集
    outerlinedata: {
      type: Array,
      default: () => [],
    },
    dom: {
      type: String,
      default: 'amapIdLOCUS' + Math.round(Math.random()*10)+Math.round(Math.random()*10)
    },
    // 设置当前地图的视图位置 格式 {grade:15,lng:经度,lat:纬度}  grade：取值范围1~15 代表不同等级的缩放比例
    zoomcenter: {
      type: Object,
      default: null
    },
    pathnavigatorstyle: {
      type: Object,
      default: () => {
        return {
          // 图标宽度
          width: 16,
          // 图标高度
          height: 32,
        // 图标地址(外链地址或者Base64)
          iconBase64: require('../../assets/alarm.png')
        }
      }
    }
  },
  data () {
    return {
      map: null, // 当前地图对象
      firstPng: null,
      endPng: null,
      person: null,
      marker: null,
      timer: null,
      currentIndex: 0,
      speed: 1
    }
  },
  created () {
  },
  methods: {
    //  初始化地图
    initMap () {
      // 初始化地图组件
      let thas = this
      // 初始化地图组件
      this.map = new AMap.Map(thas.dom, {
        resizeEnable: true,// 如果center属性缺省，地图默认定位到用户所在城市的中心
        scrollWheel: true, // 是否可以通过滑轮控制缩放
        zoom: 7,
        viewMode: '2D',  //设置地图模式
        lang: 'zh_cn',  //设置地图语言类型
        zindex: 99999
      });

      // 异步加载地图插件
      AMap.plugin(
        ['AMap.ToolBar','AMap.Geolocation'], () => {//异步加载插件
          // 自动定位插件
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            showbutton: true,
            //控制按钮的显示
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: 'LB'
          })
          thas.map.addControl(geolocation)
          geolocation.getCurrentPosition();
          thas.map.addControl(new AMap.ToolBar()) //初始化工具插件
        });
    },
    initPathSimplifier () {
      AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier) => {
        this.map.clearMap()
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！')
          return
        }
        this.pathSimplifierIns = null
        this.pathSimplifierIns = new PathSimplifier({
          zIndex: 100,
          // autoSetFitView:false,
          map: this.map, // 所属的地图实例

          getPath: (pathData, pathIndex) => {
            return pathData.path
          },
          getHoverTitle: (pathData, pathIndex, pointIndex) => {
            if (pointIndex >= 0) {
              // point
              return pathData.name +',时间:'+pathData.path[pointIndex][2]+ '，点：' + pointIndex + '/' + pathData.path.length
            }

            return pathData.name + '，点数量' + pathData.path.length
          },
          renderOptions: {

            renderAllPointsIfNumberBelow: -1 // 绘制路线节点，如不需要可设置为-1
          }
        })
        window.pathSimplifierIns = this.pathSimplifierIns
        if (window.pathSimplifierIns) {
          // 循环创建轨迹
          for (const item of this.outerlinedata) {
            const firstMarkerContent = '' +
              '<div class="custom-content-marker">' +
              '   <img style="height: 35px;width: 35px" src=' + this.firstPng + '>' +
              '</div>'
            const endMarkerContent = '' +
              '<div class="custom-content-marker">' +
              '   <img style="height: 35px;width: 35px" src=' + this.endPng + '>' +
              '</div>'
            this.map.add(this.createMarker(item.path[0], firstMarkerContent)) // 设置起点生成
            this.map.add(this.createMarker(item.path[item.path.length - 1], endMarkerContent)) // 设置终点生成
            this.pathSimplifierIns.setData(this.outerlinedata) // 设置数据
          }
        }
        const personPosition = '' +
          '<div class="custom-content-marker">' +
          '   <img style="height: 35px;width: 35px" src=' + this.person + '>' +
          '</div>'
        this.marker = this.createMarker(this.outerlinedata[0].path[0], personPosition)
        // 选中事件
        this.pathSimplifierIns.on('selectedPathIndexChanged', (e, info) => {
          info.getPathNavig
        })
        this.map.setFitView()
      })
    },
    /**
     * 创建一个简单的点标记
     * @param position  点位置
     * @param markerContent 点显示内容
     * @returns {Marker|Marker|Marker}
     */
    createMarker (position, markerContent) {
      return new AMap.Marker({
        position: position,
        // 将 html 传给 content
        content: markerContent,
        // 以 icon 的 [center bottom] 为原点
        // eslint-disable-next-line no-undef
        offset: new AMap.Pixel(0, 0),
        anchor: 'bottom-center'
      })
    },
    //  绘制动画
    async playTrajectory () {
      const trajectoryData = this.outerlinedata[0].path
      // 初始化窗体
      this.infoWindow = new AMap.InfoWindow({
        anchor: 'bottom-center',
        isCustom: false, // 使用自定义窗体
        autoMove: true,
        content: '',
        showShadow: true,
        offset: new AMap.Pixel(0, -50),
        zIndex: 1000
      })
      if (this.currentIndex >= trajectoryData.length) {
        // 已经播放完所有轨迹点，结束播放
        return
      }
      var point = trajectoryData[this.currentIndex]
      var position = new AMap.LngLat(point[0], point[1])
      // 设置人员当前位置
      this.marker.setPosition(position)
      this.map.add(this.marker)
      // 显示时间和坐标点信息
      var content = '时间：' + point[2].split(' ')[1] + '<br>经度：' + point[0] + '<br>纬度：' + point[1]
      this.infoWindow.setContent(content)
      this.infoWindow.open(this.map, position)

      this.currentIndex++
      //  设置倍速
      this.setSetTimeOutTime(this.speed)
    },
    //  暂停动画
    stop () {
      clearTimeout(this.timer)
    },
    //  重新播放
    again () {
      this.currentIndex = 0
      this.playTrajectory()
    },
    //  设置倍速
    setSpeed (num) {
      if (num !== 4) {
        num = num * 2
      } else {
        num = 0.5
      }
      this.speed = num
    },
    //  根据速度设置定时时长
    setSetTimeOutTime () {
      clearTimeout(this.timer)
      switch (this.speed) {
        case 1:
          this.timer = setTimeout(this.playTrajectory, 1000)
          break
        case 2:
          this.timer = setTimeout(this.playTrajectory, 500)
          break
        case 4:
          this.timer = setTimeout(this.playTrajectory, 250)
          break
        case 0.5:
          this.timer = setTimeout(this.playTrajectory, 2000)
          break
        default:
          this.timer = setTimeout(this.playTrajectory, 1000)
          break
      }
    },
    clearAllPathSimplifierIns(){
      if (window.pathSimplifierIns) {
        //通过该方法清空上次传入的轨迹
        pathSimplifierIns.setData([]);
      }
      this.map.clearMap()
    },
  },
  watch: {
    // 当外部传给这个组件的props的outerlinedata参数发生变化，就重新绘制轨迹路线
    outerlinedata: {
      immediate: true,
      handler () {
        if (this.map === null) {
          return
        }
        if (this.outerlinedata.length !== 0 && this.outerlinedata !== null && this.outerlinedata !== undefined) {
          this.clearAllPathSimplifierIns()
          this.initPathSimplifier() // 创建路径
        }
      }
    },
    // 当传入的中心地图位置变化
    zoomcenter: {
      immediate: true,
      handler () {
        if (this.zoomcenter) {
          this.setZommAndCenterView(this.zoomcenter.grade, this.zoomcenter.lng, this.zoomcenter.lat)
        }
      }
    },
    //  监听速度变化
    speed: {
      immediate: true,
      handler () {
        this.setSetTimeOutTime()
      }
    }
  },
  ready () {
    this.firstPng = require('../../assets/起点.png')
    this.endPng = require('../../assets/终点.png')
    this.person = require('../../assets/巡检人员.png')
    // 初始化地图
    this.initMap()
    // 初始化轨迹展示
    this.initPathSimplifier()
  }
}
</script>
<style scoped>
.input-item {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-align: center;
  align-items: center;
  width: 100%;
  height: auto;
}

.input-item:last-child {
  margin-bottom: 0;
}

.input-item > select, .input-item > input[type=text], .input-item > input[type=date] {
  position: relative;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  width: 1%;
  margin-bottom: 0;
}
.input-item > select:not(:last-child), .input-item > input[type=text]:not(:last-child), .input-item > input[type=date]:not(:last-child) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0
}
.input-item > select:not(:first-child), .input-item > input[type=text]:not(:first-child), .input-item > input[type=date]:not(:first-child) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0
}
.input-item-prepend {
  margin-right: -1px;
}

.input-item-text, input[type=text], input[type=date], select {
  height: calc(2.2rem + 2px);
}

.input-item-text {
  width: 6rem;
  text-align: justify;
  padding: 0.4rem 0.7rem;
  display: inline-block;
  text-justify: distribute-all-lines;
  /*ie6-8*/
  text-align-last: justify;
  /* ie9*/
  -moz-text-align-last: justify;
  /*ff*/
  -webkit-text-align-last: justify;
  /*chrome 20+*/
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 0;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #495057;
  text-align: center;
  white-space: nowrap;
  background-color: #e9ecef;
  border: 1px solid #ced4da;
  border-radius: .25rem;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
}

.input-item-text input[type=checkbox], .input-item-text input[type=radio] {
  margin-top: 0
}

.input-card {
  /*margin-right: 25%;*/
  z-index: 999;
  right: 1rem;
  position: absolute;
  margin: 0px;
  height: auto;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: .25rem;
  width: auto;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  bottom: 1rem;
  padding: 0.75rem 1.25rem;
}
</style>
