package com.rongwei.sfcommon.sys.service.impl;

import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.JSCommonUtils;
import com.rongwei.sfcommon.sys.service.JfCommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * JfCommonImpl class
 *
 * @author XH
 * @date 2024/09/20
 */
@Service
public class JfCommonServiceImpl implements JfCommonService {
    public static String API_URL = "https://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s&callback=showLocation&ret_coordtype=gcj02ll";
    public static String AK = "cYWTtJSCBvdDj6R7ex36eGHGoqbSraef";
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Override
    public R getLocationIdFormBDApi(String address) {

        log.info("根据地址：{}获取对应的经纬度坐标", address);

        JSCommonUtils.parameterCheck(() -> StringUtils.isBlank(address), "地址不能为空", "地址不能为空");
        URL url;
        HttpURLConnection conn;
        StringBuilder response = new StringBuilder();
        try {
            url = new URL(String.format(API_URL, address,AK));
            conn = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            conn.setRequestMethod("GET");
            // 接收响应码
            int responseCode = conn.getResponseCode();
            log.debug("响应码为:{}", responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

            }
        } catch (Exception e) {
            log.error("创建连接信息出现异常");
            return R.error("获取位置坐标失败！请联系系统管理员");
        }
        if (response.length() == 0) {
            log.debug("未获取到响应结果");
            return R.error("获取位置坐标失败！请联系系统管理员");
        }
        log.info("响应内容：{}", response);
        return R.ok(response.substring(response.toString().indexOf("{"), response.toString().length() - 1));
    }
}
