package nc.pubitf.payablebill.yx;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.pubitf.payablebill.yx.ImageCommonConstant;
import nc.pubitf.payablebill.yx.ExceptionUtil;
import nc.bs.framework.json.core.exception.ExceptionUtils;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.vo.ws.esb.EsbinfoVO;
import sun.misc.BASE64Encoder;
/**
 * 影像采集接口
 * @author ll
 * @date 2021-05-27
 *
 */
@SuppressWarnings("restriction")
public class ImageCaptureAPI {
	
	private static BaseDAO dao = null;
	
	public static HashMap<String,Object> map = new HashMap<String,Object>(){
		{
			put(ImageCommonConstant.IMAGE_NCC_ERM, "上传影像系统待办");
			put(ImageCommonConstant.IMAGE_STATUS_UPDATE, "影像同步单据状态");
			put(ImageCommonConstant.IMAGE_NCC_VIEW, "获取影像调阅地址");
		}
	};
	
	/**
	 * 调用影像系统接口
	 * @param jSONObject 传输报文
	 * @param code	影像接口在NCC系统注册编码
	 * @return
	 * @throws DAOException 
	 */
	public static JSONObject postRequest(JSONObject jSONObject, String code) throws DAOException {
		String sql = "select * from bgy_esbinfo where code = ?";
		SQLParameter params = new SQLParameter();
		params.addParam(code);
		List<EsbinfoVO> esbinfoVOs = (List<EsbinfoVO>) getDao().executeQuery(sql, params, new BeanListProcessor(EsbinfoVO.class));
		
		// 接口注册校验
		ExceptionUtil.isTrue(null == esbinfoVOs || 1 > esbinfoVOs.size(), map.get(code) + "接口未注册，请联系用友顾问!");
		EsbinfoVO esbinfoVO = esbinfoVOs.get(0);
		
		// 接口启用校验
		String isstart = esbinfoVO.getIsstart();
		ExceptionUtil.isTrue(StringUtils.isBlank(isstart) || !"1".equals(isstart), map.get(code) + "接口未启用，请联系用友顾问!");
		
		// 接口URL校验
		String url = esbinfoVO.getUrl();
		ExceptionUtil.isTrue(StringUtils.isBlank(url), map.get(code) + "接口URL为空，请联系用友顾问!");
		
		
		// clientId:clientSecret校验
		String def1 = esbinfoVO.getDef1();
		ExceptionUtil.isTrue(StringUtils.isBlank(def1), "clientId:clientSecret为空，请联系用友顾问!");
		
		// Basic Auth认证头信息校验
		ExceptionUtil.isTrue(null == getHeader(def1),"base64编码失败，请联系用友顾问!");
		
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(10000) //连接超时时间
                .setConnectionRequestTimeout(10000) //从连接池中取的连接的最长时间
                .setSocketTimeout(30000) //数据传输的超时时间
                .build();
        //设置请求配置时间
		post.setConfig(config);
		StringEntity myEntity = new StringEntity(JSONObject.toJSONString(jSONObject), ContentType.APPLICATION_JSON);// 构造请求数据
		post.addHeader("Authorization", getHeader(def1));
	    post.setEntity(myEntity);// 设置请求体
	    String responseContent = null; // 响应内容
	    CloseableHttpResponse response = null;
		try {
			response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				responseContent = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
//			e.printStackTrace();
			ExceptionUtils.wrapException(e);			
		} catch (IOException e) {
//			e.printStackTrace();
			ExceptionUtils.wrapException(e);
		} finally {
			try {
				if (response != null)
					response.close();
			} catch (IOException e) {
//				e.printStackTrace();
				ExceptionUtils.wrapException(e);
			} finally {
				try {
					if (client != null)
						client.close();
				} catch (IOException e) {
//					e.printStackTrace();
					ExceptionUtils.wrapException(e);
				}
			}
		}
		return JSONObject.parseObject(responseContent);
	}
	
	private static BaseDAO getDao() {
		if(null == dao) {
			dao = new BaseDAO();
		}
		return dao;
	}
	
	/**
	 * 构造Basic Auth认证头信息
	 * @param auth
	 * @return
	 */
	@SuppressWarnings("restriction")
	private static String getHeader(String auth) {
		BASE64Encoder ecoder = new BASE64Encoder();
		try {
			String encodedAuth = ecoder.encode(auth.getBytes("UTF-8"));
			return "Basic " + encodedAuth;
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
	
	
//	public static void main(String[] args) {
//		System.out.println(getHeader("bgyfw_ybz_test:PGF95VnClEudW5VapUe"));
//	}
	
}