<template>
  <div class="map_warp">
    <div id="container" style="width:100%;height:100%"></div>
  </div>
</template>

<script>
import { lunzApi, appKey, key, carList } from "@/api/data";
import { dateFormat } from "@/util/date";
export default {
  data() {
    return {
      appKey: appKey,
      key: key,
      setInterval: null,
      baiduMap: null,//百度实例
      locationModel: { 0: 'GPS定位', 1: '基站定位', 2: 'Wi-Fi定位', 3: '北斗定位', 4: 'GPS/北斗混合定位' },
      locationStatus: { 0: '未启用', 1: '离线', 2: '静止', 3: '行驶中' },
      locationAcc: { 0: '关闭', 1: '开启' },
      carList: carList,//车辆设备
      markList: [],//标注点记录
      polyline: null,//昨日轨迹
    }
  },
  beforeDestroy() {
    if (this.setInterval) {
      clearInterval(this.setInterval);
    }
  },
  beforeCreate() {
    if (this.setInterval) {
      clearInterval(this.setInterval);
    }
  },
  mounted() {
    this.initMap();
    window.addEventListener('resize', () => {
      if (this.setInterval) {
        clearInterval(this.setInterval);
      }
      this.initMap();
    });
  },
  methods: {
    initMap() {
      this.baiduMap = new BMapGL.Map('container');
      var point = new BMapGL.Point(118.880278, 35.649947);
      this.baiduMap.centerAndZoom(point, 11);
      this.baiduMap.enableScrollWheelZoom(true);
      var bdary = new BMapGL.Boundary();
      bdary.get("日照市莒县", rs => {
        var pointArray = [];
        var count = rs.boundaries.length;
        for (var i = 0; i < count; i++) {
          var ply = new BMapGL.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: "#0e94eb", fillColor: '', fillOpacity: 0, }); //建立多边形覆盖物
          this.baiduMap.addOverlay(ply);  //添加覆盖物
          pointArray = pointArray.concat(ply.getPath());
        }
      })
      this.carList.map((item, index) => {
        this.markList.map(mark => {
          this.baiduMap.removeOverlay(mark);
        })
        this.markList = [];
        this.queryLunz(item.deviceId, item.key);
        this.setInterval = setInterval(() => {
          this.markList.map(mark => {
            this.baiduMap.removeOverlay(mark);
          })
          this.markList = [];
          this.queryLunz(item.deviceId, item.key);
        }, 20 * 1000)
      })
    },
    //查询定位
    queryLunz(deviceId, key) {
      lunzApi.getCarUserSimpleByImei(this.appKey, deviceId).then(res1 => {
        let carInfo = res1.Data;
        lunzApi.getCurrentDeviceInfoByIMEI(this.appKey, deviceId).then(res => {
          // 创建小车图标
          var myIcon = new BMapGL.Icon(require("@/assets/images/car.png"), new BMapGL.Size(25, 25));
          lunzApi.getBaiduNear(this.appKey, res.Data.BaiduLat, res.Data.BaiduLng).then(res2 => {
            // 创建Marker标注，使用小车图标
            let lng = res.Data.BaiduLng;
            let lat = res.Data.BaiduLat;
            let pt = new BMapGL.Point(lng, lat);
            var marker = new BMapGL.Marker(pt, {
              icon: myIcon
            });
            // 将标注添加到地图
            this.baiduMap.addOverlay(marker);
            this.markList.push(marker);
            let sContent = `<div style="padding:0 10px 10px;font-size:14px;line-height:22px;">
                            <div>车牌号：${carInfo.PlateNumber}</div>
                            <div>设备位置：${res2.Data}</div>
                            <div>最后定位时间：${res.Data.GPSTimeStamp.replace("T", " ")}</div>
                            <div>状态：${this.locationStatus[res.Data.SbcStatus]}</div>
                            <div>时速：${res.Data.spd}km/h</div>
                            <div style="display: inline-block;border: 1px solid #eee;border-radius: 3px;padding: 3px 8px;color: #0e94eb;cursor: pointer;" id="btnPath_${carInfo.DeviceNumber}">行车轨迹</div>
                        </div>`;
            let infoWindow = new BMapGL.InfoWindow(sContent);
            // marker添加点击事件
            infoWindow.addEventListener('open', () => {
              document.getElementById('btnPath_' + carInfo.DeviceNumber).addEventListener('click', () => {
                this.queryPath(carInfo.DeviceNumber)
              })
            });
            marker.addEventListener('click', () => {
              this.openInfo(infoWindow, pt);
            });
          })

        })
      })
    },
    //昨日轨迹
    queryPath(deviceId) {
      let now = new Date();
      let yesterDay1 = now.setDate(now.getDate() - 1);
      let yesterDay2 = now.setDate(now.getDate() - 1);
      let param = {
        "Imei": deviceId,
        "StartTime": dateFormat(new Date(yesterDay2), 'yyyy-MM-dd'),
        "EndTime": dateFormat(new Date(yesterDay1), 'yyyy-MM-dd'),
        "MaxValue": 500
      }
      lunzApi.getLocationsByImei(this.key, param).then(res => {
        let point = [];
        res.Data.map(item => {
          point.push(new BMapGL.Point(item.Lng, item.Lat));
        });
        if (this.polyline) {
          this.baiduMap.removeOverlay(this.polyline);
          this.polyline = null;
        }
        this.polyline = new BMapGL.Polyline(point, { strokeColor: '#F5533D', strokeWeight: 5, strokeOpacity: 1, })
        this.baiduMap.addOverlay(this.polyline);
        // this.polyline = new BMapGL.Polyline(point, {
        //   strokeColor: '#F5533D',
        //   strokeWeight: 5,
        //   strokeOpacity: 1,
        // });
        // let trackAni = new BMapGLLib.TrackAnimation(this.baiduMap, this.polyline, {
        //   overallView: true,
        //   tilt: 30,
        //   duration: 20000,
        //   delay: 300
        // });
        // trackAni.start();
      }, error => {
        this.$message({
          message: '未查询到今日行车轨迹',
          type: 'warning'
        });
      })
    },
    openInfo(infoWindow, pt) {
      this.baiduMap.openInfoWindow(infoWindow, pt);
    },
  },
}
</script>

<style lang="scss" scoped>
.map_warp {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>