package com.jsowell.common.util.ip;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import com.jsowell.common.config.JsowellConfig;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 获取地址类
 *
 * @author jsowell
 */
public class AddressUtils {
	private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

	// IP地址查询
	public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

	// 高德查询地址api
	public static final String AMAP_GET_LOCATION_URL = "https://restapi.amap.com/v3/geocode/geo";

	// 高德应用key
	private static final String AMAP_GET_LOCATION_KEY = "51e155ceb3ab2d4f3b6bd81ebaab20b3";

	// 未知地址
	public static final String UNKNOWN = "XX XX";

	public static String getRealAddressByIP(String ip) {
		// 内网不查询
		if (IpUtils.internalIp(ip)) {
			return "内网IP";
		}
		if (JsowellConfig.isAddressEnabled()) {
			try {
				String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
				if (StringUtils.isEmpty(rspStr)) {
					log.error("获取地理位置异常 {}", ip);
					return UNKNOWN;
				}
				JSONObject obj = JSON.parseObject(rspStr);
				String region = obj.getString("pro");
				String city = obj.getString("city");
				return String.format("%s %s", region, city);
			} catch (Exception e) {
				log.error("获取地理位置异常 {}", ip);
			}
		}
		return UNKNOWN;
	}

	/**
	 * 地址转换经纬度
	 * areaCode和address必传参数，任意一个为空则返回null
	 * 高德api地址 https://lbs.amap.com/api/webservice/guide/api/georegeo
	 *
	 * @param areaCode 前端地址选择器获取到的区域编码 例如："320000,320500,320583"
	 * @param address  详细地址
	 * @return 逗号分割的经纬度字符串
	 */
	public static Map<String, String> getLongitudeAndLatitude(String areaCode, String address) {
		if (StringUtils.isBlank(areaCode) || StringUtils.isBlank(address)) {
			return null;
		}
		String[] split = StringUtils.split(areaCode, ",");
		String param = "key=" + AMAP_GET_LOCATION_KEY + "&city=" + split[2] + "&address=" + address;
		String resultStr = HttpUtils.sendGet(AMAP_GET_LOCATION_URL, param, Constants.UTF8);
		if (StringUtils.isNotBlank(resultStr)) {
			JSONObject resultObj = JSON.parseObject(resultStr);
			// 状态为1 查询成功
			if (StringUtils.equals(resultObj.getString("status"), Constants.ONE)) {
				JSONArray geocodes = resultObj.getJSONArray("geocodes");
				if (geocodes != null && geocodes.size() > 0) {
					Map<String, String> map = Maps.newHashMap();
					JSONObject jsonObject = geocodes.getJSONObject(0);
					String location = jsonObject.getString("location");
					String[] strArr = StringUtils.split(location, ",");
					map.put("lng", strArr[0]);
					map.put("lat", strArr[1]);
					return map;
				}
			}
		}
		return null;
	}
}
