import { FC, useEffect } from 'react';
import { Position, ExpansionProps } from '@/components/map/types';

interface SelectPositionProps extends ExpansionProps {
  onChange?: (position: Position, address: string) => void;
}

const SelectPosition: FC<SelectPositionProps> = props => {
  const { onChange, __map__ } = props;

  const map = __map__;

  const handleChange = (position: Position, address: string) => {
    onChange && onChange(position, address);
  };

  useEffect(() => {
    //地图事件
    map.on('click', (e: any) => {
      const lnglat = e.lnglat;
      map.plugin('AMap.Geocoder', function() {
        const geocoder = new window.AMap.Geocoder();
        geocoder.getAddress(
          [lnglat.lng, lnglat.lat],
          (status: string, result: any) => {
            let address = '';
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              address = result.regeocode.formattedAddress;
            }
            handleChange(
              {
                longitude: lnglat.lng,
                latitude: lnglat.lat,
              },
              address,
            );
          },
        );
      });
    });
  }, []);

  return null;
};

export default SelectPosition;
