/**
 * 封装地图类信息
 * @author Rockery(1113269755@qq.com)
 */

import indexConfig from '@/agrcloud-config/index.config';

module.exports = (params) => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (getLocationRes) => {
        const longitude = getLocationRes.longitude;
        const latitude = getLocationRes.latitude;
        uni.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo',
          data: {
            location: longitude + ',' + latitude,
            key: indexConfig.amapKey
          },
          method: "GET",
          dataType: "json",
          success: (regeocodeRes) => {
            if (regeocodeRes.statusCode == 200) {
              const currAdcode = (((regeocodeRes.data || {}).regeocode || {}).addressComponent || {}).adcode ||
                '520123';
              uni.request({
                url: 'https://restapi.amap.com/v3/weather/weatherInfo',
                data: {
                  key: indexConfig.amapKey,
                  city: currAdcode,
                  extensions: 'base'
                },
                method: "GET",
                dataType: "json",
                success: (weatherInfoRes) => {
                  const weatherInfoLives = ((weatherInfoRes.data || {}).lives || [])[0] || {};
                  resolve({
                    locationInfo: getLocationRes,
                    regeocode: (regeocodeRes.data || {}).regeocode,
                    weatherInfo: weatherInfoLives
                  });
                },
                fail: weatherInfoErr => {
                  uni.showToast({
                    title: weatherInfoErr.errMsg,
                    icon: 'none'
                  });
                  reject('err');
                }
              });
            }
          },
          fail: regeocodeErr => {
            uni.showToast({
              title: regeocodeErr.errMsg,
              icon: 'none'
            });
            reject('err');
          }
        });
      },
      fail: (getLocationErr) => {
        uni.showToast({
          title: getLocationErr.errMsg,
          icon: 'none'
        });
        reject('err');
      }
    });
  });
};
