package cn.pluss.platform.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

public class WeChatMerchantRegistUtil {

	//必须参数
	private String version="3.0";//接口版本号
	private String cert_sn="4F3FF2964275BA2D2D8320BC8187FB3E18D22DFE";//平台证书序列号
	private String mch_id="1551169371";//商户号
	private String nonce_str="ibuaiVcKdpRxkhJA";//随机字串
	private String sign_type="HMAC-SHA256";//签名类型
	private String sign="";//签名
	private String business_code="814160525";//业务申请编号
	private String id_card_copy = "uJylNilvwIro6TBgJGM-9Xo4GA_5bAWOrStBa7qYmDU8055I2W75tG9ogJjhcEJBNGAB64g7uZcFcR9oqP2wuhgitBHYTKBwFoML3Snd9p8";//身份证人像面照片
	private String id_card_national = "uJylNilvwIro6TBgJGM-9avd2QA3zCP5GL1H_q9dbC0jPBDFVINWYQF0jYSGlJ3ITYH8Vo2dnR6eYKLM8v2aX_CZWmHS80Fi9CrIejrjC5o";//身份证国徽面照片
	private String id_card_name = "fDPD1jyt2fFMIeL65aHV3wQu2CbOViddiNM5bo3ulMCgYpWH8N0d00Z75OB9hIjQnSHcmRHKZ8mjEK8tnQ+ndwWlD3/oNWrBJfn9mPD/98KUAcwGeg5HlpdTN9LuucLdTYBYuZvOsr3UBsYU08lVguKPedA7Tm8HUNg2YAgvysm5BGkWjLC+xngg4fsUaLyDav+z1K4zpT64vqGFkVNsvb8e7R96B6IxI6/ifknccpvwMiB91i101rDF+mMHsoJXwXOCRqD84w4ntljhSJwK4U+AsVlXf6dK7VsrX4bJLkmB4zIxEMnZuFB9oUCgrPOw/fVA88fzzNY9JsNbR97+QA==";//身份证姓名 钱志国
	private String id_card_number = "FfByA2mz+4Orx/nRL2kAdV3x6vmmY1n4NDGxYRQpvGjq4myv12kSKTppxmTQUR5w+T2tfKytEfAdMAaak4DYh4+QzEQ9MF7YIbATKfMHBvUbYOKrvsh8BrWsTErMdZleqkWDh3xhYweCVkML+k5AcYOidyQ2VlRPnd1oRC7GOnwqV1bQynZXDvWQiHW8zC9jC/KwcD3uFtQS1ODr8ijQIEkKviwxQRD9aawYx+4BnuozVfh27A8ADtB+2vQNlVgQDR1Lxe2D9IOtVc1IAf2ktkDMXU2nFnwiGUDCV1NmiQeiVdwZhZGKPbYC8q7ItftjXBenO7cAHn0g8eiV6hnWDg==";//身份证号码 340121198510055215
	private String id_card_valid_time = "[\"2016-08-01\",\"2036-08-01\"]";//身份证有效期限
	private String account_name = "hxODtW+jc9sU27HNdVOFAPDe2Vk38d6Kkp4zKbSt3wsO+pFKezi3K2Gy8SM2keE9VkZTS86HLfFT20yuFzy0uXd3auZKwZezBIhsdG660BvQ29/sZvZAuuPNB+UfarG9aXZXE0SIyUTaMfJyqhzpZHPUfBNGXRJhPHJI0jJsq67RqhYyDSWIKMRBDmhgH0ukNN734mxMglcOSURKL2lJrSG/jk64Iz1bh7rZ7vk7QU6JVlls/juDWfWdcS2SpyzJ0WX/77sfhd73lDZP5xwVAUDf/5d7GfVN2JAlDolAOjbVGeqdRbnbNG0+aSLshdkdKDaRpThdzN+4cMIyPW0IGg==";//开户名称
	private String account_bank = "招商银行";//开户银行
	private String bank_address_code = "340103";//开户银行省市编码
	private String bank_name = "招商银行合肥分行营业部";//开户银行全称（含支行）
	private String account_number = "Gapag31cSFQN7AKDOv5uwKLvYVHyOHvF0WhJTAZXdtRs6P3uJ5zVzZGp2UAgYBL4WhTUvVMb6f0h74njeSSRs4uVZuwhQ9xbLn/DKDOFdpfZabV9wnG4pdPWWz2qQuWFj8uZlFrevMoWAbAHyNtSaFkK2mMMjNAD00Zi+/3M1pkZKTb9SFE1lyFBnfm0pbvRWq66FCrwZSN0wjx6o8hJB10s69/+Pf/f/O4ayd0hLnblAGc2aB0MZygmRsFMIADVsI99iYeJ+5u8mJ9zA+ojy8DejO8DH049S1exxBSVZBDvOMI/OIlJkPRacNFZx2dAzjvn6m3eFGlOqoYGYs9+XQ==";//银行账号
	private String store_name = "八分菜馆";//门店名称
	private String store_address_code = "340103";//门店省市编码
	private String store_street = "庐阳区固镇路188号海棠别院3幢101/101(上)室";//门店街道名称
	private String store_entrance_pic = "uJylNilvwIro6TBgJGM-9WFbxyINH2wsT2G8W7WwisecJVrf9KczrkDpf-KD2l3qLSYdaANbOq5uAZsuZtw2JQWqbR6AZ7UIdd2RYSOrzZc";//门店门口照片
	private String indoor_pic = "uJylNilvwIro6TBgJGM-9cbPVSGY8948VHFSnRhsuqjbIRKSolQ-Gcc8Wwu-BkYpdEl9HFmdq46UmAPZ2KMliF0HyBrhKpbuRWAn8FuxMC8";//店内环境照片
	private String merchant_shortname = "八分菜馆";//商户简称
	private String service_phone = "18714898998";//客服电话
	private String product_desc = "餐饮";//售卖商品/提供服务描述
	private String rate = "0.6%";//费率
	private String contact = "fDPD1jyt2fFMIeL65aHV3wQu2CbOViddiNM5bo3ulMCgYpWH8N0d00Z75OB9hIjQnSHcmRHKZ8mjEK8tnQ+ndwWlD3/oNWrBJfn9mPD/98KUAcwGeg5HlpdTN9LuucLdTYBYuZvOsr3UBsYU08lVguKPedA7Tm8HUNg2YAgvysm5BGkWjLC+xngg4fsUaLyDav+z1K4zpT64vqGFkVNsvb8e7R96B6IxI6/ifknccpvwMiB91i101rDF+mMHsoJXwXOCRqD84w4ntljhSJwK4U+AsVlXf6dK7VsrX4bJLkmB4zIxEMnZuFB9oUCgrPOw/fVA88fzzNY9JsNbR97+QA==";//超级管理员姓名
	private String contact_phone = "E7JkGhddjlL55q37LuPYsQtT40hAqkN/z/eFyFaN9MxdRUtPRlocX3xO6NNs0QzapWNOH383G+WZeEXOPH8Yk0TxBClFv1+iZWEBKoTr8w0Df4NjuDMvnpXDMwPaDklDENfJwzhlcpC3eARr0YDhQtqwOmPEtmrmEeoOrZjuqeN8TmCSkvIxLT/8lVAfW/c+IZRZ4Uh0i0HQiPBPjSouBgOG2b+B09IbG2C7EuMDortjfBvt43cvw7pRPJOeFr3USxf6JkQNIhLJUnRLYGgBIBB9MoVtqYe8h+YJZWnkndlSGjnYdyEypSviWd3Iw9dnblSQ0RasGJE4l422VEg/ew==";//手机号码
	private String contact_email = "814160525@qq.com";//联系邮箱
	
	
	
	
	//选填参数
	private String store_longitude = "";//门店经度
	private String store_latitude = "";//门店纬度
	private String address_certification = "";//经营场地证明
	private String business_addition_desc = "";//补充说明
	private String business_addition_pics = "";//补充材料
	
	//接口请求地址
	private static String requestUrl = "https://api.mch.weixin.qq.com/applyment/micro/submit";
	private static String payKey = "7F05NZBTJ3XNDK5HLSDC3H25ZXOQKDHT";
	private static String keyStoreUrl = "D:\\WeChatMerchantTool\\apiclient_cert.p12";
	
	public void regist() throws ClientProtocolException, IOException {
		
		        // 初始化一个HttpClient
				//CloseableHttpClient httpClient = HttpClients.createDefault();
				// Post请求
				HttpPost httpPost = new HttpPost(requestUrl);
				/**
				 * 这边需要您提供微信分配的商户号跟API密钥
				 */
				
				Map<String, String> param = new HashMap<>(4);
				param.put("version", version);
				param.put("cert_sn", cert_sn);
				param.put("mch_id", mch_id);
				param.put("nonce_str", nonce_str);
				param.put("sign_type", sign_type);
				param.put("business_code", business_code);
				param.put("id_card_copy", id_card_copy);
				param.put("id_card_national", id_card_national);
				param.put("id_card_name", id_card_name);
				param.put("id_card_number", id_card_number);
				param.put("id_card_valid_time", id_card_valid_time);
				param.put("account_name", account_name);
				param.put("account_bank", account_bank);
				param.put("bank_address_code", bank_address_code);
				//param.put("bank_name", bank_name);
				param.put("account_number", account_number);
				param.put("store_name", store_name);
				param.put("store_address_code", store_address_code);
				param.put("store_street", store_street);
				param.put("store_entrance_pic", store_entrance_pic);
				param.put("indoor_pic", indoor_pic);
				param.put("merchant_shortname", merchant_shortname);
				param.put("service_phone", service_phone);
				param.put("product_desc", product_desc);
				param.put("rate", rate);
				param.put("contact", contact);
				param.put("contact_phone", contact_phone);
				//param.put("contact_email", contact_email);
				String sign = WechatSignUtil.sha256Sign(param, payKey);
				param.put("sign", sign);
				// 声明存放参数的List集合
	            List<NameValuePair> params = new ArrayList<NameValuePair>();

	            // 遍历map，设置参数到list中
	            for (Map.Entry<String, String> entry : param.entrySet()) {
	                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
	            }
	            
	            
	            // 创建form表单对象
	            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
	    		//httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.getMimeType());
	            
	            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
	            multipartEntityBuilder.addTextBody("version", version);
	            multipartEntityBuilder.addTextBody("cert_sn", cert_sn);
	            multipartEntityBuilder.addTextBody("mch_id", mch_id);
	            multipartEntityBuilder.addTextBody("nonce_str", nonce_str);
	            multipartEntityBuilder.addTextBody("sign_type", sign_type);
	            multipartEntityBuilder.addTextBody("business_code", business_code);
	            multipartEntityBuilder.addTextBody("id_card_copy", id_card_copy);
	            multipartEntityBuilder.addTextBody("id_card_national", id_card_national);
	            multipartEntityBuilder.addTextBody("id_card_name", id_card_name);
	            multipartEntityBuilder.addTextBody("id_card_number", id_card_number);
	            multipartEntityBuilder.addTextBody("id_card_valid_time", id_card_valid_time);
	            multipartEntityBuilder.addTextBody("account_name", account_name);
	            multipartEntityBuilder.addTextBody("account_bank", account_bank);
	            multipartEntityBuilder.addTextBody("bank_address_code", bank_address_code);
	            //multipartEntityBuilder.addTextBody("bank_name", bank_name);
	            multipartEntityBuilder.addTextBody("account_number", account_number);
	            multipartEntityBuilder.addTextBody("store_name", store_name);
	            multipartEntityBuilder.addTextBody("store_address_code", store_address_code);
	            multipartEntityBuilder.addTextBody("store_street", store_street);
	            multipartEntityBuilder.addTextBody("store_entrance_pic", store_entrance_pic);
	            multipartEntityBuilder.addTextBody("indoor_pic", indoor_pic);
	            multipartEntityBuilder.addTextBody("merchant_shortname", merchant_shortname);
	            multipartEntityBuilder.addTextBody("service_phone", service_phone);
	            multipartEntityBuilder.addTextBody("product_desc", product_desc);
	            multipartEntityBuilder.addTextBody("rate", rate);
	            multipartEntityBuilder.addTextBody("contact", contact);
	            multipartEntityBuilder.addTextBody("contact_phone", contact_phone);
	            //multipartEntityBuilder.addTextBody("contact_email", contact_email);
	            multipartEntityBuilder.addTextBody("sign", sign);
	            
	            
	    		FileInputStream instream = null;
				SSLContext sslcontext = null;
				try {
					KeyStore keyStore = KeyStore.getInstance("PKCS12");
					instream = new FileInputStream(new File(keyStoreUrl));
					keyStore.load(instream, mch_id.toCharArray());// 这里写密码..默认是你的MCHID
					sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
				} catch (Exception e) {
					System.out.println(e.getMessage());
				} finally {
					try {
						if (instream != null) {
							instream.close();
						}
					} catch (IOException e) {

					}
				}
				@SuppressWarnings("deprecation")
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
						null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
				CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
				try {
					RequestConfig config = RequestConfig.custom().setConnectTimeout(10000)
							.setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
					httpPost.setConfig(config);
					//// 这里的Content-type要设置为"multipart/form-data"，否则返回“参数填写有误，请检查后重试”
					httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=utf-8");
					StringEntity postEntity = new StringEntity(WXPayXmlUtil.parseMapToXML(param), "UTF-8");
					httpPost.setEntity(postEntity);
					CloseableHttpResponse response = httpclient.execute(httpPost);
					String result = EntityUtils.toString(response.getEntity(), "UTF-8");
					System.out.println(result);
				}
				catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
	}
	
	
}
