package com.ruoyi.common.utils.http.restTemplate;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Slf4j
public class InvokingService {
    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;

    /**
     * 服务调用，返回响应Body
     *
     * @param url
     * @param type
     * @param paramType 参数类型，若是post请求，且参数类型为'@RequestBody'时，需特殊处理
     * @param headerMap 参数类型，若是post请求，且参数类型为'@RequestBody'时，需特殊处理
     * @param paramMap  参数类型为'@RequestBody'时，参数Map中只放一个随意key即可，值为JSON字符串参数
     * @return
     */
    public String invServiceForResultData(String url, String type, String paramType, Map<String, String> headerMap, Map<String, String> paramMap) {
        try {
            String resultObj = "";
            HttpEntity requestEntity = buildRequestEntity(paramType, headerMap, paramMap);
            if ("GET".equalsIgnoreCase(type)) {
//                resultObj = restTemplate.getForObject(url, String.class);
                //借用exchange发送GET请求，设置请求头Header
                HttpEntity<String> httpEntityResult = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
                resultObj =httpEntityResult.getBody();
            } else if ("POST".equalsIgnoreCase(type)) {
                resultObj = restTemplate.postForObject(url, requestEntity, String.class);
            } else if ("PUT".equalsIgnoreCase(type) || "DELETE".equalsIgnoreCase(type)) {
                ResponseEntity<String> responseEntity = restTemplate.exchange(url, choiceHttpMethod(type), requestEntity, String.class);
                resultObj = responseEntity.getBody();
            }
            return resultObj;
        } catch (Exception e) {
//            JSONObject errorObj = new JSONObject();
//            errorObj.put("url", url);
//            errorObj.put("type", type);
//            Result result = new Result(ResultCodeEnum.C505, errorObj);
//            return JSONObject.fromObject(result).toString();
        }
        return null;
    }

    /**
     * 服务调用，返回响应体，可获取所有响应信息，如响应头，响应code等
     *
     * @param url
     * @param type
     * @param paramType
     * @param headerMap
     * @param paramMap
     * @return
     */
    public ResponseEntity<String> invServiceForResultEntity(String url, String type, String paramType, Map<String, String> headerMap, Map<String, String> paramMap) {
        try {
            ResponseEntity<String> responseEntity = null;
            HttpEntity requestEntity = buildRequestEntity(paramType, headerMap, paramMap);
            responseEntity = restTemplate.exchange(url, choiceHttpMethod(type), requestEntity, String.class);
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
//            JSONObject errorObj = new JSONObject();
//            errorObj.put("url", url);
//            errorObj.put("type", type);
//            throw new BizException(BizExceptionCodeEnum.INVOKING_ERROR, errorObj.toString());
        }
        return null;
    }

    /**
     * 构建http请求配置
     *
     * @param paramType
     * @param headerMap
     * @param paramMap
     * @return
     */
    public HttpEntity buildRequestEntity(String paramType, Map<String, String> headerMap, Map<String, String> paramMap) {
        HttpEntity requestEntity = null;
        HttpHeaders headers = setHeaders(headerMap);
        if (paramType != null && "BODY".equalsIgnoreCase(paramType)) {
            headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
            String param = "";
            if (null != paramMap) {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    param = entry.getValue();
                    break;
                }
            }
            requestEntity = new HttpEntity(JSONObject.parseObject(param), headers);
        } else {
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            if (null != paramMap) {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    params.add(entry.getKey(), entry.getValue());
                }
            }
            requestEntity = new HttpEntity(params, headers);
        }
        return requestEntity;
    }

    /**
     * 设置请求头部信息
     *
     * @param headerMap
     * @return
     */
    public HttpHeaders setHeaders(Map<String, String> headerMap) {
        HttpHeaders headers = new HttpHeaders();
        if (null == headerMap) {
            return headers;
        }
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            headers.set(entry.getKey(), entry.getValue());
        }
        return headers;
    }

    /**
     * 选择请求方式
     *
     * @param type
     * @return
     */
    public HttpMethod choiceHttpMethod(String type) {
        if ("GET".equalsIgnoreCase(type)) {
            return HttpMethod.GET;
        } else if ("POST".equalsIgnoreCase(type)) {
            return HttpMethod.POST;
        } else if ("PUT".equalsIgnoreCase(type)) {
            return HttpMethod.PUT;
        } else if ("DELETE".equalsIgnoreCase(type)) {
            return HttpMethod.DELETE;
        } else if ("HEAD".equalsIgnoreCase(type)) {
            return HttpMethod.HEAD;
        } else if ("PATCH".equalsIgnoreCase(type)) {
            return HttpMethod.PATCH;
        } else if ("OPTIONS".equalsIgnoreCase(type)) {
            return HttpMethod.OPTIONS;
        } else if ("TRACE".equalsIgnoreCase(type)) {
            return HttpMethod.TRACE;
        } else {
            return HttpMethod.POST;
        }
    }

}
