import AMapLoader from '@amap/amap-jsapi-loader'

// 简易请求
function request(url, params, options = {}) {
  const queryString = Object.keys(params || {}).map((key) => {
    const val = encodeURIComponent(params[key])
    return `${key}=${val}`
  }).join('&')

  const api = queryString ? `${url}?${queryString}` : url

  return new Promise((resolve, reject) => {
    window.fetch(api, {
      mode: 'cors',
      referrerPolicy: 'no-referrer',
      ...options
    }).then(response => response.json())
    .then((data) => {
      const { status, info } = data
      if (status === '1') {
        resolve(data)
      } else {
        console.error(data)
        const err = new Error(info)
        reject(err)
      }
    }).catch(reject)
  })
}

export default function amapSDK(key) {
  const prefix = 'https://restapi.amap.com'

  function loadMapModule(options = {}) {
    // AMapLoader 可以多次加载
    return new Promise((resolve, reject) => {
      AMapLoader.load({
        ...options,
        key: key.web,
      }).then((AMap) => {
        resolve(AMap)
      }).catch((e) => {
        reject(e)
      })
    })
  }

  function getPlaceAround(params = {}) {
    const url = `${prefix}/v3/place/around`
    return request(url, { key: key.service, ...params } )
  }

  return {
    loadMapModule,
    getPlaceAround,
  }
}
