package cn.pluss.platform.util;

import cn.pluss.platform.exception.MsgException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.geoip.model.v20200101.DescribeIpv4LocationResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * IP相关接口
 */
public class IpUtils {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST = "127.0.0.1";
    private static final String SEPARATOR = ",";

    public static String getIpAddr(HttpServletRequest request) {
        System.out.println(request);
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (LOCALHOST.equals(ipAddress)) {
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                        ipAddress = inet.getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(SEPARATOR) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

    /**
     * 是否为公网ip
     * @return
     */
    public static boolean isWAN(String ip) {
        if (StringUtils.isEmpty(ip)) {
            throw new MsgException("ip不能为空");
        }

        if (ip.startsWith("192.168")) {
            return false;
        }

        if (ip.startsWith("172.16")) {

        }

        return false;
    }

    /**
     * 高德根据ip获取经纬度
     * @param address
     * @return
     */
    public static Map<String,String> getLocationByAddress(String address){
        Map<String,String> result = new HashMap<>(2);
        String url = "https://restapi.amap.com/v3/geocode/geo?address="+address+"&key=4d6b5117916ada2b52452d6a04483ac7";
        RestTemplate restTemplate = new RestTemplate();
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        if("1".equals(forObject.getString("status"))){
            JSONArray geocodes = forObject.getJSONArray("geocodes");
            String location = geocodes.getJSONObject(0).getString("location");
            result.put("y",location.split(",")[0]);
            result.put("x",location.split(",")[1]);
            return result;
        }
        return null;
    }

    public static String getIpLoactionAddress(DescribeIpv4LocationResponse response) {
        if(response == null){
            return null;
        }
        StringBuffer sb = new StringBuffer();
        if(StringUtil.isNotEmpty(response.getProvince())){
            sb.append(response.getProvince() + "-");
        }
        if(StringUtil.isNotEmpty(response.getCity())){
            sb.append(response.getCity() + "-");
        }
        if(StringUtil.isNotEmpty(response.getCounty())){
            sb.append(response.getCounty() + "-");
        }
        if(sb.length() == 0){
            return null;
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
