package com.jkcredit.invoice.util;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 敬众  MOBILE_CHECK_VIP
 * Created by zhangqingxin Date : 16/11/6 Time : 10:41
 * <p/>
 * 参考一(HttpClient)：http://mvnrepository.com/artifact/commons-httpclient/commons-
 * httpclient/3.1
 * 参考一(json-lib)：http://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4
 */
public class QueryDemo_3rd {

	/**
	 * 测试地址
	 */
	//	private static final String URL = " http://45.126.120.88/gateway?api=credit.sec.data_test"; 
	private static final String URL = "http://110.88.150.68:8000/gateway?api=credit.sec.data";

	/**
	 * 分配的appKey
	 */
	private static final String appKey = "DATA_TEST";

	static String filename = "/Users/mashengyi/Desktop/";
	static String logname = "编辑1.txt";

	/**
	 * 方法入口
	 *
	 * @param args
	 */

	public static void main(String args[]) throws Exception {

		QueryDemo_3rd demo = new QueryDemo_3rd();
		


		int count = 0;
		int total = 0;

		HashMap hashMap = new HashMap();
		
		try {
			File file = new File(filename + logname);
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			LineNumberReader lr = new LineNumberReader(isr, 512);
			String laststr = "";
			int count_d = 0;
			int total_d = 0;
			while (true) {

				String str = lr.readLine();

				try {
					if (str == null)
						break;

				/**	if(str.contains("18:")){
						continue;
					}
					if(str.contains("requestid")|| str.contains("未解密成功")){
						System.out.println(str);
					}

					if( str.contains("未解密成功")){
						System.out.println(str);
						continue;
					}
					String str1 = getsrt("\"msg\":\"", "\"", str);
					System.out.println(str1);**/

				String mobile = getsrt("mobile:", "idcard:", str).trim();
					
				String idcard = getsrt("idcard:", "name:", str).trim();

				String name = getsrt1("name:",str).trim();


				demo.runMainService(name,idcard,mobile);

				} catch (Exception e) {

					System.out.println("无法解析：" + str);
				}
			}
			lr.close();

		} catch (FileNotFoundException e) {
			System.out.println("FILENAME:" + filename);
			System.out.println("File not found");
		} catch (IOException e) {
			System.out.println("IO error");
		}

		Iterator it = hashMap.keySet().iterator();

		while (it.hasNext()) {

			String key = (String) it.next();
			Integer ttttttt = (Integer) hashMap.get(key);

			System.out.println(key + "====" + ttttttt);
		}

	}

	public static String getsrt(String startkeystr, String endstr, String str) {
		int customerindex = str.indexOf(startkeystr);
		String temp = str.substring(customerindex + startkeystr.length());
		int endindex = temp.indexOf(endstr);
		String sss = temp.substring(0, endindex);
		return sss;
	}

	public static String getsrt1(String startkeystr, String str) {
		int customerindex = str.indexOf(startkeystr);
		String temp = str.substring(customerindex + startkeystr.length());
		return temp;
	}

	/**
	 * 利用正则表达式判断字符串是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 调用主接口
	 */
	public void runMainService(String name,String idcard,String mobile) {
		try {
			/**
			 * 实名demo
			 */
			if(StringUtils.isEmpty(name) || StringUtils.isEmpty(idcard) || StringUtils.isEmpty(mobile)){

				System.out.println("未解密成功");

			}else{
				JSONObject paramJsonObj = initParamJsonObj_Realname(name,idcard,mobile);
				String ret = postClient(URL, paramJsonObj);
				System.out.println(ret);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 整合参数(实名认证)
	 *
	 * @return
	 */
	public JSONObject initParamJsonObj_Realname(String name,String idcard,String mobile) {
		/**
		 * 基本参数
		 */
		JSONObject paramJsonObj = new JSONObject();
		paramJsonObj.put("api", "CMCC_3RD_DETAIL_V20H");
		paramJsonObj.put("appKey", appKey);
		paramJsonObj.put("appSecret",
		 "C41DF125F0C23FBBB83E461F5045A30ACB3FF55A");
		 

		/**
		 * 业务参数
		 */
		JSONObject dataJson = initMainServiceParamJsonObj_Realname(name,idcard,mobile);
		paramJsonObj.put("data", dataJson);
		return paramJsonObj;
	}

	/*
	 * 初始化业务参数(实名认证)
	 *
	 * 姓名,身份证,手机号
	 *
	 * @return
	 */
	public JSONObject initMainServiceParamJsonObj_Realname(String name,String idcard,String mobile) {
		/**
		 * 具体业务参数放在data中
		 */
		JSONObject dataJson = new JSONObject();
		dataJson.put("name", name);
		dataJson.put("id_number", idcard);
		dataJson.put("mobile", mobile);
		dataJson.put("encrypt", "SHA256");
		return dataJson;
	}

	/**
	 * 实现http post请求 注意编码 UTF-8
	 *
	 * @param url
	 * @param paramObj
	 * @return
	 */
	public String postClient(String url, JSONObject paramObj) {
		String str = "";
		HttpClient client = null;
		PostMethod method = null;
		try {
			client = new HttpClient();
			method = new PostMethod(url);
			method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			NameValuePair[] param = new NameValuePair[paramObj.size()];
			Iterator<String> keys = paramObj.keys();
			int i = 0;
			while (keys.hasNext()) {
				String key = (String) keys.next();
				String value = paramObj.getString(key);
				param[i] = new NameValuePair(key, value);
				i++;
			}
			method.setRequestBody(param);
			client.executeMethod(method);
			str = convertStreamToString(method.getResponseBodyAsStream());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (method != null) {
				method.releaseConnection();
			}
		}
		return str;
	}

	/**
	 * 流转字符串
	 *
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder builder = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return builder.toString();
	}

}
