package com.czg.service.account.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.czg.account.service.GeoService;
import com.czg.exception.CzgException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.util.HashMap;
import java.util.Map;

/**
 * 经纬度
 *
 * @author Administrator
 */
@Service
@Slf4j
public class GeoServiceImpl implements GeoService {
    private final RestClient restClient = RestClient.create();
    private static final String API_KEY = "7a7f2e4790ea222660a027352ee3af39";
    private static final String BASE_URL = "https://restapi.amap.com/v3/geocode/regeo";

    @Override
    public JSONObject getAddress(String lat, String lng) {
        // 高德 API 坐标格式为 "经度,纬度"
        String location = lng + "," + lat;

        String response = restClient.get()
                .uri(BASE_URL + "?key=" + API_KEY + "&location=" + location)
                .retrieve()
                .body(String.class);

        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject == null) {
            log.warn("经纬度获取失败{}", response);
            throw new CzgException("获取经纬度失败");
        }
        return jsonObject.getJSONObject("regeocode");
    }

    @Override
    public String district(String keywords, String subdistrict) {
        Map<String, Object> param = new HashMap<>();
        //超掌柜生活-用户端
        param.put("key", "7a7f2e4790ea222660a027352ee3af39");
        param.put("keywords", keywords);
        param.put("subdistrict", "1");
        if (StrUtil.isNotBlank(subdistrict)) {
            param.put("subdistrict", "2");
        }
        param.put("extensions", "base");
        String s = HttpUtil.get("https://restapi.amap.com/v3/config/district", param);
        return s;
    }
}


