package com.app.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

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

@Component
public class HttpUtil {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 功能描述：
     *
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        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 (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

    /**
     * 功能描述：获取服务器地址  http://localhost:8080/  类似
     *
     * @param request
     * @return
     */
    public String getServerPath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    /**
     * 功能描述：
     *
     * @return
     */
    public String getHostAddress() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
        }

        return addr.getHostAddress();
    }

    /**
     * 功能描述：发送GET请求
     *
     * @param url
     * @return
     */
    public String get(String url) {
        return get(url, null);
    }

    /**
     * 功能描述：发送GET请求
     *
     * @param url
     * @param param
     * @return
     */
    public String get(String url, Map<String, String> param) {
        return restTemplate.getForEntity(url, String.class, param).getBody();
    }

    /**
     * 功能描述：发送POST-JSON请求
     *
     * @param url
     * @param jsonObject
     * @return
     */
    public String post(String url, JSONObject jsonObject) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity formEntity = new HttpEntity(jsonObject, headers);
        return restTemplate.postForEntity(url, jsonObject, String.class).getBody();
    }

    /**
     * 功能描述：发送POST-JSON请求
     *
     * @param url
     * @param param
     * @return
     */
    public String post(String url, String param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity formEntity = new HttpEntity(param, headers);
        return restTemplate.postForEntity(url, param, String.class).getBody();
    }

    /**
     * 功能描述：发送POST 表单请求
     *
     * @param url
     * @param param
     * @return
     */
    public String post(String url, MultiValueMap<String, String> param) {
        // 请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        return restTemplate.postForEntity(url, param, String.class).getBody();
    }

}
