package com.xkrs.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkrs.model.vo.FileServerResultVo;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 上传工具
 * @author tajochen
 **/
public class RequestUtil {

    /**
     * 发送管理命令到文件服务器
     * @param url
     * @param map
     * @return
     */
    public static FileServerResultVo postFileManage(String url, Map<String,String> map){
        Logger log = LoggerFactory.getLogger(RequestUtil.class);
        String body = "";
        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        try {
            // 设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            // 设置header报文头信息
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
            httpPost.setHeader("Accept", "application");
            httpPost.setHeader("Accept-Encoding", "gzip, deflate");
            // 执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            // 释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileServerResultVo fileServerResultVo = new FileServerResultVo();
        ObjectMapper mapper = new ObjectMapper();
        try {
            fileServerResultVo = mapper.readValue(body, FileServerResultVo.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.warn(e.toString());

        }
        return fileServerResultVo;
    }

    /**
     * 模拟 get请求
     * @param url   链接
     * @param map   参数列表
     */
    public static void getStandard(String url, Map<String,String> map) {
        // 1.拿到一个httpclient的对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2.设置请求方式和请求信息
        HttpPost httpPost = new HttpPost(url);
        //2.1 提交header头信息
        httpPost.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        //2.1 提交请求体
        ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        // 装填参数
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(parameters));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 3.执行请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 4.获取返回值
        String html = null;
        try {
            assert response != null;
            html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 5.打印
        System.out.println(html);
    }

    /**
     * 模拟get请求（加请求头）
     * @param url
     * @param param
     * @return
     */
    public static String doGet(String url, Map<String, String> param) {

        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 模拟Post请求 application/x-www-form-urlencoded
     * @param url   资源地址
     * @param map   参数列表
     * @return
     */
    public static String postStandard(String url, Map<String,String> map) {
        String body = "";
        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        try {
            // 设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            // 设置header报文头信息
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
            httpPost.setHeader("Accept", "application");
            httpPost.setHeader("Accept-Encoding", "gzip, deflate");
            // 执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            // 释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * 模拟Post请求 multipart/form-data
     * @param postFile
     * @param postUrl
     * @param postParam
     * @return
     */
    public static Map<String,Object> postFile(File postFile,String postUrl,Map<String,String> postParam) {

        Logger log = LoggerFactory.getLogger(RequestUtil.class);
        Map<String,Object> resultMap = new HashMap<String,Object>(16);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try{
            // 把一个普通参数和文件上传给下面这个地址
            HttpPost httpPost = new HttpPost(postUrl);

            // 设置传输参数
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            // 解决乱码问题
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.setCharset(StandardCharsets.UTF_8);

            // 设置文件参数 ，获取文件名postFile.getName()
            // 把文件转换成流对象FileBody
            multipartEntity.addBinaryBody("file",postFile, ContentType.create("multipart/form-data", Consts.UTF_8),postFile.getName());
            // 设计文件以外的参数
            Set<String> keySet = postParam.keySet();
            for (String key : keySet) {
                // 相当于<input type="text" name="name" value=name>
                multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("multipart/form-data", Consts.UTF_8)));
            }
            HttpEntity reqEntity =  multipartEntity.build();
            httpPost.setEntity(reqEntity);
            // 设置header报文头信息
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0");
            httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpPost.setHeader("Accept-Encoding","gzip, deflate");

            // 发起请求，返回请求的响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                resultMap.put("statusCode", response.getStatusLine().getStatusCode());
                // 获取响应对象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    // 打印响应内容
                    resultMap.put("data", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
                    resultMap.put("message", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
                    resultMap.put("status", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
                }
                // 销毁
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally{
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("上传结果:" + resultMap);
        return resultMap;
    }
}
