import { message } from 'antd';
import Axios from 'axios';

// 位置的类型
export interface LocationType {
  ip: string;
  network: string;
  version: string;
  city: string;
  region: string;
  region_code: string;
  country: string;
  country_name: string;
  country_code: string;
  country_code_iso3: string;
  country_capital: string;
  country_tld: string;
  continent_code: string;
  in_eu: boolean;
  postal: null;
  latitude: number;
  longitude: number;
  timezone: string;
  utc_offset: string;
  country_calling_code: string;
  currency: string;
  currency_name: string;
  languages: string;
  country_area: number;
  country_population: number;
  asn: string;
  org: string;
  status: string;
  info: string;
  infocode: string;
  province: string;
  adcode: string;
  rectangle: string;
}

// 根据用户的ip地址获取当前位置
export default function getLocationByIP(): Promise<LocationType> {
  return new Promise((resolve, reject) => {
    // 用户的ip信息
    let ipInfo: LocationType;
    // 获取用户的ip信息
    const getIPInfo = async () => {
      const res = await Axios.get('https://ipapi.co/json/');
      if (res && res?.status === 200) {
        ipInfo = res.data;
        // console.log('获取位置1 --->', ipInfo);
        return;
      }
      message.warning('获取位置失败').then();
    };
    // 根据ip信息获取位置信息
    const getLocationByIPInfo = async () => {
      const res = await Axios.get(
        `https://restapi.amap.com/v3/ip?key=4f98d03f611b80f95a0ad56b044ffb59&ip=${ipInfo.ip}`,
      );
      if (res && res?.status === 200) {
        const { province, city, adcode, rectangle } = res.data;
        ipInfo.province = province;
        ipInfo.city = city;
        ipInfo.adcode = adcode;
        ipInfo.rectangle = rectangle;
        // console.log('获取位置 --->', ipInfo);
        resolve(ipInfo);
        return;
      }
      message.warning('获取位置失败').then();
      reject(ipInfo);
    };
    // 自执行
    (async () => {
      await getIPInfo();
      await getLocationByIPInfo();
    })();
  });
}
