package com.tzy.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzy.common.utils.http.forest.CommonForestClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;

// 高德地址编码工具类
@Slf4j
@Component
public class AmapUtils {

    @Resource
    private CommonForestClient commonForestClient;
    private static final String AMAP_API_KEY = "3cb75b92582973bf1f3dd77fa83660f2";

    public String getLocation(String showConfigJson) {
        String location = "";
        try {
            if (StringUtils.isNotEmpty(showConfigJson)) {
                JSONObject showConfig = JSONObject.parseObject(showConfigJson);
                String address = "";
                if (showConfig.containsKey("address")) {
                    address += showConfig.getString("address");
                }
                if (showConfig.containsKey("addressMore")) {
                    address += showConfig.getString("addressMore");
                }
                String url = UriComponentsBuilder.fromHttpUrl("https://restapi.amap.com")
                        .path("/v3/geocode/geo")
                        .queryParam("address", address)
                        .queryParam("output", "JSON")
                        .queryParam("key", AMAP_API_KEY)
                        .build()
                        .toUriString();
                String jsonstr = commonForestClient.sendGet(url);
                JSONObject json = JSON.parseObject(jsonstr);
                if (json != null && "1".equals(json.getString("status"))) {
                    JSONArray jsonArray = json.getJSONArray("geocodes");
                    location = jsonArray.getJSONObject(0).getString("location");
                }
            }
        } catch (Exception e) {
            log.error("获取高德地理编码异常：" + e);
        }
        return location;
    }
}
