import React, { FC, useEffect } from 'react';
import { ExpansionProps } from '../types';

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

const BrowerLocation: FC<BrowerLocationProps> = props => {
  const { __map__, onChange } = props;
  const map = __map__;

  const handlePositionGot = (status: string, result: any) => {
    if (status === 'complete') {
      const { position, addressComponent = {}, formattedAddress } =
        result || {};
      const { province, city, district } = addressComponent || {};
      onChange?.(
        `${position.lng},${position.lat}`,
        `${province}${city}${district}`,
        formattedAddress,
      );
    } else console.info(`浏览器定位失败 ======>`, JSON.stringify(result));
  };

  useEffect(() => {
    map.plugin(['AMap.Geolocation'], () => {
      const geolocation = new window.AMap.Geolocation({
        // 是否使用高精度定位，默认：true
        enableHighAccuracy: true,
        // 设置定位超时时间，默认：无穷大
        timeout: 10000,
        // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
        buttonOffset: new window.AMap.Pixel(10, 20),
        //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        zoomToAccuracy: true,
        //  定位按钮的排放位置,  RB表示右下
        buttonPosition: 'RB',
      });

      geolocation.getCurrentPosition(handlePositionGot);
    });
  }, []);

  return <div />;
};

export default BrowerLocation;
