<template>
  <div id="aMapContainer"></div>
</template>

<script>
export default {
  name: 'AMapView',
  data () {
    return {
      icons: {
        startIcon: require('@/assets/img/start.png'),
        currentIcon: require('@/assets/img/sph_car.png'),
        endIcon: require('@/assets/img/end.png')
      }
    }
  },
  props: {
    transport: {
      type: Boolean,
      default: false
    },
    pointList: {
      type: Array,
      default: () => {
        return []
      }
    },
    drivePoint: {
      type: Object,
      default: () => {
        return {
          startPoint: {
            address: '',
            longitude: 0,
            latitude: 0
          },
          endPoint: {
            address: '',
            longitude: 0,
            latitude: 0
          }
        }
      }
    }
  },
  mounted () {
    this.initAMap()
  },
  methods: {
    initAMap() {
      let map = new AMap.Map('aMapContainer', {
        resizeEnable: true,
        zoom: 11,
        zooms: [5, 15]
      })
      if (this.transport) {
        console.log('=======')
        this.drawExelState(map)
      } else {
        console.log('11111111111')
        this.drawPointLine(map)
      }
    },
    /* 根据点数组画线 */
    drawPointLine(map) {
      let _this = this
      let pathParam = []

      _this.pointList.forEach(point => {
        pathParam.push({
          'x': parseFloat(point.longitude),
          'y': parseFloat(point.latitude),
          'sp': parseInt(point.speed),
          'ag': parseInt(point.direction),
          'tm': point.tm
        })
      })
      let pathLength = pathParam.length
      // 由于高德地图对每次数据数量500的限制，需要将数据进行每500分段
      // 按500分组时先计算有多少组,不足500的同样为一组，故向上取整
      let group = Math.ceil(pathLength / 490)
      console.log(group)
      // 定义高德 数据纠偏 对象
      let graspRoad = new AMap.GraspRoad()
      // 定义一个二维数组,开始对每组数据进行操作
      let tdGroup = []
      for (let i = 0; i < group; i++) {
        // 每500一组切割，塞入二维数组中
        tdGroup.push(pathParam.slice(i * 490, (i + 1) * 490))
      }
      console.log(tdGroup)
      // 遍历二维数组，对数组中的每个一维数组进行高德点转换
      tdGroup.forEach((itemArr, tdIndex) => {
        // 用于转换的高德定位临时数组
        let aMapTemp = []
        itemArr.forEach(item => {
          let aMapLngLat = new AMap.LngLat(item.x, item.y)
          aMapTemp.push(aMapLngLat)
        })
        // gps定位数据转换为高德数据
        AMap.convertFrom(aMapTemp, 'gps', function (status, result) {
          if (result.info === 'ok') {
            let aMapLngLat = result.locations
            // 转换成高德数据后，替换源数据
            aMapLngLat.forEach((lngLat, i) => {
              itemArr[i].x = lngLat.lng
              itemArr[i].y = lngLat.lat
            })
            // 绘制起点
            if (tdIndex === 0) {
              let startMarker = new AMap.Marker({
                position: aMapLngLat[0],
                offset: new AMap.Pixel(-15, -38),
                icon: _this.icons.startIcon
              })
              startMarker.setLabel({
                offset: new AMap.Pixel(4, 0), // 设置文本标注偏移量
                content: `<div class='marker'>${_this.drivePoint.startPoint.address}</div>`, // 设置文本标注内容
                direction: 'right' // 设置文本标注方位
              })
              map.add(startMarker)
            }
            // 绘制终点
            if (tdIndex === tdGroup.length - 1) {
              let endMarker = new AMap.Marker({
                position: aMapLngLat[aMapLngLat.length - 1],
                offset: new AMap.Pixel(-15, -38),
                icon: _this.icons.endIcon
              })
              endMarker.setLabel({
                offset: new AMap.Pixel(4, 0), // 设置文本标注偏移量
                content: `<div class='marker'>${_this.drivePoint.endPoint.address}</div>`, // 设置文本标注内容
                direction: 'right' // 设置文本标注方位
              })
              map.add(endMarker)
            }
            // 开始进行对轨迹纠偏
            if (!graspRoad) {
              graspRoad = new AMap.GraspRoad()
            }
            graspRoad.driving(pathParam, function(error, result) {
              if (!error) {
                let path2 = []
                let newPath = result.data.points
                for (let i = 0; i < newPath.length; i += 1) {
                  path2.push([newPath[i].x, newPath[i].y])
                }

                // 绘制线数据到地图上
                let newLine = new AMap.Polyline({
                  path: path2,
                  strokeWeight: 8,
                  strokeOpacity: 0.8,
                  strokeColor: '#0091ea',
                  showDir: true
                })
                map.add(newLine)
                map.setFitView()
              } else {
                console.log(error)
              }
            })
          }
        })
      })
    },
    /* 绘制起点和终点，并绘制车的位置 */
    drawExelState(map) {
      let _this = this
      // 获取Gis点数据的最后一位
      let currentItem = _this.pointList.slice(-1)[0]

      let startPoint = new AMap.LngLat(_this.drivePoint.startPoint.longitude, _this.drivePoint.startPoint.latitude)
      let currentPoint = new AMap.LngLat(currentItem.longitude, currentItem.latitude)
      let endPoint = new AMap.LngLat(_this.drivePoint.endPoint.longitude, _this.drivePoint.endPoint.latitude)
      // 塞入临时数据
      let aMapTemp = [startPoint, currentPoint, endPoint]
      console.log(currentItem)
      // 转换成高德点
      AMap.convertFrom(aMapTemp, 'gps', function (status, result) {
        if (result.info === 'ok') {
          let aMapLngLat = result.locations
          console.log(aMapLngLat)
          // 开始绘制起点
          let startMarker = new AMap.Marker({
            position: aMapLngLat[0],
            icon: _this.icons.startIcon,
            offset: new AMap.Pixel(-15, -38)
          })
          startMarker.setLabel({
            offset: new AMap.Pixel(4, 0), // 设置文本标注偏移量
            content: `<div class='marker'>${_this.drivePoint.startPoint.address}</div>`, // 设置文本标注内容
            direction: 'right' // 设置文本标注方位
          })
          map.add(startMarker)

          // 开始绘制车辆位置
          let currentMarker = new AMap.Marker({
            position: aMapLngLat[1],
            // angle: parseInt(currentItem.direction),
            offset: new AMap.Pixel(-15, -20),
            content: `<div class="markerlabel"><img src="${_this.icons.currentIcon}" style="width: 35px;transform:rotate(${currentItem.direction}deg)"><div class="marker">${currentItem.roadInfo}</div></div>`
            // autoRotation: true,
            // icon: new AMap.Icon({
            //   image: _this.icons.currentIcon,
            //   size: new AMap.Size(52, 52), // 图标大小
            //   imageSize: new AMap.Size(30, 40)
            // })
          })
          // currentMarker.setLabel({
          //   offset: new AMap.Pixel(4, 0), // 设置文本标注偏移量
          //   content: `<div style="transform:rotate(273deg)" class='marker'>${currentItem.roadInfo}</div>`, // 设置文本标注内容
          //   direction: 'right' // 设置文本标注方位
          // })
          map.add(currentMarker)
          // 开始绘制终点
          let endMarker = new AMap.Marker({
            position: aMapLngLat[2],
            icon: _this.icons.endIcon,
            offset: new AMap.Pixel(-15, -38)
          })
          endMarker.setLabel({
            offset: new AMap.Pixel(4, 0), // 设置文本标注偏移量
            content: `<div class='marker'>${_this.drivePoint.endPoint.address}</div>`, // 设置文本标注内容
            direction: 'right' // 设置文本标注方位
          })
          map.add(endMarker)
        }
      })
    }
  }
}
</script>

<style lang="scss" >
  #aMapContainer{
  height: 300px;
  width: 100%;
  }

  .amap-marker-label{
    border: 0;
    background-color: transparent;
  }
  .markerlabel{
    white-space: nowrap;
  }

  .marker{
    border-radius: 2px;
    padding: 3px 4px;
    background-color: #fff;
    width: auto;
    box-shadow: 0 2px 6px 0 rgb(114,124,245 / 50%);
  }
</style>
