package com.infoepoch.pms.dispatchassistant.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.infoepoch.pms.dispatchassistant.common.component.Result;
import jdk.nashorn.internal.runtime.regexp.joni.exception.ValueException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.validation.ValidationException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Component
public class RestTemplateUtils {

    private final Logger logger = LoggerFactory.getLogger(RestTemplateUtils.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * delete
     *
     * @param url   请求地址
     * @param param 参数
     * @return
     */
    public String deleteFormData(String url, MultiValueMap<String, String> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(param, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
        return exchange.toString();
    }

    /**
     * get
     *
     * @param url         请求地址
     * @param param       参数
     * @param returnClass 返回类型
     * @return
     */
    public <T> T get(String url, Class<T> returnClass, Map<String, ?> param) {
        return restTemplate.getForObject(url, returnClass, param);
    }

    /**
     * post
     *
     * @param url         请求地址
     * @param param       参数
     * @param returnClass 返回类型
     * @param header      自定义的头信息
     * @return
     */
    public <E> E post(String url, E param, Class<E> returnClass, Map<String, String> header) {
        HttpHeaders headers = new HttpHeaders();
        for (Map.Entry<String, String> entry : header.entrySet()) {
            headers.set(entry.getKey(), entry.getValue());
        }

        //header.forEach((o1, o2) -> headers.set(o1, o2));
        HttpEntity<E> httpEntity = new HttpEntity<E>(param, headers);
        return restTemplate.postForObject(url, httpEntity, returnClass);
    }

    /**
     * post
     *
     * @param url       请求地址
     * @param postParam 参数
     * @return
     */
    public String postFormData(String url, MultiValueMap<String, String> postParam) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(postParam, headers);
        return restTemplate.postForEntity(url, request, String.class).getBody();
    }

    /**
     * post
     *
     * @param url         请求地址
     * @param param       参数
     * @param returnClass 返回类型
     * @return
     */
    public <E> E postByDefault(String url, E param, Class<E> returnClass) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity<E> httpEntity = new HttpEntity<E>(param, headers);
        return restTemplate.postForObject(url, httpEntity, returnClass);
    }

    /**
     * post方式，json格式传输和接收数据
     *
     * @param url
     * @param param
     * @return
     */
    public String postByDefault(String url, String param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(param, headers);
        String jsonResult = restTemplate.postForObject(url, formEntity, String.class);
        return jsonResult;
    }

    /**
     * 获取result类型的返回结果
     *
     * @param url
     * @param param
     * @return
     */
    public Result postForResult(String url, Map<String, Object> param) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(JsonUtils.objectToJson(param), headers);
        String jsonResult = restTemplate.postForObject(url, formEntity, String.class);
        JsonNode jsonNode = JsonUtils.jsonToJsonNode(jsonResult);
        Boolean success = jsonNode.get("isSuccess").asBoolean();
        String message = jsonNode.get("message").asText();
        if (success)
            return Result.successData(jsonNode);
        else
            return Result.error(-1, message);
    }

    /**
     * 获取result类型的返回结果
     *
     * @param url
     * @param param
     * @return
     */
    public Result postForResultTwo(String url, Map<String, Object> param) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(JsonUtils.objectToJson(param), headers);
        String jsonResult = restTemplate.postForObject(url, formEntity, String.class);
        JsonNode jsonNode = JsonUtils.jsonToJsonNode(jsonResult);
        boolean success = jsonNode.get("isSuccess").asBoolean();
        String message = jsonNode.get("message").asText();
        if (success)
            return Result.successData(jsonNode.get("data"));
        else
            return Result.error(-1, message);
    }
    /**
     * 获取result类型的返回结果
     *
     * @param url
     * @param param
     * @return
     */
    public JsonNode postForLinkedMultiValueMap(String url, MultiValueMap<String, Object> param) {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        String jsonResult = responseEntity.getBody();
        JsonNode jsonNode = JsonUtils.jsonToJsonNode(jsonResult);
        String s = jsonNode.toString();
        logger.info("postForLinkedMultiValueMap return result"+s);
        String userId = jsonNode.get("data").get("userId").asText();
        logger.info("postForLinkedMultiValueMap userId result"+userId);
        return jsonNode;
    }

    /**
     * 获取原生result类型的返回结果
     *
     * @param url
     * @param param
     * @return
     */
    public Result postForTrueResult(String url, Map<String, Object> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(JsonUtils.objectToJson(param), headers);
        String jsonResult = restTemplate.postForObject(url, formEntity, String.class);
        JsonNode jsonNode = JsonUtils.jsonToJsonNode(jsonResult);
        if (!jsonNode.has("isSuccess"))
            return Result.error(-1, jsonResult);
        return JsonUtils.jsonToObject(jsonResult, Result.class);
    }


    /**
     * 获取jsonNode类型的返回结果
     *
     * @param url
     * @param param
     * @return
     */
    public JsonNode postForJsonNode(String url, Map<String, Object> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(JsonUtils.objectToJson(param), headers);
        String jsonResult = restTemplate.postForObject(url, formEntity, String.class);
        return JsonUtils.jsonToJsonNode(jsonResult);
    }

    /**
     * 获取jsonNode类型的返回结果
     *
     * @param url
     * @param param
     * @return
     */
    public JsonNode postForJsonNodeTwo(String url, Map<String, String> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(JsonUtils.objectToJson(param), headers);
        String jsonResult = restTemplate.postForObject(url, formEntity, String.class);
        return JsonUtils.jsonToJsonNode(jsonResult);
    }

    /***
     * @Description: get请求
     * @Param: [url, param]
     * @return:
     * @Author: lxd
     * @Date: 2020/3/20
     */
    public String getIncludeParam(String url, Map<String, Object> param) {
        String result = restTemplate.getForObject(url, String.class, param);
        return result;
    }

    /**
     * get方式，json格式接收数据
     *
     * @param url
     * @return
     */
    public String getByDefault(String url) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String jsonResult = restTemplate.getForObject(url, String.class);
        return jsonResult;
    }

    public Result getForResult(String url) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String jsonResult = restTemplate.getForObject(url, String.class);
        JsonNode jsonNode = JsonUtils.jsonToJsonNode(jsonResult);
        if(jsonNode == null)
            return Result.error(-1,"转换返回值失败");
        boolean success = jsonNode.get("isSuccess").asBoolean();
        String message = jsonNode.get("message").asText();
        if (success)
            return Result.successData(message);
        else
            return Result.error(-1, message);
    }


    public Result getForResultTwo(String url) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String jsonResult = restTemplate.getForObject(url, String.class);
        JsonNode jsonNode = JsonUtils.jsonToJsonNode(jsonResult);
        if(jsonNode == null)
            return Result.error(-1,"转换返回值失败");
        boolean success = jsonNode.get("isSuccess").asBoolean();
        String message = jsonNode.get("message").asText();
        if (success)
            return Result.successData(jsonNode.get("data"));
        else
            return Result.error(-1, message);
    }

    /**
     * 详见
     * {@link RestTemplateUtils#postHttpRequest(String, Object, String)}
     */
    public Result postHttpRequest(String url, String errorMsgDesc) {
        return postHttpRequest(url, null, errorMsgDesc);
    }

    /**
     * POST请求
     *
     * @param url    url
     * @param object 请求实体
     * @param <T>    实体类型
     * @return 接口返回数据包装类
     */
    public <T> Result postHttpRequest(String url, T object, String errorMsgDesc) {
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) {
            if (item.getClass() == StringHttpMessageConverter.class) {
                converterTarget = item;
                break;
            }
        }
        if (converterTarget != null) {
            converterList.remove(converterTarget);
        }
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        converterList.add(1, converter);

        logger.info("【POST】请求URL：{}，请求数据：{}", url, JsonUtils.printToJsonString(object));
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
        header.put(HttpHeaders.ACCEPT, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));


        ResponseEntity<String> exchangeResult;
        try {
            exchangeResult = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(object, header), String.class);
            if (!exchangeResult.getStatusCode().equals(HttpStatus.OK)) {
                logger.info("请求异常【{}】. URL: {}{}", exchangeResult.getStatusCode(), url, JsonUtils.printToJsonString(exchangeResult.getHeaders()));
                throw new ValidationException("请求异常【" + exchangeResult.getStatusCode() + "】. URL: " + url);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ValidationException(errorMsgDesc + ": " + ex.getMessage() + ". URL: " + url);
        }
        JsonNode resultNode =
                Optional.ofNullable(JsonUtils.jsonToJsonNode(exchangeResult.getBody())).orElseThrow(() -> new ValueException("URL：" + url + "结果解析异常！"));
        if (resultNode.get("isSuccess").asBoolean()) {
            return Result.successData(resultNode.get("data"));
        }
        return Result.error(resultNode.get("code").intValue(), resultNode.get("message").asText(), resultNode.get("data"));
    }

    /**
     * @Description: getHttpStatus
     * @Param: [url 请求地址 , queryParams url查询参数]
     * @Author: zhangyd
     */
    public HttpStatus getHttpStatus(String url, Map<String, Object> queryParams) {
        url = buildQueryParams(url, queryParams);
        if (StringUtils.isBlank(url))
            return null;
        ResponseEntity<String> forEntity = null;
        try {
            forEntity = restTemplate.getForEntity(url, String.class);
        } catch (ResourceAccessException e) {
            logger.info(e.getMessage());
            return HttpStatus.CHECKPOINT;
        }
        return forEntity.getStatusCode();
    }

    /**
     * @Description: postHttpStatus
     * @Param: [url 请求地址, queryParams url查询参数, bodyParam]
     * @Author: zhangyd
     */
    public HttpStatus postHttpStatus(String url, Map<String, Object> queryParams, Map<String, Object> bodyParam) {
        url = buildQueryParams(url, queryParams);
        if (StringUtils.isBlank(url))
            return null;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(JsonUtils.objectToJson(bodyParam), headers);
        ResponseEntity<String> forEntity = null;
        try {
            forEntity = restTemplate.postForEntity(url, formEntity, String.class);
        } catch (ResourceAccessException e) {
            logger.info(e.getMessage());
            return HttpStatus.CHECKPOINT;
        }
        return forEntity.getStatusCode();
    }

    /**
     * 注意 uriVariables 参数为 路径参数
     * ps:
     *
     * @GetMapping(value = "/demo/{id}/{name}")
     * public void demo(@PathVariable String id,@PathVariable String name){}
     */

    private String buildQueryParams(String urlStr, Map<String, Object> param) {
        if (StringUtils.isBlank(urlStr))
            return null;
        urlStr = urlStr.trim();
        if (param == null || param.size() == 0)
            return urlStr;
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlStr);
        MultiValueMap<String, String> valueMap = new LinkedMultiValueMap<>();
        param.forEach((k, v) -> {
            valueMap.addIfAbsent(k, v == null ? null : v.toString());
        });
        builder.queryParams(valueMap);
//        return builder.build().encode().toString();
        return builder.build().toString();
    }

    /**
     * 获取post请求结果
     *
     * @param url   请求地址
     * @param param 请求参数
     * @return 结果字符串
     */
    public String postForString(String url, Map<String, Object> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("Accept", "application/json");
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject(url, httpEntity, String.class);
        return result;
    }

}
