package com.tykj.workflowcore.user.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

/**
 * @author HuangXiahao
 * @version V1.0
 * @class HttpUtil
 * @packageName com.tykj.support.misc.util
 **/

@Component
@Slf4j
public class HttpUtil {

    @Resource
    CookieStore cookieStore;

    private CloseableHttpClient getClient() {
        return SpringUtils.getBean("client");
    }

    public CloseableHttpResponse request(HttpMethodName methodName, String uri, String param, Header[] headers){
        CloseableHttpResponse response = null;
        HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase = new HttpEntityEnclosingRequestBase() {
            @Override
            public String getMethod() {
                return methodName.toString();
            }
        };
        try {
            httpEntityEnclosingRequestBase.setURI(new URI(uri));
            if (param!=null){
                httpEntityEnclosingRequestBase.setEntity(new StringEntity(param));
            }
            httpEntityEnclosingRequestBase.setHeaders(headers);
            response = getClient().execute(httpEntityEnclosingRequestBase);
            return response;
        } catch (Exception e) {
            log.error("请求接口出现错误,参数为：methodName"+methodName+"uri:"+uri+"param:"+param);
            throw new ApiException("请求接口出现错误");
        }
    }

    public String closeableHttpResponse2String(CloseableHttpResponse response){
        InputStream responseStream = null;
        try {
            responseStream = response.getEntity().getContent();
            return IOUtils.toString(responseStream,"utf-8");
        } catch (IOException e) {
            log.error("解析Api返回值出现错误");
            throw new ApiException("解析Api返回值出现错误,请求的Api发生错误");
        }
    }


    public enum HttpMethodName{

         GET,POST,PUT,DELETE;

         public static HttpMethodName get(String str){
             if (str.equals(GET.toString())){
                 return GET;
             }
             if (str.equals(POST.toString())){
                 return POST;
             }
             if (str.equals(PUT.toString())){
                 return PUT;
             }
             if (str.equals(DELETE.toString())){
                 return DELETE;
             }
             throw new ApiException("该API的请求参数不正确，请联系管理员");
         }
    }
}
