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

<script>
import { lunzApi, appKey, key, carList, styleJson } 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,//昨日轨迹
      viewData: [],//点聚合坐标集合
      // endPointMarker:null,//轨迹终点标记
    }
  },
  beforeDestroy() {
    clearInterval(this.setInterval);
    console.log('销毁');
  },
  beforeCreate() {
    clearInterval(this.setInterval);
  },
  created() {
  },
  mounted() {
    this.initMap();
    window.addEventListener('resize', () => {
      if (this.baiduMap) {
        this.backMap();
      }
    });
  },
  methods: {
    //回到原中心点
    backMap() {
      var point = new BMap.Point(118.880278, 35.649947);
      this.baiduMap.centerAndZoom(point, 11);
    },
    initMap() {
      var point = new BMap.Point(118.880278, 35.649947);
      if (this.baiduMap) {
        this.baiduMap.centerAndZoom(point, 11);
      }
      else {
        this.baiduMap = new BMap.Map('container');
        this.baiduMap.centerAndZoom(point, 11);
        this.baiduMap.enableScrollWheelZoom(true);
        this.baiduMap.setMapStyle({ style: 'midnight' });
        // this.baiduMap.setMapStyleV2({
        //   styleJson: styleJson
        // })
        // alert('自定义样式')
        // this.view = new mapvgl.View({
        //   map: this.baiduMap
        // });
        var bdary = new BMap.Boundary();
        bdary.get("日照市莒县", rs => {
          var count = rs.boundaries.length;
          for (var i = 0; i < count; i++) {
            var xyArr = rs.boundaries[i].split(';');
            var ptArr = [];
            for (var j = 0; j < xyArr.length; j++) {
              var tmp = xyArr[j].split(',');
              var pt = new BMap.Point(tmp[0], tmp[1]);
              ptArr.push(pt);
            }
            // var mapmask = new BMap.MapMask(ptArr, {
            //   isBuildingMask: true,
            //   isPoiMask: true,
            //   isMapMask: true,
            //   showRegion: 'inside',
            //   topFillColor: '#5679ea',
            //   topFillOpacity: 0.5,
            //   sideFillColor: '#5679ea',
            //   sideFillOpacity: 0.9
            // });
            // this.baiduMap.addOverlay(mapmask);
            var border = new BMap.Polyline(ptArr, {
              strokeColor: '#0e94eb',
              strokeWeight: 3,
              strokeOpacity: 1
            });
            this.baiduMap.addOverlay(border);
            // var ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: "#0e94eb", fillColor: '', fillOpacity: 0, }); //建立多边形覆盖物
            // this.baiduMap.addOverlay(ply);  //添加覆盖物
          }
        })
        this.baiduMap.removeEventListener('tilesloaded', this.handleEvent);
        this.baiduMap.addEventListener('tilesloaded', this.handleEvent);
      }

    },
    handleEvent() {
      console.log('addEventListener');
      this.carList.map((item, index) => {
        this.markList.map(mark => {
          this.baiduMap.removeOverlay(mark);
        })
        this.markList = [];
        this.queryLunz(item.deviceId, item.key, item.cardNo, index);
      })
      clearInterval(this.setInterval);
      let timer = 0;
      this.setInterval = setInterval(() => {
        console.log(timer++)
        // this.view.removeAllLayers();
        this.markList.map(mark => {
          this.baiduMap.removeOverlay(mark);
        })
        this.markList = [];
        // this.viewData = [];
        this.carList.map((item, index) => {
          this.queryLunz(item.deviceId, item.key, item.cardNo, index);

        })
      }, 20 * 1000)
    },
    //单个设备定位聚焦放大
    queryDingwei(deviceId) {
      lunzApi.getCurrentDeviceInfoByIMEI(this.appKey, deviceId).then(res => {
        let lng = res.Data.BaiduLng;
        let lat = res.Data.BaiduLat;
        let pt = new BMap.Point(lng, lat);
        this.baiduMap.centerAndZoom(pt, 18);
      })
    },
    //查询定位
    queryLunz(deviceId, key, carNo, index) {
      // lunzApi.getCarUserSimpleByImei(this.appKey, deviceId).then(res1 => {
      // let carInfo = res1.Data;
      lunzApi.getCurrentDeviceInfoByIMEI(this.appKey, deviceId).then(res => {
        // 创建小车图标
        var myIcon = new BMap.Icon(require("@/assets/images/car.png"), new BMap.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 BMap.Point(lng, lat);
          var marker = new BMap.Marker(pt, {
            icon: myIcon
          });
          // 将标注添加到地图
          this.baiduMap.addOverlay(marker);
          // this.viewData.push({
          //   geometry: {
          //     type: 'Point',
          //     coordinates: [lng, lat]
          //   },
          //   objdata: { carNo: carNo, deviceId: key, resData: res.Data, res2Data: res2.Data }
          // })
          this.markList.push(marker);
          let sContent = `<div style="font-size:0.14rem;line-height:0.22rem;padding:0 0.05rem 0 0.15rem;">
                            <div id="close_${deviceId}" style="display:inline-block;color:#fff;font-size:0.16rem;font-weight:bold;width:0.18rem;line-height:0.18rem;cursor:pointer;text-align:center;float:right;">x</div>
                            <div style="display:flex;align-items:center;margin-bottom:0.15rem;font-style: italic;font-size:0.2rem;font-family: FZSK;">
                              <div style="color: #ffffff;margin-right:0.1rem;">${carNo}</div>
                              <div style="display:inline-block;color:${res.Data.SbcStatus == 3 ? "#ffffff" : "#062766"};background:${res.Data.SbcStatus == 3 ? "#1dd58e !important" : "#9ab3c6 !important"};width:0.65rem;text-align:center;border-radius:100px;font-size:0.16rem;padding:0.04rem 0;">${this.locationStatus[res.Data.SbcStatus]}</div>
                              <div style="margin-left:0.35rem;color: #fff;font-style: italic;font-size:0.2rem;margin-right:0.15rem;">${res.Data.spd}km/h</div>  
                            </div>
                            <div style="display:flex;margin-bottom:0.1rem;max-width:3.5rem;"><div style="color: #ffffff;">设备位置：</div><div style="color: #ffffff;flex:1;">${res2.Data}</div></div>
                            <div style="display:flex;"><div style="color: #ffffff;">最后定位时间：</div><div style="color: #ffffff;flex:1;">${res.Data.GPSTimeStamp.replace("T", " ")}</div></div>
                            <div style="text-align:center;margin:0.12rem 0 0;max-width:3.25rem;"> <div style="display: inline-block;width:0.88rem;border-radius: 100px;text-align:center;color: #1b2f57;font-style: italic;font-family: FZSK;cursor: pointer;background:#facd89 !important;font-size:0.16rem;font-weight:bold;padding:0.04rem 0;" id="btnPath_${deviceId}">行车轨迹</div></div>
                        </div>`;
          let infoWindow = new BMap.InfoWindow(sContent, { width: 367, height: 220 });
          // marker添加点击事件
          infoWindow.addEventListener('open', () => {
            document.getElementById('btnPath_' + deviceId).addEventListener('click', () => {
              this.queryPath(deviceId)
            })
            document.getElementById('close_' + deviceId).addEventListener('click', () => {
              this.baiduMap.closeInfoWindow();
            })
          });
          marker.addEventListener('click', () => {
            this.openInfo(infoWindow, pt);
          });
        })

      })
      // })
    },
    //信息窗口
    openWindow(sContent, pt, DeviceNumber) {
      let infoWindow = new BMap.InfoWindow(sContent);
      // marker添加点击事件
      infoWindow.addEventListener('open', () => {
        document.getElementById('btnPath_' + DeviceNumber).addEventListener('click', () => {
          this.queryPath(DeviceNumber)
        })
      });
      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
      }
      param = {
        "IMEI": deviceId,
        "StartDateTime": dateFormat(new Date(yesterDay2), 'yyyy-MM-dd'),
        "EndDateTime": dateFormat(new Date(yesterDay1), 'yyyy-MM-dd'),
        "MaxValues": 500,
        "LocType": 1
      }
      lunzApi.getLocationsByImei2(this.appKey, param).then(res => {
        if (res.Data == null) {
          this.$message({
            message: '未查询到今日行车轨迹',
            type: 'warning'
          });
          return;
        }
        let point = [];
        res.Data.Locations.map(item => {
          point.push(new BMap.Point(item.Lng, item.Lat));
        });
        if (this.polyline) {
          this.baiduMap.removeOverlay(this.polyline);
          this.polyline = null;
        }
        this.polyline = new BMap.Polyline(point, { strokeColor: '#ffe954', strokeWeight: 4, strokeOpacity: 1, })
        this.baiduMap.addOverlay(this.polyline);
        //终点标注maker
        if (this.endPointMarker) {
          this.baiduMap.removeOverlay(this.endPointMarker);
          this.endPointMarker = null;
        }
        // var myIcon = new BMap.Icon(require("@/assets/images/end_point_icon.png"), new BMap.Size(37, 44));
        // this.endPointMarker = new BMap.Marker(point[point.length-1], {
        //     icon: myIcon
        // });
        // console.log('最后一个坐标',point[point.length-1])
        // this.baiduMap.addOverlay(this.endPointMarker);
        this.baiduMap.centerAndZoom(point[0], 15);
        this.baiduMap.closeInfoWindow();
        // this.polyline = new BMap.Polyline(point, {
        //   strokeColor: '#F5533D',
        //   strokeWeight: 5,
        //   strokeOpacity: 1,
        // });
        // let trackAni = new BMapLib.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>