package abacus.springboot.example.util;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;

import com.abacus.xpos.foundation.pubs.WebserviceException;
import com.alibaba.fastjson.JSONObject;

/**
 * <p>Title:RequestUtil</p>
   <p>Description: http-工具</p>
   @author chuanZeng 
   @date 2026年8月18日
 */
public class RequestUtil {
	private static final int connectTimeout = 5000; 			// 连接超时时间
	private static final int connectionRequestTimeout = 5000;	// 请求超时时间
	private static final int socketTimeout = 5000;				// 套接字连接超时(读取超时时间)
	
	public static final String charset = "utf-8";				// 编码方式
	
	/**
	 * post Json提交
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws WebserviceException 
	 */
	public static String send(String url ,String jsonStr, String id) throws WebserviceException{
			
			HttpClientParams params = new HttpClientParams();
			params.setContentCharset("UTF-8");
			
			HttpClient hc = new HttpClient(params,new SimpleHttpConnectionManager(true));
			hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			hc.getHttpConnectionManager().getParams().setSoTimeout(5000);
			PostMethod hm = new PostMethod(url);
			hm.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
			try {
				System.out.println(DateUtil.getDateTime()+"-"+ id + "-url:"+url);
				hm.setRequestEntity(new StringRequestEntity(jsonStr, "application/json", "utf-8"));
				System.out.println(DateUtil.getDateTime()+"-"+ id + "-send报文:" + jsonStr.toString());
				int status = hc.executeMethod(hm);
				if(status == HttpStatus.SC_OK) {
					String temp = hm.getResponseBodyAsString();
					System.out.println(DateUtil.getDateTime()+"-"+ id +  "-resp data:"+temp);
					return temp ;
				}else{
					throw new WebserviceException("请求出错!");
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(e.getMessage());
				throw new WebserviceException(e.getMessage());
			}finally {
				hm.releaseConnection();
			}
	}
	
	/**
	 * POST 键值对提交
	 * @param url
	 * @param paramsMap
	 * @return
	 * @throws WebserviceException 
	 */
	public static String sendParams(String url ,Map<String,Object> paramsMap, String id) throws WebserviceException{
		
		HttpClientParams params = new HttpClientParams();
		params.setContentCharset("UTF-8");
		
		HttpClient hc = new HttpClient(params,new SimpleHttpConnectionManager(true));
		hc.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
		hc.getHttpConnectionManager().getParams().setSoTimeout(10000);
		PostMethod hm = new PostMethod(url);
//		GetMethod gm = new GetMethod(url);
		hm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		
		Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);   
		Protocol.registerProtocol("https", myhttps);
		
		try {
			for(String key : paramsMap.keySet()){
				hm.addParameter(key, paramsMap.get(key).toString());
			}
			System.out.println(DateUtil.getDateTime()+">>>" + id + ">>>url>>>" + url
					+ ">>>sendParams报文>>>" + paramsMap.toString());
			int status = hc.executeMethod(hm);
			if(status == HttpStatus.SC_OK) {
				String temp = hm.getResponseBodyAsString();
				System.out.println(DateUtil.getDateTime()+">>>" + id  + ">>>resp data>>>"+ JSONObject.parseObject(temp));
				return temp ;
			}else{
				throw new WebserviceException("请求出错!"+status);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			throw new WebserviceException(e.getMessage());
		}finally {
			hm.releaseConnection();
		}
	}
	
	public static String sendGet(String url) throws WebserviceException{
		
		HttpClientParams params = new HttpClientParams();
		params.setContentCharset("UTF-8");
		
		HttpClient hc = new HttpClient(params,new SimpleHttpConnectionManager(true));
		hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		hc.getHttpConnectionManager().getParams().setSoTimeout(5000);
		GetMethod getMethod = new GetMethod(url);
		getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		try {
			System.out.println("url:"+url);
			
			int status = hc.executeMethod(getMethod);
			
			if(status == HttpStatus.SC_OK) {
				String temp = getMethod.getResponseBodyAsString();
				System.out.println("resp data:"+temp);
				return temp ;
			}else{
				throw new WebserviceException("请求出错!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			throw new WebserviceException(e.getMessage());
		}finally {
			getMethod.releaseConnection();
		}
	}
	
	public static String postHttp(String urls, NameValuePair[] nvp) throws Exception {
		try {
			String result = "";
			// 定义http客户端对象--httpClient
			HttpClient httpClient = new HttpClient();
			// 定义并实例化客户端链接对象-postMethod
			PostMethod postMethod = new PostMethod(urls);
			httpClient.setConnectionTimeout(5000);

			try {

				postMethod.setRequestHeader("application/json", "UTF-8");

				postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

				// 将表单的值放入postMethod中
				postMethod.addParameters(nvp);
				// 定义访问地址的链接状态
				int statusCode = 0;
				try {
					// 客户端请求url数据
					statusCode = httpClient.executeMethod(postMethod);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 请求成功状态-200
				if (statusCode == HttpStatus.SC_OK) {
					try {
						result = postMethod.getResponseBodyAsString();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {

				}

			} catch (Exception e) {

			} finally {
				// 释放链接
				postMethod.releaseConnection();
				httpClient.getHttpConnectionManager().closeIdleConnections(0);
			}
			return result;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static String getHttp(String urls, NameValuePair[] nvp) throws Exception {
		try {
			String result = "";
			// 定义http客户端对象--httpClient
			HttpClient httpClient = new HttpClient();

			// 定义并实例化客户端链接对象-postMethod
			GetMethod getMethod = new GetMethod(urls);

			try {
				// 设置http的头

				// （1）、这里可以设置自己想要的编码格式
				getMethod.getParams().setContentCharset("utf-8");

				// （2）、对于get方法也可以这样设置
				getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

				// （3）、还可以如下这样设置
				getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");

				getMethod.setQueryString(nvp);

				// 定义访问地址的链接状态
				int statusCode = 0;
				try {
					// 客户端请求url数据
					statusCode = httpClient.executeMethod(getMethod);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 请求成功状态-200
				if (statusCode == HttpStatus.SC_OK) {
					try {
						result = getMethod.getResponseBodyAsString();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {

			} finally {
				// 释放链接
				getMethod.releaseConnection();
				httpClient.getHttpConnectionManager().closeIdleConnections(0);
			}
			return result;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static void main(String[] args) {
		// 验证设备唯一码,验证设备分配账户号
//		Map<String, Object> paramsMap = new HashMap<String, Object>();
//		paramsMap.put("error_code","1");
//		paramsMap.put("msg","TRUE1");
//		paramsMap.put("data","{\"Result\":{\"ResponseStatus\":{\"ErrorCode\":500,\"IsSuccess\":false,\"Errors\":[{\"FieldName\":null,\"Message\":\"插件取消了保存操作，可能因为数据不合法。\",\"DIndex\":0}],\"SuccessEntitys\":[],\"SuccessMessages\":[],\"MsgCode\":0},\"Id\":\"\",\"NeedReturnData\":[{}]}}");
//
//		List<Map<String, Object>> mapl = new ArrayList<Map<String, Object>>();
//		mapl.add(paramsMap);
//		
//		String str = JSONObject.toJSONString(mapl);
//		System.out.println(str);
//		
////		JSONObject jsonObject = JSONObject.parseObject(str);
//		JSONArray jsonObject = JSONArray.parseArray(str);
//		
//		System.out.println(jsonObject.getJSONObject(0).getString("data"));
//		
//		JSONObject jsonObjects = JSONObject.parseObject(jsonObject.getJSONObject(0).getString("data")).getJSONObject("Result").getJSONObject("ResponseStatus");
//		
//		String message = jsonObjects.getInteger("ErrorCode") + ":" + jsonObjects.getJSONArray("Errors").getJSONObject(0).getString("Message");
//		String FieldName = jsonObjects.getInteger("ErrorCode") + ":" + jsonObjects.getJSONArray("Errors").getJSONObject(0).getString("FieldName");
//		
//		System.out.println(message);
//		System.out.println(FieldName);
		
//		String context = "{\"type\":1,\"batchNub\":\"\",\"qctype\":2,\"prodNumber\":\"10401000006\",\"qrcode\":[\"https%3a%2f%2fbetascan.vats.com.cn%2fscan%2f3%2f001f3618fd5d4d1d84125c04d5c2ebe6\",\"https://betascan.vats.com.cn/scan/3/002f3618fd5d4d1d84125c04d5c2ebe6\",\"https://betascan.vats.com.cn/scan/3/003f3618fd5d4d1d84125c04d5c2ebe6\"],\"operateUser\":\"47\",\"companyCode\":\"25\"}";
//		try {
////			String map1 = new RequestUtil().send("https://apistest.vatsliquor.com/hzztlgs/addProductQrcode?token=aHp6dC0xNTY2Mjc4OTcwMTE5LXZhdHM_", context);
//		
////			System.out.println(map1);
//		} catch (WebserviceException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
		
		
		
//		if("1".equals(jsonObject.get("error_code")) || "TRUE".equals(jsonObject.get("msg"))) {
//			System.out.println(jsonObject.get("data"));
//		}
		
	}
	
}
