import { useEffect, useState } from 'react';

export function useGeolocation() {
  const [position, setPosition] = useState<{
    position?: any;
    address?: any;
  } | null>(null);

  useEffect(() => {
    const AMapLoader = require('@amap/amap-jsapi-loader');
    window._AMapSecurityConfig = {
      securityJsCode: 'd7492300c43c8d3737909b77f2b2c387',
    };
    AMapLoader.load({
      key: '87b424e68754efc3ba9d11ae07475091', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Geolocation', 'AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then(async (AMap: any) => {
        //用户定位
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：5s
          position: 'RB', //定位按钮的停靠位置
          offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
          zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
        });
        geolocation.getCurrentPosition(function (status: string, result: any) {
          if (status == 'complete') {
            onComplete(result);
          } else {
            onError(result);
          }
        });
        //解析定位结果
        async function onComplete(data: any) {
          console.log('定位成功', data.position);
          setPosition({
            position: data.position,
            address: null,
          });

          var geocoder = new AMap.Geocoder({
            city: '全国', // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          });

          geocoder.getAddress(
            [data.position.lng, data.position.lat],
            function (
              status: string,
              result: {
                info: string;
                regeocode?: {
                  formattedAddress: string;
                  addressComponent: {
                    adcode: string;
                  };
                };
              },
            ) {
              console.log('获取地址结果', result);
              if (status === 'complete' && result.info === 'OK') {
                // result为对应的地理位置详细信息
                setPosition({
                  ...position,
                  address: result.regeocode,
                });
              } else {
                setPosition({
                  ...position,
                  address: null,
                });
              }
            },
          );
        }
        //解析定位错误信息
        async function onError(data: any) {
          // message.error(`定位失败
          // 失败原因排查信息：${data.message}
          // 浏览器返回信息：${data.originMessage}
          // `)
        }
      })
      .catch((e: any) => {
        console.log(e);
      });
  }, []);

  return position;
}
