import AMapLoader from '@amap/amap-jsapi-loader'
let Amap
async function GetGDMap(secretKey, key) {
  if (!Amap) {
    window._AMapSecurityConfig = {
      securityJsCode: secretKey
    }
    //  解决高德地图加载报错 ---> 禁止多种API加载方式混用
    AMapLoader.reset()
    Amap = await AMapLoader.load({
      key: key, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        'AMap.IndexCluster',
        'AMP.MarkerCluster',
        'AMap.InfoWindow',
        'AMap.HeatMap',
        'AMap.HawkEye',
        'AMap.DistrictSearch',
        'AMap.CitySearch',
        'AMap.ToolBar',
        'AMap.Geolocation',
        'AMap.MouseTool',
        'AMap.Geocoder',
        'AMap.MarkerClusterer',
        'AMap.AutoComplete',
        'AMap.Scale'
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      AMapUI: {
        version: '1.1', // AMapUI 缺省 1.1
        plugins: ['misc/PositionPicker'] // 需要加载的 AMapUI ui插件
      }
    })
  }
  return Amap
}

async function getGDMap(address) {
  new (await GetGDMap()).Geocoder({
    radius: 500 // 范围，默认：500
  }).getLocation(address, function (status, result) {
    if (status === 'complete' && result.geocodes.length) {
      return { lng: result.geocodes[0].location.lng, lat: result.geocodes[0].location.lat }
    } else {
      // eslint-disable-next-line prefer-promise-reject-errors
      throw new Error('根据经纬度查询地址失败')
    }
  })
}

async function GetLocation(address) {
  return new Promise((resolve, reject) => {
    try {
      resolve(getGDMap(address))
    } catch (e) {
      reject(e)
    }
  })
}
export { GetGDMap, GetLocation }
