<template>
  <div class="container">
    <SiteSearch :siteList="siteList" @node-click="onNodeClick" />
    <div id="mapDiv" class="container-map"></div>
    <div id="mapMarker" class="rect-marker-dialog">
      <DialogMarkerContainer ref="de">
        <SiteDetail :markerSiteData="markerSiteData" />
      </DialogMarkerContainer>
    </div>
  </div>
</template>

<script>
import { DefinedMarkerInfoWindow } from './utils';
import SiteDetail from './components/SiteDetail.vue';
import SiteSearch from './components/SiteSearch.vue';
import { getSiteList } from '@/api/monitor';
import DialogMarkerContainer from '@/views/server/monitor/components/DialogMarkerContainer.vue';
export default {
  name: 'Monitor',
  components: {
    SiteDetail,
    DialogMarkerContainer,
    SiteSearch,
  },
  data() {
    return {
      overlay: null,
      map: null,
      markerSiteData: {},
      siteDetailOpenPoint: null,
      markerContainRect: {},
      siteList: [],
      deviceInfo: [],
    };
  },
  async mounted() {
    const siteList = await getSiteList();
    this.siteList = siteList;
    const tmpSiteList = this.flatSiteList();
    const tmp = tmpSiteList.find(s => s.id === 1) || tmpSiteList[0];
    const initLngLat = {
      longitude: tmp?.longitude || 116.40769,
      latitude: tmp?.latitude || 39.89945,
      zoom: 12,
    };

    this.initMap(initLngLat);
    this.initMarker(tmpSiteList);
  },
  methods: {
    async initMap(initLngLat) {
      console.log('map');
      this.map = new T.Map('mapDiv');
      this.map.centerAndZoom(
        new T.LngLat(initLngLat.longitude, initLngLat.latitude),
        initLngLat.zoom
      );

      // http://lbs.tianditu.gov.cn/api/js4.0/class.html
      const ctrl = new T.Control.MapType([
        {
          title: 'map',
          icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/vector.png',
          layer: window.TMAP_NORMAL_MAP,
        },
        {
          title: 'satellite',
          icon: ' http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellite.png',
          layer: window.TMAP_SATELLITE_MAP,
        },
      ]);
      this.map.addControl(ctrl);
      this.map.setMapType(window.TMAP_NORMAL_MAP);
    },
    flatSiteList() {
      let tmpSiteList = [];
      this.siteList.forEach(mo => {
        mo.children.forEach(co => {
          tmpSiteList = tmpSiteList.concat(co.children);
        });
      });
      return tmpSiteList;
    },

    initMarker(siteList) {
      const markerPointList = siteList.map(point => {
        var iconUrl =
          point.status == 1
            ? require('@/assets/position.gif')
            : require('@/assets/stop.gif');
        const marker = new T.Marker(
          new T.LngLat(point.longitude, point.latitude),
          {
            icon: new T.Icon({
              iconUrl,
              id: point.id,
              iconSize: new T.Point(50, 50),
              iconAnchor: new T.Point(0, 0),
            }),
            title: point.name,
          }
        );
        const infoWin = new DefinedMarkerInfoWindow(`a${point.id}`, {
          placement: 'rightBottom',
        });

        infoWin.on('open', () => {
          this.siteDetailOpenPoint = point;
          this.resizeSiteDetailPosition();
        });

        infoWin.on('close', () => {
          this.$refs?.de?.setPosition?.({
            top: -999,
            left: -999,
          });
          this.siteDetailOpenPoint = null;
        });
        const tmp = { marker, ...point, lng: point.longitude, lat: point.lat };
        marker.on('click', e => {
          this.markerSiteData = tmp;
          this.$nextTick(() => {
            marker.openInfoWindow(infoWin);
          });
        });

        return tmp;
      });

      const markersCluster = new T.MarkerClusterer(this.map, {
        markers: markerPointList.map(s => s.marker),
        girdSize: 100,
      });

      markersCluster.setMaxZoom(18);
      markersCluster.setStyles([
        {
          url: require('../../../assets/position.gif'),
          size: [60, 60],
          offset: new T.Point(0, 0), //显示图片的偏移量
          textColor: '#fff', //显示数字的颜色
          textSize: 10, //显示文字的大小
          range: [0, 5],
        },
        {
          url: require('../../../assets/folder.png'),
          size: [60, 60],
          offset: new T.Point(0, 0), //显示图片的偏移量
          textColor: '#fff', //显示数字的颜色
          textSize: 10, //显示文字的大小
          range: [5, 100000],
        },
      ]);

      this.markerContainRect = document
        .querySelector('#mapMarker')
        ?.getBoundingClientRect() ?? { top: 0, left: 0 };

      this.onMapListener();
    },

    onMapListener() {
      if (this.map) {
        this.map.on('resize', this.resizeSiteDetailPosition);
        this.map.on('dragend', this.resizeSiteDetailPosition);
        this.map.on('zoomend', this.resizeSiteDetailPosition);
        this.map.on('dragstart', this.resizeSiteDetailPosition);
        this.map.on('drag', this.resizeSiteDetailPosition);

        this.map.on('clearoverlays', () => {
          this.$refs?.de?.setPosition?.({
            top: -999,
            left: -999,
          });
          this.siteDetailOpenPoint = null;
        });
      }
    },

    resizeSiteDetailPosition() {
      if (this.siteDetailOpenPoint) {
        this.$nextTick(() => {
          const abc = document.querySelector(
            `#a${this.siteDetailOpenPoint.id}`
          );
          const {
            top = 0,
            left = 0,
            width = 60,
          } = abc?.getBoundingClientRect?.() ?? {};
          const { top: t = 0, left: l = 0 } = this.markerContainRect;
          this.$refs?.de?.setPosition?.({
            top: top - t,
            left: left + width - l,
          });
        });
      }
    },

    onNodeClick(node) {
      this.map.centerAndZoom(new T.LngLat(node.longitude, node.latitude), 18);
      console.log(node, 'node-click______-');
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  height: calc($base-app-main-height - 32px);
  padding: 16px;

  &-map {
    width: 100%;
    height: 100%;

    ::v-deep {
      .tdt-infowindow-tip-container {
        display: none;
      }

      .tdt-infowindow-content {
        padding: 0;
        margin: 0;
        background: none;
      }

      .tdt-infowindow-content-wrapper {
        background: none;
        box-shadow: none;
      }
    }
  }

  .rect-marker-dialog {
    height: 100%;
    width: 100%;
    opacity: 1;
    background: rgba(0, 0, 0, 0);
    overflow: hidden;
    position: relative;
    transform: translate(0, -100%);
    bottom: 0;
    left: 0;
    z-index: 900;
    pointer-events: none;
  }
}
</style>

<style lang="scss">
.el-submenu__title:hover {
  background-color: rgba(#1890ff, 0.085) !important;
  color: hsla(208, 100%, 55%, 0.95) !important;
}
</style>
