<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="startPathNavigators()"/>
          <input  type="button" v-show="pathStatus" class="btn btn-info" value="暂停动画" id="pause" @click="pausePathNavigators()"/>
          <input  type="button" v-show="!pathStatus" class="btn btn-info" value="继续动画" id="resume" @click="resumePathNavigators()"/>
        </div>
        <div class="input-item">
          <input type="button" class="btn btn-info" value="加速动画" id="add" @click="upSpeedPathNavigators()"/>
          <input type="button" class="btn btn-info" value="减速动画" id="des" @click="downSpeedPathNavigators()"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

let firstPng = require('../../assets/firstPng.png')
let endPng = require('../../assets/endPng.png')

export default {
  title: '高德地图轨迹回放',
  props: {
    // 需要绘制的轨迹点的点集
    outerlinedata:{
      default:()=>[],
      type: Array,
    },
    dom : {
      type:String,
      default: ''
    },
    // 设置当前地图的视图位置 格式 {grade:15,lng:经度,lat:纬度}  grade：取值范围1~15 代表不同等级的缩放比例
    zoomcenter: {
      type:Object,
      default: null
    },
    pathnavigatorstyle: {
      type: Object,
      default: {
        width: 50, //图标宽度
        height: 50, // 图标高度
        iconBase64: require('../../assets/巡检人员.png') //图标地址（外链地址或者Base64）
      }
    }
  },
  data () {
    return {
      map: null, //当前地图对象
      pathSimplifierIns: null, // 路径实例
      pathNavigatorList: [], //巡航器组
      pathStatus: true, // 当前巡航器状态
    }
  },
  created(){
    if (this.dom==='') {
      this.dom = "amapIdLOCUS"+Math.round(Math.random()*10)+Math.round(Math.random()*10)
    }
  },
  methods: {

    initAMap () {
      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.path[pointIndex-1][2] +'，点：' + pointIndex + '/' + pathData.path.length;
            }

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

            renderAllPointsIfNumberBelow: 100 //绘制路线节点，如不需要可设置为-1
          }
        });
        window.pathSimplifierIns = this.pathSimplifierIns;
        if (window.pathSimplifierIns) {
          // 循环创建轨迹
          for (let item of this.outerlinedata) {
            let firstMarkerContent = '' +
              '<div class="custom-content-marker">' +
              '   <img style="height: 35px;width: 35px" src='+firstPng+'>' +
              '</div>';
            let endMarkerContent = '' +
              '<div class="custom-content-marker">' +
              '   <img style="height: 35px;width: 35px" src='+endPng+'>' +
              '</div>';
            console.log('起点'+ item.path[0])
            this.map.add(this.createMarker(item.path[0],firstMarkerContent)) // 设置起点生成
            console.log('终点'+ item.path[item.path.length-1])
            this.map.add(this.createMarker(item.path[item.path.length-1],endMarkerContent)) //设置终点生成
            this.pathSimplifierIns.setData(this.outerlinedata)  // 设置数据
          }
          // 结束所有巡航器
          this.destroyAllPathSimplifier();

          // 循环创建巡航器
          for (let i = 0,lent=this.outerlinedata.length; i < lent; i++) {
            if (this.outerlinedata[i].pathnavigatorstyle&&this.outerlinedata[i].pathnavigatorstyle.iconBase64) {
              // 如果每组的数据中带有每个路径的样式，就使用自定义的
              this.createPathNavigators(PathSimplifier,this.pathSimplifierIns,i,this.outerlinedata[i].speed,this.outerlinedata[i].pathnavigatorstyle)
            }else {
              // 如果没有自定义样式，就使用默认样式
              this.createPathNavigators(PathSimplifier,this.pathSimplifierIns,i,this.outerlinedata[i].speed, this.pathnavigatorstyle)
            }
            console.log("创建巡航器"+i)
          }
        }
        // 选中事件
        this.pathSimplifierIns.on('selectedPathIndexChanged', (e, info)=> {
          info.getPathNavig
        });
        this.map.setFitView();
      });
    },
    /**
     * 创建路径巡航器
     * PathSimplifier: PathSimplifier对象
     * pathSimplifierIns: 路径对象
     * itemIndex: 路径下标
     * speed: 路径速度
     * pathStyle: 巡航器样式
     */
    createPathNavigators(PathSimplifier,pathSimplifierIns,itemIndex,speed,pathStyle){
      var navg =  pathSimplifierIns.createPathNavigator(itemIndex, {
        loop: true,
        speed: speed,
        pathNavigatorStyle: {
          width: pathStyle.width,
          height: pathStyle.height,
          content: PathSimplifier.Render.Canvas.getImageContent(pathStyle.iconBase64, onload, onerror),
          strokeStyle: null,
          fillStyle: null
        }
      });
      this.pathNavigatorList.push(navg)
    },
    /**
     * 暂停路径巡航器
     */
    pausePathNavigators() {
      this.pathStatus = false
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {
          pathNavigatorListElement.pause(); // 暂停所有巡航器
        }
      }
    },
    /**
     * 开始所有巡航器
     */
    startPathNavigators(){
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {
          pathNavigatorListElement.start(); // 开启所有巡航器
        }
      }
    },
    /**
     * 继续所有巡航器
     */
    resumePathNavigators() {
      this.pathStatus = true
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {
          pathNavigatorListElement.resume(); //继续所有巡航器
        }
      }
    },
    /*
     * 停止所有巡航器
     */
    stopPathNavigators(){
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {
          pathNavigatorListElement.stop(); //停止所有巡航器
        }
      }
    },
    /**
     * 为所有巡航器设置速度
     */
    setSpeedPathNavigators(speed){
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {

        }
      }
    },
    /**
     * 加速和减速 每次变化10   +10/-10
     */
    upSpeedPathNavigators() {
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {
          pathNavigatorListElement.setSpeed(pathNavigatorListElement.getSpeed()+10);
        }
      }
    },
    downSpeedPathNavigators() {
      if (this.pathNavigatorList.length === this.outerlinedata.length) {
        for (const pathNavigatorListElement of this.pathNavigatorList) {
          if (pathNavigatorListElement.getSpeed()<=10) {
            pathNavigatorListElement.setSpeed(10);
          }else {
            pathNavigatorListElement.setSpeed(pathNavigatorListElement.getSpeed()-10);
          }
        }
      }
    },
    /**
     * 创建一个简单的点标记
     * @param position  点位置
     * @param markerContent 点显示内容
     * @returns {Marker|Marker|Marker}
     */
    createMarker(position,markerContent) {
      return new AMap.Marker({
        position: position,
        // 将 html 传给 content
        content: markerContent,
        // 以 icon 的 [center bottom] 为原点
        offset: new AMap.Pixel(0,0),
        anchor:'bottom-center'

      });
    },
    /**
     * 清楚所有巡航器
     */
    destroyAllPathSimplifier() {
      for (const pathNavigatorListElement of this.pathNavigatorList) {
        console.log("销毁所有巡航器")
        pathNavigatorListElement.destroy(); // 销毁所有巡航器
      }
      this.pathNavigatorList=[] // 清空巡航器组
    },
    /**
     *清楚所有点和已绘制的路径
     */
    clearAllPathSimplifierIns(){
      if (window.pathSimplifierIns) {
        //通过该方法清空上次传入的轨迹
        pathSimplifierIns.setData([]);
      }
      this.map.clearMap()
    },
    /**
     * 清楚所有巡航器和点和已绘制的路径
     */
    clearAllPathSimplifierAndSimplifierIns() {
      this.destroyAllPathSimplifier()
      this.clearAllPathSimplifierIns()
    },
    /**
     * 让地图中心位置视图转移 显示在某个经纬度
     *_grade:等级1~15  缩放等级 全国~街道
     */
    setZommAndCenterView (_grade,_lng,_lat) {
      this.map.setZoomAndCenter(_grade,[_lng, _lat])
      this.map.getCenter();
    }
  },
  //当外部传给这个组件的props的outerlinedata参数发生变化，就重新绘制轨迹路线
  watch: {
    outerlinedata:function () {
      this.clearAllPathSimplifierAndSimplifierIns()//当轨迹变化清楚之前的所有轨迹 重新渲染
      if (this.outerlinedata.length!==0 && this.outerlinedata !== null && this.outerlinedata !== undefined) {
        this.initPathSimplifier() // 创建路径
      }else {
        this.clearAllPathSimplifierAndSimplifierIns()
      }
    },
    // 当传入的中心地图位置变化
    zoomcenter: function () {
      if (this.zoomcenter) {
        this.setZommAndCenterView(this.zoomcenter.grade,this.zoomcenter.lng,this.zoomcenter.lat)
      }
    }
  },
  ready () {
    // 初始化地图
    this.initAMap();
    // 初始化轨迹展示
    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>
