package cn.qinys.platform.admin.service.impl;

import cn.qinys.platform.admin.service.GaoDeService;
import cn.qinys.platform.base.exceptions.BizException;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * @author lie tan
 * @description
 * @date 2026-06-13 11:15
 **/
@Slf4j
@Service
public class GaoDeServiceImpl implements GaoDeService {

    @Resource
    RestTemplate restTemplate;

    String key = "88a0c82c3f60a748c6c638ef9db16bca";

    @Override
    public JSONObject getGaoDeResult(BigDecimal lon, BigDecimal lat, Integer index) {
        if (index >= 100) {
            return null;
        }
        index++;
        String url = "https://restapi.amap.com/v3/geocode/regeo?key={0}&location={1},{2}";
        JSONObject res = restTemplate.getForObject(url, JSONObject.class, key, lon, lat);
        if (res == null) {
            throw new BizException("逆地理解释出现错误");
        }
        if ("1".equals(res.getString("status"))) {
            log.info("获取逆地理解析信息成功{}", res);
            return res.getJSONObject("regeocode");
        } else {
            return this.getGaoDeResult(lon, lat, index);
        }
    }

}
