package io.renren.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;


/**
 * 身份证识别
* 重要提示如下:
* 身份证OCR识别文档地址：https://market.aliyun.com/products/57124001/cmapi00051896.html
* 完整版请从 https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
public class IdCardUtils {
	private static Logger logger = LoggerFactory.getLogger(IdCardUtils.class); // 日志记录
	
	private static final String URL = "https://sidocr.market.alicloudapi.com/ocr/idcard";
	
	private static final String APPCODE = "6698454b70fa4f32af372006912e9a67";
	
	public static String doPost(Map<String, String> bodys) throws Exception {
		String result = null;
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(URL);
		try {
			httpPost.addHeader("Authorization", "APPCODE " + APPCODE);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	        if (bodys != null) {
	            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
	            for (String key : bodys.keySet()) {
	                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
	            }
	            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
	            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
	            httpPost.setEntity(formEntity);
	        }
	        HttpResponse response = httpClient.execute(httpPost);
	        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	           //String temp = "{\"msg\":\"\",\"orderno\":\"973627429421580288\",\"code\":200,\"data\":{\"birthday\":\"1996年11月24日\",\"idcard\":\"123456199611245678\",\"sex\":\"男\",\"issue\":\"区县级公安局名称\",\"address\":\"大庆市大庆区大庆路1号样例\",\"name\":\"小易\",\"nation\":\"汉\",\"expirydate\":\"\"}}";
	        	JSONObject parseObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
		       if(parseObject.get("code") != null && parseObject.getString("code").equals("200")) {
			       result = parseObject.getString("data");
			       //IDCardVo vo = JSONObject.parseObject(parseObject.getString("data"), IDCardVo.class);
			       //System.out.println(vo);
		       }else {
			       logger.error("调用身份证识别接口失败:"+ parseObject.get("msg"));
			       return null;
		       }
	        }else {
	        	logger.error("调用身份证识别接口失败:返回信息");
	        	logger.error("----------------");
	        	Header[] allHeaders = response.getAllHeaders();//X-Ca-Error-Message
	        	for (Header header : allHeaders) {
	        		logger.error(header.getName() + ":" + header.getValue());
				}
	        	logger.error("----------------");
	        }
		} catch (Exception e) {
			logger.error("调用身份证识别接口异常:", e);
		} finally {
            httpPost.releaseConnection();
        }
        return result;
    }
	
}
