/**
 * 首页地图组件-使用ClusteringMapView
 * @邠心vbe on 2021/03/18
 */
import React, { useEffect, useRef } from 'react';
import { PROVIDER_GOOGLE } from 'react-native-maps';
import MapView from "react-native-map-clustering";
import { MyCluster, MyMarker } from './Cluster';

export default Maps2 = ({ region, onMapReady, stopList, onMarkerPress }) => {
  const mapRef = useRef();
  const superClusterRef = useRef();

  useEffect(() => {
    console.log('mapRef.current', mapRef.current);
    //mapRef.current.animateToRegion(region, 500);
    mapRef.current.animateCamera({ center: region, zoom: 17 }, { duration: 500 }); //移动地图到当前位置并放大
  }, [region])

  /*componentDidMount() {
    this.mapRef = this.ref.current.mapRef ? this.ref.current.mapRef : this.ref.current;
  }*/

  const renderCluster = (props) => {
    //console.log("renderCluster", props);
    let hasAvailableConnector = false;
    if (props.geometry.hasAvailableConnector === undefined) {
      if (superClusterRef) {
        const points = superClusterRef.current.getLeaves(props.id, Infinity, 0);
        if (points) {
          for (let index = 0; index < points.length; index++) {
            const point = points[index];
            if (point.properties.coordinate?.available) {
              hasAvailableConnector = true;
              break;
            }
          }
        }
      }
    } else {
      hasAvailableConnector = props.geometry.hasAvailableConnector
    }
    props.geometry.hasAvailableConnector = hasAvailableConnector;
    const latlng = {latitude: props.geometry.coordinates[1], longitude: props.geometry.coordinates[0]}
    //InteractionManager.runAfterInteractions();
    return (
      <MyCluster
        {...props}
        key={props.id}
        location={latlng}
        available={hasAvailableConnector}
        onOpen2={latlng => openClusterMarker(latlng)}/>
    );
  }

  const openClusterMarker = async (latlng) => {
    var camera = await mapRef.current.getCamera();
    camera.center = latlng
    camera.zoom = camera.zoom + 2
    //console.log('camera', camera);
    mapRef.current.animateCamera(camera, 300);
  }

  return (
    <MapView
      ref={mapRef}
      superClusterRef={superClusterRef}
      style={ui.flex1}
      minZoom={10}
      maxZoom={15}
      radius={45}
      extent={512}
      nodeSize={64}
      provider={PROVIDER_GOOGLE}
      onMapReady={onMapReady}
      showsUserLocation={true}
      initialRegion={region}
      renderCluster={(info) => renderCluster(info)}>
      { stopList.map((marker, index) => {
        return (
          <MyMarker
            key={index}
            {...marker}
            coordinate={marker}
            onPress={() => onMarkerPress(marker.id)}
          />
        );
      })}
    </MapView>
  );
}