<template>
  
  <div>
        <yd-navbar :title="imei">
            <router-link :to="'/route_search/' + imei" slot="left">
                <yd-navbar-back-icon></yd-navbar-back-icon>
            </router-link>
            <router-link to="/location" slot="right">
                <yd-icon name="home-outline" size=".4rem" color="#111"></yd-icon>
            </router-link>
        </yd-navbar>
 
    <div id="route-map">  </div>

    <div class="type-bar">
      <div class="change-button">
        <span class="icon-base" :class="{buttonActive: gpsActive}" @click="activeGps">
          <yd-icon name="weixing-copy" size=".4rem"  custom></yd-icon>
        </span>
        <span class="icon-base" :class="{buttonActive: stationActive}" @click="activeStation">
          <yd-icon name="jizhanxinhao" size=".5rem" custom></yd-icon>
        </span>
      </div>
    </div>

    <div class="progress-bar">
      <div class="point-info">
        <span>{{currentPt ? currentPt.OnlineTime : '--'}}</span>
        <span v-if="currentPt && currentPt.SignalType" style="margin-left:5px"><van-tag plain :type="(currentPt.SignalType == 'GPS' ? 'primary' : 'warning')">{{currentPt.SignalType}}</van-tag></span>
        <span style="margin-left:15px">{{currentPt ? (currentPt.SignalType == "WiFi" ? currentPt.WifiAddress : currentPt.gpsAddress) : '--'}}</span>
      </div>
      <div class="bar-contrl">
          <yd-icon name="play" size=".4rem" color="#2196f3" style="margin-right:0.2rem" v-if="!routePlaying" @click.native="naviPlaystart"></yd-icon>
          <yd-icon name="pause" size=".4rem" color="#2196f3" style="margin-right:0.2rem" custom v-else @click.native="naviPlayPaulse"></yd-icon>
          <vue-slider
          v-model="value"
          @change="handlePoint"
          :max="(routeList.length - 1)"
          :min="0"
          tooltip="none"
          style="width:calc(100% - 20px - 1rem)"
          
          >
          
          
          </vue-slider>

        <yd-icon :name="speedIcon" size=".4rem" color="#2196f3" style="margin-left:0.2rem" @click.native="changgeSpeed" custom></yd-icon>
      </div>


    </div>



  <van-overlay :show="loadingMask" style="display: flex;justify-content: center;align-items: center;z-index:99">
    <div>
      <van-loading size="24px" type="spinner">地图加载中...</van-loading>
    </div>
  </van-overlay>


  </div>


</template>

<script>
import VueSlider from 'vue-slider-component'
import 'vant/lib/index.css';
import 'vue-slider-component/theme/default.css'

import Vue from 'vue';
import { Overlay ,Loading, Tag} from 'vant';

Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Tag);




export default { 
    components: {
      VueSlider
    },
    data: function () {
      return {
        value: 0,
        imei: '',
        fenceOverlay: null,
        date: '',
        map: null,
        gpsActive: true,
        stationActive: false,
        routePlaying: false,
        currentPointIndex: 0,
        speedLevel: 1,
        speedIcon: 'beisu1',
        loadingMask: true,
        loadinTimer: null,
        pathList: [],
        routeList: [],
        currentPt: null
      }
    },

    mounted(){
      let that = this;
      this.imei = this.$route.params.imei;
      let PathClass =  new Promise((resolve, reject) => {
          AMapUI.load(['ui/misc/PathSimplifier'], function(PathSimplifier) {

            if (!PathSimplifier.supportCanvas) {
                alert('当前环境不支持 Canvas！');
                reject(false)
            }

            resolve(PathSimplifier)



            //启动页面
            // initPage(PathSimplifier);
            
          });
      });

      PathClass.then((result) => {
        that.PathSimplifier = result;
        that.initMap()
      }).catch((err) => {
        console.log('init err', err)
      });

      
      
    },


    methods: {
      handlePoint(val){
        let num = parseInt((val / 100) * this.pathList.length);
        console.log(num, 'num')
        let decimal = String((val / 100) * this.pathList.length).split('.')[1]||0
        console.log(decimal, 'decimal')
        this.navgtr.moveToPoint(num, Number('0.'+decimal));
        this.currentPt = this.routeList[num]
        this.pathSimplifierIns.renderLater();
      },
      changgeSpeed(){
        let that = this;
        let speedLevel = that.speedLevel;
        if(parseInt( speedLevel / 16 ) == 1){
          speedLevel = 1;
          that.navgtr.setSpeed(speedLevel * 10000)
        }else{
          speedLevel *= 2;
          that.navgtr.setSpeed(speedLevel * 10000)
        }
        that.speedLevel = speedLevel
        that.speedIcon = 'beisu' + speedLevel
        console.log(speedLevel)


      },


        requestRoute(studentId){
            let that = this;
            let startTime = this.$route.params.startTime;
            let endTime =this.$route.params.endTime;
            if(!startTime ||  !endTime){
                this.$dialog.toast({
                    mes: '请返回选择起止时间',
                    timeout: 3000
                });
                return;
            }

            this.$http.get("/getSationRoutes&startTime=" + startTime + "&endTime=" + endTime + "&studentId=" + studentId).then(res => {
                    
                    if(!res.data.success || res.data.data.length == 0){
                        that.routeList = [];
                        that.pathList = [];
                        return;
                    }
                    
                    let resList=  res.data.data;
                    let pathList = [];
                    resList.forEach( (item, index) => {
                      pathList.push(
                        {
                          name: index,
                          lngLat: [item.lng, item.lat],
                        }
                      );
                    });
                    that.pathList = pathList;
                    that.routeList = resList;

                    this.initRoute();



                    
                })
                .catch(res => {
                    console.log(res);
                });     
        },

        requestGpsRoute(){
            let that = this;
            let startTime = this.$route.params.startTime;
            let endTime =this.$route.params.endTime;

            if(!startTime ||  !endTime){
                this.$dialog.toast({
                    mes: '请返回选择起止时间',
                    timeout: 3000
                });
                that.loadingMask = false;
                return;
            }

            this.$http.get("/getGpsRoutes&startTime=" + startTime + "&endTime=" + endTime + "&imei=" + this.imei).then(res => {
                    
                    if(!res.data.success || res.data.data.length == 0){
                        that.routeList = [];
                        that.pathList = [];
                        that.$dialog.toast({
                            mes: '选择时间段无轨迹',
                            timeout: 3000
                        });
                        that.loadingMask = false;
                        return;
                    }
                    
                    let resList=  res.data.data;
                    let pathList = [];
                    resList.forEach( (item, index) => {
                      pathList.push(
                        {
                          name: index,
                          lngLat: [item.lng, item.lat],
                        }
                      );
                    });
                    that.pathList = pathList;
                    that.routeList = resList;

                    that.currentPt = resList[0]

                    resList.forEach( (item, index) => {
                      if(item.SignalType === 'GPS'){
                        that.geocoder.getAddress([item.lng, item.lat], function(status, result) {
                          if (status === 'complete' && result.info === 'OK') {
                              // result为对应的地理位置详细信息
                            that.routeList[index].gpsAddress =  result.regeocode.formattedAddress
                          }
                        })
                      }
                    });

                    this.initRoute();

                    that.loadingMask = false;


                    
                })
                .catch(res => {
                  
                    console.log(res);
                    that.loadingMask = false;
                });     
        },


      activeStation(){
        if(this.stationActive){
          return;
        }
        this.stationActive = true;
        this.gpsActive = false;

        this.$dialog.toast({
            mes: '切换至基站轨迹',
            timeout: 3000
        });
        this.requestRoute()
      },
      activeGps(){
        if(this.gpsActive){
          return;
        }

        this.stationActive = false;
        this.gpsActive = true;
        this.$dialog.toast({
            mes: '切换至GPS轨迹',
            timeout: 3000
        });
        this.requestGpsRoute()
      },
      initMap(){
          let that = this;

          var map = new AMap.Map('route-map', {
              zoom:4,//级别
              // center: [116.403322, 39.920255],//中心点坐标
              // viewMode:'3D',//使用3D视图
              mapStyle: 'amap://styles/light',
              showBuildingBlock: true
          });
          AMap.plugin([
              'AMap.ToolBar',
              'AMap.Scale',
              'AMap.HawkEye',
              // 'AMap.MapType',
              'AMap.Geocoder',
          ], function(){
              // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
              map.addControl(new AMap.ToolBar({position: 'LT'}));

              // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
              map.addControl(new AMap.Scale({position: 'LB'}));
          
              // // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
              // map.addControl(new AMap.MapType());

              that.geocoder = new AMap.Geocoder({})
          });



          this.map = map;



          this.map.on('complete', function(){
            that.requestGpsRoute()
          })


          

          

          
          
      },

      initRoute(){
        let that = this;

        var pathSimplifierIns = new that.PathSimplifier({
            zIndex: 100,
            //autoSetFitView:false,
            map: that.map, //所属的地图实例

            getPath: function(pathData, pathIndex) {
                let points = pathData.routeList,
                 lnglatList = [];


                for (var i = 0, len = points.length; i < len; i++) {
                    lnglatList.push(points[i].lngLat);
                }

                return lnglatList;

            },
            getHoverTitle: function(pathData, pathIndex, pointIndex) {

                if (pointIndex >= 0) {
                    //point 
                    return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
                }

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

                renderAllPointsIfNumberBelow: that.routeList.length //绘制路线节点，如不需要可设置为-1
            }
        });

        that.pathSimplifierIns = pathSimplifierIns;

        //设置数据
        that.pathSimplifierIns.setData([{
            name: '轨迹',
            routeList: that.pathList
        }]);

        //对第一条线路（即索引 0）创建一个巡航器
        that.navgtr = that.pathSimplifierIns.createPathNavigator(0, {
            loop: false, //循环播放
            speed: 2500 * that.speedLevel //巡航速度，单位千米/小时
        });



        that.navgtr.on('move', function(e){
          let idx = e.target.cursor.idx, tail = e.target.cursor.tail, progressBarIndex;
          
          // progressBarIndex = parseInt(idx / that.pathList.length * 100) + parseInt(tail * 10); 
          
          that.value = idx
          console.log(idx, 'progressBarIndex')
          that.currentPt = that.routeList[idx]

        })
        that.navgtr.on('stop', function(e){
          console.log('stop')

        })
        that.navgtr.on('pause', function(e){
          console.log('pause')
          that.routePlaying = false;
        })

        that.navgtr.on('start', function(e){
          console.log(e)
        })

        // that.navgtr.start();


      },
      naviPlaystart(){
        let that = this;
        that.routePlaying = true;
        let idx = that.navgtr.getCursor().idx;
        if(!idx){
          that.navgtr.start()
          return
        }
        console.log(idx)
        if(idx == that.pathList.length -1){
          that.value = 0;
          that.navgtr.start(0)
        }
        
        




        that.navgtr.resume()
      },
      naviPlayPaulse(){
        let that = this;
        that.routePlaying = false;
        that.navgtr.pause()
      }


    }
}
</script>
<style>
.amap-ui-pathsimplifier-container canvas{
  left:0;
  position: absolute;
}
</style>

<style scoped>

#route-map{
  height: calc(100vh - 1rem);
  /* width: 100%; */
   -webkit-transform: translateZ(0);
   -moz-transform: translateZ(0);
   -ms-transform: translateZ(0);
   -o-transform: translateZ(0);
   transform: translateZ(0);
}

.progress-bar{
  position: absolute;
  bottom: 1rem;
  width: 100%;
  opacity: 0.85;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) */
  
}

.type-bar{
  position: absolute;
    right: 10px;
    z-index: 99;
    top: 50%;
}
.change-button{
  display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.icon-base{
  width: 0.6rem;
  height: 0.6rem;
  margin-bottom: 0.1rem;
  background: white;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  color: darkgray;
}
.buttonActive{
  color: white;
  background: #2196f3;
}
.bar-contrl{
    display: flex;
    justify-content: center;
    align-items: center;
    background: white;
    border-radius: 0 0 10px 10px;
    margin: 0 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
}
.point-info{
    margin: 0 10px;
    background: white;
    border-radius: 10px 10px 0 0;
    padding: 10px;
}
.bottom-panel{
  width: 100%;
  height: 150px;
  background: white;
  border-top-left-radius:1em;
  border-top-right-radius:1em;
  padding: 5px 5px 5px 5px;
  position: fixed;
  bottom: 0;

}
.bottom-panel-first-row{
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.date-picker-icon{
  width: 18px;
  height: 18px;
  margin-right: 5px;
}
.refresh-button-icon{
  width: 18px;
  height: 18px;
  margin-right: 5px;
}
.delimit-line{
  width: 100%;
  height: 1px;
  background: #ddd;
  margin-right: 10px;
}
.bottom-panel-right{
  display:flex;
  margin-right:10px;
  align-items: center;
}
.font-refresh{
  font-weight: bold;
  background: linear-gradient(#58cfff, #749fff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-size: 16px;
}

.bottom-panel-button-area{
  height: 100px;
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.button-area-next-last{
  width: 32px;
  height: 32px;
}
.button-area-play-pause{
  width: 64px;
  height: 64px;
}
.font-margin{
  margin-left: 5px;
}
</style>