/* 
 * Copyrights 尚果科技平台研发项目组 @ 2015，尚果科技 SEOCOO Computer Co., Ltd.<br>
 * 项目名称：尚果科技-平台开发组 <br>
 * 文件名称：WeiXinUtil.java <br>
 * 创建时间：2015-6-15-下午02:32:32 <br>
 * Description： 
 * History：<br> [ Author Date Version Content ]<br>
 *  
 */
package cn.pluss.platform.wechat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.util.MD5Util;

public class WeiXinUtil {

	 private static final Logger logger = LoggerFactory.getLogger( WeiXinUtil.class);
		

		
		public static PayNotify xmlToPayNotify(String msg){
			PayNotify payNotify=new PayNotify();
			try {
				Document doc = DocumentHelper.parseText(msg);
				Element root = doc.getRootElement();
				String return_code = root.element("return_code").getTextTrim();
				
				
				if(Constant.RESULT_CODE_SUCCESS.equals(return_code)){
					
					String result_code = root.element("result_code").getTextTrim();
					
					if(Constant.RESULT_CODE_SUCCESS.equals(result_code)){
						
						
						String appid = root.element("appid").getTextTrim();
						String mch_id = root.element("mch_id").getTextTrim();
						String nonce_str = root.element("nonce_str").getTextTrim();
						String sign = root.element("sign").getTextTrim();
						String openid = root.element("openid").getTextTrim();
						String is_subscribe = root.element("is_subscribe").getTextTrim();
						String trade_type = root.element("trade_type").getTextTrim();
						
//						String trade_state_desc = root.element("trade_state_desc").getTextTrim();
						String bank_type = root.element("bank_type").getTextTrim();
						String total_fee = root.element("total_fee").getTextTrim();
						String transaction_id = root.element("transaction_id").getTextTrim();
						String out_trade_no = root.element("out_trade_no").getTextTrim();
						String time_end = root.element("time_end").getTextTrim();
						payNotify.setAppid(appid);
						payNotify.setBank_type(bank_type);
						payNotify.setIs_subscribe(is_subscribe);
						payNotify.setMch_id(mch_id);
						payNotify.setNonce_str(nonce_str); 
						payNotify.setOpenid(openid);
						payNotify.setOut_trade_no(out_trade_no);
						payNotify.setResult_code(result_code);
						payNotify.setReturn_code(return_code);
						payNotify.setSign(sign);
						payNotify.setTime_end(time_end);
						payNotify.setTotal_fee(total_fee);
						payNotify.setTrade_type(trade_type);
//						payNotify.setTrade_state_desc(trade_state_desc);
						payNotify.setTransaction_id(transaction_id);
						
					}else{
						payNotify.setReturn_code("FAIL");
						payNotify.setReturn_msg("支付回调接口返回数据错误");
						System.out.println("支付回调接口返回数据错误");
					}
					
					
				}else{
					//协议错误
					String return_msg = root.element("return_msg").getTextTrim();
					payNotify.setReturn_code("FAIL");
					payNotify.setReturn_msg(return_msg);
					System.out.println("支付回调接口协议数据错误");
				}
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				payNotify.setReturn_code("FAIL");
				payNotify.setReturn_msg("支付回调接口返回数据错误");
				System.out.println("支付回调接口返回数据错误");
			}   
			
			return payNotify;
			
		}
		
		/**
		 * 解析调用统一支付接口响应报文
		 * @param msg
		 * @return
		 */
		public static PayNotify xmlToPayNotifyResponse(String msg){
			
			PayNotify payNotify=new PayNotify();
			try {
				Document doc = DocumentHelper.parseText(msg);
				Element root = doc.getRootElement();
				String return_code = root.element("return_code").getTextTrim();
				
				
				if(Constant.RESULT_CODE_SUCCESS.equals(return_code)){
					
					String result_code = root.element("result_code").getTextTrim();
					
					if(Constant.RESULT_CODE_SUCCESS.equals(result_code)){
						
						String appid = root.element("appid").getTextTrim();
						String mch_id = root.element("mch_id").getTextTrim();
						String nonce_str = root.element("nonce_str").getTextTrim();
						String code_url = root.element("code_url").getTextTrim();
						String sign = root.element("sign").getTextTrim();
						String trade_type = root.element("trade_type").getTextTrim();
						String prepay_id = root.element("prepay_id").getTextTrim();
						String return_msg = root.element("return_msg").getTextTrim();
						payNotify.setAppid(appid);
						payNotify.setMch_id(mch_id);
						payNotify.setNonce_str(nonce_str); 
						payNotify.setPrepay_id(prepay_id);
						payNotify.setCode_url(code_url);
						payNotify.setResult_code(result_code);
						payNotify.setReturn_code(return_code);
						payNotify.setSign(sign);
						payNotify.setTrade_type(trade_type);
						payNotify.setReturn_msg(return_msg);
						
					}else{
						//协议错误
						String return_msg = root.element("return_msg").getTextTrim();
						payNotify.setReturn_code("FAIL");
						payNotify.setReturn_msg(return_msg);
						System.out.println("统一下单回调接口协议数据错误");
					}
					
				}else{
					//协议错误
					String return_msg = root.element("return_msg").getTextTrim();
					payNotify.setReturn_code("FAIL");
					payNotify.setReturn_msg(return_msg);
					System.out.println("统一下单回调接口协议数据错误");
				}
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				payNotify.setReturn_code("FAIL");
				payNotify.setReturn_msg("统一下单回调接口返回数据错误");
				System.out.println("统一下单回调接口返回数据错误");
			}   
			
			return payNotify;
		}
		
		
		//生成签名
		public static String paySign(String pKey2, String packageMsg, String appId2,String timeMillis, String appSecret2, String nonceStr,String signType) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("appId", appId2);
			param.put("timeStamp", timeMillis);
			param.put("nonceStr", nonceStr);
			param.put("package", packageMsg);
			param.put("signType", signType);
			//去除空串
			Map<String, String> array = MicroPayCore.paraFilter(param);
			//排序生成签名
			String paySign = MicroPayCore.buildMysign(array, pKey2);
			return paySign;
				
		}
		//生成预支付订单签名
		public static String paySign(String pKey2,String return_code,String return_msg, String appid, 
				String mch_id,String nonce_str, String prepay_id, String result_code,String err_code_des,String signType) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("return_code", return_code);
			param.put("return_msg", return_msg);
			param.put("appid", appid);
			param.put("mch_id", mch_id);
			param.put("nonce_str", nonce_str);
			param.put("prepay_id", prepay_id);
			param.put("result_code", result_code);
			param.put("err_code_des", err_code_des);
			param.put("signType", signType);
			//去除空串
			Map<String, String> array = MicroPayCore.paraFilter(param);
			//排序生成签名
			String paySign = MicroPayCore.buildMysign(array, pKey2);
			return paySign;
			
		}
		//模式二生成预支付订单签名
		   public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {  
		        StringBuffer sb = new StringBuffer();  
		        Set es = packageParams.entrySet();  
		        Iterator it = es.iterator();  
		        while (it.hasNext()) {  
		            Map.Entry entry = (Map.Entry) it.next();  
		            String k = (String) entry.getKey();  
		            String v = String.valueOf(entry.getValue()) ;  
		            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {  
		                sb.append(k + "=" + v + "&");  
		            }  
		        }  
		        sb.append("key=" + API_KEY);  
		        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();  
		        return sign;  
		    } 
		   
		   
		  public static String getCurrTime() {  
		        Date now = new Date();  
		        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");  
		        String s = outFormat.format(now);  
		        return s;  
		    }  
		 
		  public static String getRequestXml(SortedMap<Object, Object> parameters) {  
		        StringBuffer sb = new StringBuffer();  
		        sb.append("<xml>");  
		        Set es = parameters.entrySet();  
		        Iterator it = es.iterator();  
		        while (it.hasNext()) {  
		            Map.Entry entry = (Map.Entry) it.next();  
		            String k = (String) entry.getKey();  
		            String v = String.valueOf(entry.getValue());  
		            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {  
		                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");  
		            } else {  
		                sb.append("<" + k + ">" + v + "</" + k + ">");  
		            }  
		        }  
		        sb.append("</xml>");  
		        return sb.toString();  
		    }  
	
		  
		  
		  /**
			 * 解析调用统一支付接口响应报文
			 * @param msg
			 * @return
			 */
			public static PayUnitedResponse xmlToPayUnitedResponse(String msg){
				
				PayUnitedResponse payUnitedResponse=new PayUnitedResponse();

				Document doc=null;
				try {
					doc = DocumentHelper.parseText(msg);
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Element root = doc.getRootElement();
				String return_code = root.element("return_code").getTextTrim();
				
				
				if(Constant.RESULT_CODE_SUCCESS.equals(return_code)){
					
					String result_code = root.element("result_code").getTextTrim();
					
					if(Constant.RESULT_CODE_SUCCESS.equals(result_code)){
						
						String appid = root.element("appid").getTextTrim();
						String mch_id = root.element("mch_id").getTextTrim();
						String nonce_str = root.element("nonce_str").getTextTrim();
						String sign = root.element("sign").getTextTrim();
						String trade_type = root.element("trade_type").getTextTrim();
						String prepay_id = root.element("prepay_id").getTextTrim();

						payUnitedResponse.setAppid(appid);
						payUnitedResponse.setMch_id(mch_id);
						payUnitedResponse.setNonce_str(nonce_str);
						payUnitedResponse.setReturn_code(return_code);
						payUnitedResponse.setReturn_code(result_code);
						payUnitedResponse.setSign(sign);
						payUnitedResponse.setTrade_type(trade_type);
						payUnitedResponse.setPrepay_id(prepay_id);
						
					}else{
						String err_code = root.element("err_code").getTextTrim();
						String err_code_desc = root.element("err_code_des").getTextTrim();
						payUnitedResponse.setReturn_msg(err_code_desc);
						System.out.println("请求统一支付接口返回数据错误");
					}
					
					
				}else{
					//协议错误
					String return_msg = root.element("return_msg").getTextTrim();
					payUnitedResponse.setReturn_msg(return_msg);
					System.out.println("请求统一支付接口协议数据错误");
				}
				return  payUnitedResponse;
			
				
			}
		
		  
}
