import AMapLoader from '@amap/amap-jsapi-loader';
import {onMounted} from "vue";

export function useAMap(options) {
  let AMap, map, nowLayer, labelsLayer, scale, cluster;
  const markers = {
    point: []
  };
  let clickMarker = null;
  let addPoints = [];
  // 初始化事件
  const initMap = (options) => {
    AMapLoader.load({
      key: options.key, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: !!options.version ? options.version : '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: options.plugins ? options.plugins : ['AMap.Scale', 'AMap.RangingTool', 'AMap.MouseTool', 'AMap.PolygonEditor', 'AMap.MarkerCluster']
    }).then((res) => {
      AMap = res;
      map = new AMap.Map('aMap', {
        WebGLParams: {
          preserveDrawingBuffer: true
        },
        // 是否为3D地图模式
        viewMode: '3D',
        pitch: options.pitch,
        // 初始化地图级别
        zoom: options.zoom ? options.zoom : 11,
        // 初始化地图中心点位置
        center: options.center,
        // 是否可拖拽
        dragEnable: options.dragEnable,
        // 是否允许通过鼠标滚轮来缩放
        scrollWheel: options.scrollWheel
      });
      // 初始化比例尺
      if (options.showScale) {
        scale = new AMap.Scale();
        map.addControl(scale);
      }
      if (typeof options.onLoadCompleted === 'function') {
        options.onLoadCompleted(AMap, map);
      }
    });
  };
  const getAMap = () => {
    return AMap;
  };
  const getMap = () => {
    return map;
  };
  const getScale = () => {
    return scale;
  };
  // 切换地图
  const switchMap = (type: string) => {
    if (type === 'vectorgraph') {
      map.removeLayer(nowLayer);
    } else if (type === 'satellite') {
      const satellite = new AMap.TileLayer.Satellite();
      map.addLayer(satellite);
      nowLayer = satellite;
    }
  };
  // 添加搜索的标记的
  const addSearchMarker = (item) => {
    map.setCenter([item.longitude, item.latitude]);
    addMarker(item, true);
  };

  const addMarker = (points, isSearchItem?: boolean) => {
    clearMarker('point');
    addPoints = points;
    const count = points.length;
    const _renderClusterMarker = function (context) {
      console.log(context);
      console.log('21312', context.clusterData);
      // 聚合中点个数
      const clusterCount = context.count;
      const div = document.createElement('div');
      div.style.backgroundColor = 'rgba(78,179,211,.5)';
      const size = Math.round(25 + Math.pow(clusterCount / count, 1 / 5) * 20);
      div.style.width = div.style.height = size + 'px';
      div.style.border = 'solid 1px rgba(78,179,211,1)';
      div.style.borderRadius = size / 2 + 'px';
      div.innerHTML = context.count;
      div.style.lineHeight = size + 'px';
      div.style.color = '#ffffff';
      div.style.fontSize = '12px';
      div.style.textAlign = 'center';
      context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
      context.marker.setContent(div);
      context.marker.on('click', (e) => {
        debugger;
      });
    };
    const _renderMarker = function (context) {
      const content =
        '<div style="display: flex;flex-direction: column;align-items: center;justify-content: center">' +
        '<div style="background: url(' +
        context.data[0].icon +
        ') no-repeat; width: ' +
        context.data[0].size[0] +
        'px;height: ' +
        context.data[0].size[1] +
        'px;cursor: pointer; background-size: cover"></div>' +
        // '<div style="font-size: 36px;white-space: nowrap">'+ context.data[0].name +'</div>' +
        '</div>';
      const offset = new AMap.Pixel(-9, -9);
      context.marker.setContent(content);
      context.marker.setOffset(offset);
      context.marker.setExtData(context.data[0]);
      context.marker.on('click', function (e) {
        const extData = e.target.getExtData();
        let index = 0;
        let index2 = 0;
        for (let i = 0; i < addPoints.length; i++) {
          if (addPoints[i].id === extData.id && addPoints[i].imageHover) {
            addPoints[i].icon = addPoints[i].imageHover;
            e.target.setContent(content);
            index++;
          } else if (!!clickMarker) {
            const extData2 = clickMarker.getExtData();
            if (addPoints[i].id === extData2.id) {
              addPoints[i].icon = addPoints[i].image;
              clickMarker.setContent(content);
              index2++;
            }
          }
          if ((!!clickMarker && index === 1 && index2 === 1) || (!clickMarker && index === 1)) {
            break;
          }
        }
        addMarker(addPoints);
        clickMarker = e.target;
        options.onMarkerClick(extData);
      });
    };
    cluster = new AMap.MarkerCluster(
      map, //地图实例
      points, //海量点数据，数据中需包含经纬度信息字段 lnglat
      {
        gridSize: 30, //数据聚合计算时网格的像素大小
        renderClusterMarker: _renderClusterMarker, //上述步骤的自定义聚合点样式
        renderMarker: _renderMarker //上述步骤的自定义非聚合点样式
      }
    );
    points.forEach((item) => {
      markers['point'].push(item);
    });
  };

  // 清除所有标加
  const clearMarker = (id) => {
    if (!cluster || !markers[id]) return;
    cluster.setMap(null);
    markers[id] = [];
  };

  const handleHover = (extData, dataType) => {
    map.setZoom(18);
    map.setCenter([extData.lng, extData.lat]);
    setTimeout(() => {
      let index = 0;
      let index2 = 0;
      let data = {};
      debugger
      for (let i = 0; i < addPoints.length; i++) {
        if (addPoints[i].id === extData.id.toString() && addPoints[i].dataType === dataType) {
          addPoints[i].icon = addPoints[i].imageHover;
          index++;
          data = addPoints[i];
        } else if (!!clickMarker) {
          const extData2 = clickMarker.getExtData();
          if (addPoints[i].id === extData2.id) {
            addPoints[i].icon = addPoints[i].image;
            index2++;
          }
        }
        if ((!!clickMarker && index === 1 && index2 === 1) || (!clickMarker && index === 1)) {
          break;
        }
      }
      addMarker(addPoints);
      options.onMarkerClick(data);
    }, 2000);
  };

  const getMarkers = () => {
    return markers;
  };

  // 显示信息框
  let infoWindow;
  const showInfo = (content, position, isCustom) => {
    hideInfo();
    // 实例化InfoWindow
    infoWindow = new AMap.InfoWindow({
      // 完全自定义
      isCustom: isCustom,
      offset: new AMap.Pixel(0, -20) // 信息窗体的偏移量
      // 可以根据需要设置其他InfoWindow的属性
    });
    const lnglat = new AMap.LngLat(position[0], position[1]);
    // 打开InfoWindow，并设置其内容和位置
    infoWindow.setContent(content);
    infoWindow.open(map, lnglat);
  };

  const hideInfo = (e) => {
    if (!!infoWindow) {
      infoWindow.close();
      if (!!clickMarker && e) {
        const extData = clickMarker.getExtData();
        for (let i = 0; i < addPoints.length; i++) {
          if (addPoints[i].id === extData.id) {
            addPoints[i].icon = addPoints[i].image;
            clickMarker = null;
            addMarker(addPoints);
            break;
          }
        }
      }
    }
  };


  initMap(options);
  return {
    getAMap,
    getMap,
    switchMap,
    addMarker,
    addSearchMarker,
    clearMarker,
    getMarkers,
    getScale,
    showInfo,
    hideInfo,
    handleHover
  };
}
