package com.house365.commons.system;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

/**
 * 访问外部接口的工具类
 * @author zhaodeshan
 * @version [版本号, 2015年1月31日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public final class RestUtil {
    private static final Logger LOG = LoggerFactory.getLogger(RestUtil.class);
    /**
     * 获取外部接口返回的JSON对象
     * @author zhaodeshan
     * @version [版本号, 2015年1月31日]
     * @param url 请求地址
     * @param queryParams 请求参数
     * @param claxx 要转换的对象类型
     * @return 对象
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     * @since [产品/模块版本](可选)
     */
    public static <T> T getForObject(String url,List<NameValuePair> queryParams,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException
    {
        if (StringUtils.isBlank(url)) {
            LOG.error("请求Url不能为空！");
            return null;
        }

        String result = getForString(url, queryParams);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(result, claxx);
    }

    /**
     * 直接获取外部接口返回的JSON字符串
     * @author zhaodeshan
     * @version [版本号, 2015年1月31日]
     * @param url 请求地址
     * @param queryParams 请求参数
     * @return JSON字符串
     * @since [产品/模块版本](可选)
     */
    public static String getForString(String url,List<NameValuePair> queryParams)
    {
        Client client = Client.create();
        client.setConnectTimeout(600000);
        client.setReadTimeout(600000);
        WebResource resource = client
                .resource(url);
        for (NameValuePair entry : queryParams) {
            resource = resource.queryParam(entry.getName(),entry.getValue()==null?"":entry.getValue());
        }
        String result = resource.get(String.class);
        client.destroy();

        return result;
    }

    public static String postForString(String url,MultivaluedMap<String, String> params)
    {
        Client client = Client.create();
        WebResource resource = client
                .resource(url);
        String result = resource.type(MediaType.APPLICATION_FORM_URLENCODED).post(String.class, params);
        client.destroy();

        return result;
    }

    public static <T> T postForObject(String url,MultivaluedMap<String, String> params,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException
    {
        if (StringUtils.isBlank(url)) {
            LOG.error("请求Url不能为空！");
            return null;
        }

        String result = postForString(url, params);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(result, claxx);
    }

    public static <T> List<T> postForList(String url,MultivaluedMap<String, String> params,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException, URISyntaxException
    {
        if (StringUtils.isBlank(url)) {
            LOG.error("请求Url不能为空！");
            return null;
        }
        String result = postForString(url, params);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(result,
                   mapper.getTypeFactory().constructCollectionType(
                       List.class, claxx));
    }

    /**
     * 获取外部接口返回的JSON Array对象
     * @author zhaodeshan
     * @version [版本号, 2015年1月31日]
     * @param url 请求地址
     * @param queryParams 请求参数
     * @param claxx 对象类型
     * @return List<T>
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     * @throws URISyntaxException
     * @since [产品/模块版本](可选)
     */
    public static <T> List<T> getForList(String url,List<NameValuePair> queryParams,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException, URISyntaxException
    {
        if (StringUtils.isBlank(url)) {
            LOG.error("请求Url不能为空！");
            return null;
        }
        String result = HttpClientUtil.doGet(url, queryParams);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(result,
                   mapper.getTypeFactory().constructCollectionType(
                       List.class, claxx));
    }
}
