import React, { useState, useEffect, useRef } from 'react';
import isNumber from '@pansy/is-number';
import { Position, ExpansionProps } from '../types';
import styles from './index.less';

interface SelectPointProps extends ExpansionProps {
  visible?: boolean;
  onChange?: (position: Position) => void;
}

const SelectPoint: React.FC<SelectPointProps> = props => {
  const { onChange, visible, __map__ } = props;

  const map = __map__;

  const zoom = useState(map.getZoom());

  const center = useRef([map.getCenter().lng, map.getCenter().lat]);

  const handleChange = () => {
    let centerLngLat = map.getCenter();
    if (
      centerLngLat.lng === center.current[0] &&
      centerLngLat.lat === center.current[1]
    )
      return;
    center.current = [centerLngLat.lng, centerLngLat.lat];
    onChange &&
      onChange({
        latitude: centerLngLat.lat,
        longitude: centerLngLat.lng,
      });
  };

  useEffect(() => {
    //地图事件
    map.on('moveend', () => {
      handleChange();
    });
    map.on('zoomend', () => {
      handleChange();
    });
  }, []);

  useEffect(() => {
    if (visible && zoom && isNumber(zoom[0])) {
      map.setZoom(zoom[0]);
    }
  }, [visible]);

  return <span className={styles.selectPoint} />;
};

SelectPoint.defaultProps = {
  visible: true,
};

export default SelectPoint;
