package com.neusoft.smart.pos.payment.repository;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.payment.request.PostGrantToPayRequest;
import com.neusoft.smart.pos.framework.constants.ApplicationConstants;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.framework.utils.IdGenerateUtils;
import com.neusoft.smart.pos.payment.constants.AliPayConstants;
import com.neusoft.smart.pos.payment.constants.PaymentErrorCode;
import com.neusoft.smart.pos.payment.persistent.domain.GrantPayOrder;
import com.neusoft.smart.pos.payment.persistent.domain.MchPayChannel;
import com.neusoft.smart.pos.payment.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payment.persistent.domain.PayTypeDict;
import com.neusoft.smart.pos.payment.persistent.ext.domain.*;
import com.neusoft.smart.pos.payment.utils.LogUtils;
import lombok.val;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author tjm
 * @date 2018-02-24 
 * @description 支付宝预授权管理使用Repository
 */
@Component("aliPayGrantRepository")
public class AliPayGrantRepository implements IThirdPayGrantRepository {

	/**
	 * 创建支付宝支付单使用方法
	 * @param mchPayChannel
	 * @return
	 */
	@Override
	public ThirdPlatformFreezePay freezePayToThirdPlatform(GrantPayOrder grantPayOrder, MchPayChannel mchPayChannel, PayTypeDict payTypeDict){
		//1.处理数据
		String aliPayRequestData =  aliPayCreateOrderRequestDataHandle(grantPayOrder,mchPayChannel,payTypeDict);
		//2.请求支付宝预付单生成接口
		
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.URL, mchPayChannel.getAppid(), mchPayChannel.getPrivateKey(), AliPayConstants.FORMAT, AliPayConstants.CHARSET, mchPayChannel.getPublicKey(), AliPayConstants.SIGN_TYPE);
		String responseData = "";
//		AlipayFundAuthOrderFreezeRequest request = new AlipayFundAuthOrderFreezeRequest();//创建API对应的request类
		AlipayFundAuthOrderVoucherCreateRequest request = new AlipayFundAuthOrderVoucherCreateRequest();//创建API对应的request类
		request.setBizContent(aliPayRequestData);//设置业务参数
		request.setNotifyUrl(payTypeDict.getNotifyUrl());
		try{
			System.out.printf(JSON.toJSONString(request));
			AlipayFundAuthOrderVoucherCreateResponse response = alipayClient.execute(request);
//			AlipayFundAuthOrderFreezeResponse response = alipayClient.execute(request);
			responseData = response.getBody();
		}catch (AlipayApiException e){
			e.printStackTrace();
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_PRECREATE_ERROR);
		}finally {
			//3.记录日志
			LogUtils.savePaymentTradeLog(grantPayOrder.getMcode(),grantPayOrder.getmOrderNumber(), DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode(),LogUtils.LOG_DESCRIPTION_DDSC,aliPayRequestData,responseData,DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
		}
		return aliPayCreateOrderResponseDataHandle(grantPayOrder,responseData);
	}

	/**
	 * 支付宝预支付请求数据绑定方法
	 * @param mchPayChannel
	 * @return
	 */
	private String aliPayCreateOrderRequestDataHandle(GrantPayOrder grantPayOrder, MchPayChannel mchPayChannel,PayTypeDict payTypeDict){
		//请求参数金额是以分为单位，支付宝接口金额是以元为单位，换算成元
		float orderAmount = (float)grantPayOrder.getGrantAmount() / 100;
		String requestData = ("{" +
				"\"out_order_no\":\"" + grantPayOrder.getmOrderNumber() + "\"," +
				"\"out_request_no\":\"" + grantPayOrder.getmOrderNumber() + "\"," +
				"\"order_title\":\"资金预授权\"," +
				"\"amount\":" + orderAmount + "," +
				"\"product_code\":\"PRE_AUTH\"," +
				"\"pay_timeout\":\"2h\"}");
		return requestData;
	}
	
	/**
	 * 支付宝支付响应数据处理
	 * @param payOrder
	 * @param responseData
	 * @return
	 */
	private ThirdPlatformFreezePay aliPayCreateOrderResponseDataHandle(GrantPayOrder payOrder, String responseData){
		JSONObject resData = JSONObject.fromObject(responseData);
        if (resData.has("alipay_fund_auth_order_voucher_create_response")) {
        	JSONObject result = resData.getJSONObject("alipay_fund_auth_order_voucher_create_response");
        	if (result.has("code") && !result.getString("code").equals(ApplicationConstants.ALIPAY_SUCC_CODE)){
        		throw new BusinessCommonException(result.getString("code"), result.getString("msg") + "|" + (result.has("sub_code")?result.getString("sub_code"):"") + "|" + (result.has("sub_msg")?result.getString("sub_msg"):""));
        	}
        	val thirdPlatformOrder = new ThirdPlatformFreezePay();
    		thirdPlatformOrder.setMcode(payOrder.getMcode());
    		thirdPlatformOrder.setTradeId(payOrder.getTradeId());
    		thirdPlatformOrder.setMOrderNumber(payOrder.getmOrderNumber());
    		thirdPlatformOrder.setOuterOrderNumber("");
//    		thirdPlatformOrder.setOuterOrderNumber(result.getString("operation_id"));
    		thirdPlatformOrder.setOuterCodeUrl(result.getString("code_value"));
	        thirdPlatformOrder.setAuthAmount(payOrder.getGrantAmount());
	        thirdPlatformOrder.setGrantTime("");
	        thirdPlatformOrder.setPayFreezeStatus(DictionaryConstant.PAY_GRANT_STATUS_CLZ.getCode());
	        thirdPlatformOrder.setAuthNo("");
//	        thirdPlatformOrder.setAuthNo(result.getString("auth_no"));
    		return thirdPlatformOrder;
        }else{
        	throw new BusinessCommonException(PaymentErrorCode.ALIPAY_PRECREATE_RESPONSE_ERROR);
        }
		
	}
	
	/**
	 * 预付单撤销使用方法
	 * @return
	 */
	public ThirdPlatformReversePayGrant reversePayGrantFromThirdPlatform(GrantPayOrder grantPayOrder, MchPayChannel mchPayChannel){
		String reqData = "{" +
				"\"auth_no\":\""+grantPayOrder.getAuthNo()+"\"," +
				"\"out_order_no\":\""+grantPayOrder.getmOrderNumber()+"\"," +
				"\"operation_id\":\""+grantPayOrder.getOuterOrderNumber()+"\"," +
				"\"out_request_no\":\""+grantPayOrder.getmOrderNumber()+"\"," +
				"\"remark\":\"授权撤销\"" +
				"  }";
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.URL, mchPayChannel.getAppid(), mchPayChannel.getPrivateKey(), AliPayConstants.FORMAT, AliPayConstants.CHARSET, mchPayChannel.getPublicKey(), AliPayConstants.SIGN_TYPE);
		AlipayFundAuthOperationCancelRequest request = new AlipayFundAuthOperationCancelRequest();
		request.setBizContent(reqData);
		String responseData = "";
		try{
			AlipayFundAuthOperationCancelResponse response = alipayClient.execute(request);
			responseData = response.getBody();
		}catch (AlipayApiException e){
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_ERROR);
		}finally {
			//3.记录日志
			LogUtils.savePaymentTradeLog(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(), DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode(),LogUtils.LOG_DESCRIPTION_DDQX,reqData,responseData,DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
		}
		return reversePayGrantResponseDataHandle(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(),responseData);
	}

	/**
	 * 支付宝支付订单取消响应数据处理
	 * @return
	 */
	private ThirdPlatformReversePayGrant reversePayGrantResponseDataHandle(String mcode,String orderNumber, String responseData){
		JSONObject resData = JSONObject.fromObject(responseData);
        if (resData.has("alipay_fund_auth_operation_cancel_response")) {
        	JSONObject result = resData.getJSONObject("alipay_fund_auth_operation_cancel_response");
        	if (result.has("code") && !result.getString("code").equals(ApplicationConstants.ALIPAY_SUCC_CODE)){
        		throw new BusinessCommonException(result.getString("code"), result.getString("msg") + "|" + (result.has("sub_code")?result.getString("sub_code"):"") + "|" + (result.has("sub_msg")?result.getString("sub_msg"):""));
        	}
        	val thirdPlatformReverseOrder = new ThirdPlatformReversePayGrant();
        	thirdPlatformReverseOrder.setMcode(mcode);
        	thirdPlatformReverseOrder.setMOrderNumber(orderNumber);
        	thirdPlatformReverseOrder.setPayType(DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode());
    		thirdPlatformReverseOrder.setReverseStatus("2");
    		return thirdPlatformReverseOrder;
        }else{
        	throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_RESPONSE_ERROR);
        }
	}

	/**
	 *
	 * * 资金授权解冻使用方法
	 * @return
	 */
	public ThirdPlatformUnFreezePayGrant unfreezePayFromThirdPlatform(Long amount, GrantPayOrder grantPayOrder, MchPayChannel mchPayChannel){
		Long unFreezeAmount = 0L;
        if(null == amount||amount == 0){
			//如果为空则解冻全部金额
			unFreezeAmount = grantPayOrder.getGrantAmount()-grantPayOrder.getUnfreezeAmount();
		}else{
			unFreezeAmount = amount;
   
		}
        float freezeAmount = (float)unFreezeAmount / 100;
		String reqData = "{" +
				"\"auth_no\":\""+grantPayOrder.getAuthNo()+"\"," +
				"\"out_request_no\":\""+grantPayOrder.getmOrderNumber()+ IdGenerateUtils.randomNumber(6) +"\"," +
				"\"amount\":\""+freezeAmount+"\"," +
				"\"remark\":\"授权资金解冻\"" +
				"  }";
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.URL, mchPayChannel.getAppid(), mchPayChannel.getPrivateKey(), AliPayConstants.FORMAT, AliPayConstants.CHARSET, mchPayChannel.getPublicKey(), AliPayConstants.SIGN_TYPE);
		AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
		request.setBizContent(reqData);
		String responseData = "";
		try{
			AlipayFundAuthOrderUnfreezeResponse response = alipayClient.execute(request);
			responseData = response.getBody();
		}catch (AlipayApiException e){
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_ERROR);
		}finally {
			//3.记录日志
			LogUtils.savePaymentTradeLog(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(), DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode(),LogUtils.LOG_DESCRIPTION_DDQX,reqData,responseData,DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
		}
		return unFreezePayGrantResponseDataHandle(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(),responseData);
	}
	
	/**
	 * 支付宝支付订单取消响应数据处理
	 * @return
	 */
	private ThirdPlatformUnFreezePayGrant unFreezePayGrantResponseDataHandle(String mcode,String orderNumber, String responseData){
		JSONObject resData = JSONObject.fromObject(responseData);
		if (resData.has("alipay_fund_auth_order_unfreeze_response")) {
			JSONObject result = resData.getJSONObject("alipay_fund_auth_order_unfreeze_response");
			if (result.has("code") && !result.getString("code").equals(ApplicationConstants.ALIPAY_SUCC_CODE)){
				throw new BusinessCommonException(result.getString("code"), result.getString("msg") + "|" + (result.has("sub_code")?result.getString("sub_code"):"") + "|" + (result.has("sub_msg")?result.getString("sub_msg"):""));
			}
			val thirdPlatformUnFreezePayGrant = new ThirdPlatformUnFreezePayGrant();
			thirdPlatformUnFreezePayGrant.setMcode(mcode);
			thirdPlatformUnFreezePayGrant.setMOrderNumber(orderNumber);
			thirdPlatformUnFreezePayGrant.setPayType(DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode());
			thirdPlatformUnFreezePayGrant.setUnFreezeStatus("2");
			thirdPlatformUnFreezePayGrant.setUnFreezeTime(result.getString("gmt_trans"));
			Double amountD = Double.parseDouble(result.getString("amount"));
			BigDecimal amountB=BigDecimal.valueOf(amountD).multiply(BigDecimal.valueOf(100L));
			thirdPlatformUnFreezePayGrant.setAmount(amountB.longValue());
			return thirdPlatformUnFreezePayGrant;
		}else{
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_RESPONSE_ERROR);
		}
	}
	
	/**
	 * 资金授权信息查询使用方法
	 * @return
	 */
	public ThirdPlatformQueryPayGrant queryPayGrantFromThirdPlatform(GrantPayOrder grantPayOrder, MchPayChannel mchPayChannel){
		String reqData = "{" +
				"\"auth_no\":\""+grantPayOrder.getAuthNo()+"\"," +
				"\"out_order_no\":\""+grantPayOrder.getmOrderNumber()+"\"," +
				"\"out_request_no\":\""+grantPayOrder.getmOrderNumber()+ IdGenerateUtils.randomNumber(6) +"\"," +
				"\"operation_id\":\""+grantPayOrder.getOuterOrderNumber()+"\"," +
				"  }";
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.URL, mchPayChannel.getAppid(), mchPayChannel.getPrivateKey(), AliPayConstants.FORMAT, AliPayConstants.CHARSET, mchPayChannel.getPublicKey(), AliPayConstants.SIGN_TYPE);
		AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
		request.setBizContent(reqData);
		String responseData = "";
		try{
			AlipayFundAuthOperationDetailQueryResponse response = alipayClient.execute(request);
			responseData = response.getBody();
		}catch (AlipayApiException e){
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_ERROR);
		}finally {
			//3.记录日志
			LogUtils.savePaymentTradeLog(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(), DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode(),LogUtils.LOG_DESCRIPTION_DDQX,reqData,responseData,DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
		}
		return queryPayGrantResponseDataHandle(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(),responseData);
	}
	
	/**
	 * 支付宝支付订单查询响应数据处理
	 * @return
	 */
	private ThirdPlatformQueryPayGrant queryPayGrantResponseDataHandle(String mcode,String orderNumber, String responseData){
		JSONObject resData = JSONObject.fromObject(responseData);
		if (resData.has("alipay_fund_auth_operation_detail_query_response")) {
			JSONObject result = resData.getJSONObject("alipay_fund_auth_operation_detail_query_response");
			if (result.has("code") && !result.getString("code").equals(ApplicationConstants.ALIPAY_SUCC_CODE)){
				throw new BusinessCommonException(result.getString("code"), result.getString("msg") + "|" + (result.has("sub_code")?result.getString("sub_code"):"") + "|" + (result.has("sub_msg")?result.getString("sub_msg"):""));
			}
			val thirdPlatformQueryPayGrant = new ThirdPlatformQueryPayGrant();
			thirdPlatformQueryPayGrant.setMcode(mcode);
			thirdPlatformQueryPayGrant.setMOrderNumber(orderNumber);
			thirdPlatformQueryPayGrant.setAuthNo(result.getString("auth_no")); //支付宝资金授权订单号
			thirdPlatformQueryPayGrant.setTotalFreezeAmount(convertAliPrice(result.getString("total_freeze_amount")));//订单累计的冻结金额，单位为：分（人民币）
			thirdPlatformQueryPayGrant.setRestAmount(convertAliPrice(result.getString("rest_amount")));//订单总共剩余的冻结金额，单位为：分（人民币）
			thirdPlatformQueryPayGrant.setTotalPayAmount(convertAliPrice(result.getString("total_pay_amount")));//订单累计用于支付的金额，单位为：分（人民币）
			thirdPlatformQueryPayGrant.setOrderTitle(result.getString("order_title"));           //业务订单的简单描述，如商品名称等
			thirdPlatformQueryPayGrant.setPayerLogonId(result.getString("payer_logon_id"));//付款方支付宝账号（Email或手机号），仅作展示使用，默认会加“*”号处理
			thirdPlatformQueryPayGrant.setPayerUserId(result.getString("payer_user_id"));//付款方支付宝账号对应的支付宝唯一用户号，以2088开头的16位纯数字组成
			thirdPlatformQueryPayGrant.setOuterOrderNumber(result.getString("operation_id"));//支付宝资金操作流水号
			thirdPlatformQueryPayGrant.setOutRequestNo(result.getString("out_request_no"));//商户资金操作的请求流水号
			thirdPlatformQueryPayGrant.setAmount(convertAliPrice(result.getString("amount"))); //该笔资金操作流水opertion_id对应的操作金额，单位为：分（人民币）
			thirdPlatformQueryPayGrant.setOperationType(result.getString("operation_type"));//支付宝资金操作类型， 目前支持：  FREEZE：冻结  UNFREEZE：解冻  PAY：支付
			thirdPlatformQueryPayGrant.setStatus(result.getString("status"));//资金操作流水的状态， 目前支持：  INIT：初始  SUCCESS：成功  CLOSED：关闭
			thirdPlatformQueryPayGrant.setRemark(result.getString("remark"));//商户对本次操作的附言描述，长度不超过100个字母或50个汉字
			thirdPlatformQueryPayGrant.setGmtCreate(result.getString("gmt_create"));//资金授权单据操作流水创建时间， 格式：YYYY-MM-DD HH:MM:SS
			thirdPlatformQueryPayGrant.setGmtTrans(result.getString("gmt_trans"));//支付宝账务处理成功时间， 格式：YYYY-MM-DD HH:MM:SS
//			thirdPlatformQueryPayGrant.setTotalFreezeCreditAmount(convertAliPrice(result.getString("total_freeze_credit_amount")));//累计冻结信用金额，单位为：分（人民币）
//			thirdPlatformQueryPayGrant.setTotalFreezeFundAmount(convertAliPrice(result.getString("total_freeze_fund_amount")));//累计冻结自有资金金额，单位为：分（人民币）
//			thirdPlatformQueryPayGrant.setTotalPayCreditAmount(convertAliPrice(result.getString("total_pay_credit_amount")));//累计支付信用金额，单位为：分（人民币）
//			thirdPlatformQueryPayGrant.setTotalPayFundAmount(convertAliPrice(result.getString("total_pay_fund_amount")));//累计支付自有资金金额，单位为：分（人民币）
//			thirdPlatformQueryPayGrant.setRestCreditAmount(convertAliPrice(result.getString("rest_credit_amount")));//剩余冻结信用金额，单位为：分（人民币）
//			thirdPlatformQueryPayGrant.setRestFundAmount(convertAliPrice(result.getString("rest_fund_amount")));//剩余冻结自有资金金额，单位为：分（人民币）
//			thirdPlatformQueryPayGrant.setCreditAmount(convertAliPrice(result.getString("credit_amount")));//该笔资金操作流水opertion_id对应的操作信用金额
//			thirdPlatformQueryPayGrant.setFundAmount(convertAliPrice(result.getString("fund_amount")));//该笔资金操作流水opertion_id对应的操作自有资金金额
			return thirdPlatformQueryPayGrant;
		}else{
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_RESPONSE_ERROR);
		}
	}
	
	/**
	 * 授权转支付使用方法
	 * @return
	 */
	public ThirdPlatformGrantToPay grantToPayFromThirdPlatform(PostGrantToPayRequest grantToPayRequest, GrantPayOrder grantPayOrder, MchPayChannel mchPayChannel, PayTypeDict payTypeDict){
		float payAmount = (float)grantPayOrder.getPayAmount() / 100;
		AlipayTradePayModel model = new AlipayTradePayModel();
		model.setOutTradeNo(grantPayOrder.getmPayOrderNumber()); // 预授权转支付商户订单号，为新的商户交易流水号；如果重试发起扣款，商户订单号不要变；
		model.setProductCode("PRE_AUTH"); // 固定值PRE_AUTH_ONLINE
		model.setAuthNo(grantPayOrder.getAuthNo()); // 填写预授权冻结交易号
		model.setSubject("预授权转支付"); // 解冻转支付标题，用于展示在支付宝账单中
		model.setTotalAmount(String.valueOf(payAmount)); // 结算支付金额
		model.setSellerId(mchPayChannel.getMchId()); // 填写卖家支付宝账户pid
		model.setBuyerId(grantPayOrder.getPayerUserId()); // 填写预授权用户uid，通过预授权冻结接口返回的payer_user_id字段获取
		model.setAuthConfirmMode("COMPLETE");
		model.setStoreId(grantToPayRequest.getStoreId());   //支付宝开放平台门店ID
		model.setTerminalId(grantToPayRequest.getDeviceId());   //设备sn
		ExtendParams extendParams = new ExtendParams();
		extendParams.setSysServiceProviderId(grantToPayRequest.getPid()); //系统商编号 该参数作为系统商返佣数据提取的依据，请填写系统商签约协议的PID
		model.setExtendParams(extendParams);
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.URL, mchPayChannel.getAppid(), mchPayChannel.getPrivateKey(), AliPayConstants.FORMAT, AliPayConstants.CHARSET, mchPayChannel.getPublicKey(), AliPayConstants.SIGN_TYPE);
		AlipayTradePayRequest request = new AlipayTradePayRequest();
		request.setBizModel(model);
//		request.setNotifyUrl(payTypeDict.getNotifyUrl());
		String responseData = "";
		try{
			AlipayTradePayResponse response = alipayClient.execute(request);
			responseData = response.getBody();
		}catch (AlipayApiException e){
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_ERROR);
		}finally {
			//3.记录日志
			LogUtils.savePaymentTradeLog(mchPayChannel.getMcode(),grantPayOrder.getmOrderNumber(), DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode(),LogUtils.LOG_DESCRIPTION_SQZZF,JSON.toJSONString(model),responseData,DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
		}
		return queryGrantToPayResponseDataHandle(mchPayChannel.getMcode(),grantPayOrder,responseData);
	}
	
	/**
	 * 支付宝支付订单查询响应数据处理
	 * @return
	 */
	private ThirdPlatformGrantToPay queryGrantToPayResponseDataHandle(String mcode,GrantPayOrder grantPayOrder, String responseData){
		JSONObject resData = JSONObject.fromObject(responseData);
		if (resData.has("alipay_trade_pay_response")) {
			JSONObject result = resData.getJSONObject("alipay_trade_pay_response");
			if (result.has("code") && !result.getString("code").equals(ApplicationConstants.ALIPAY_SUCC_CODE)){
				throw new BusinessCommonException(result.getString("code"), result.getString("msg") + "|" + (result.has("sub_code")?result.getString("sub_code"):"") + "|" + (result.has("sub_msg")?result.getString("sub_msg"):""));
			}
			val thirdPlatformGrantToPay = new ThirdPlatformGrantToPay();
			thirdPlatformGrantToPay.setMcode(mcode);
			thirdPlatformGrantToPay.setMOrderNumber(grantPayOrder.getmOrderNumber());
			thirdPlatformGrantToPay.setTradeId(grantPayOrder.getTradeId());
			thirdPlatformGrantToPay.setOuterOrderNumber(grantPayOrder.getOuterOrderNumber());
			thirdPlatformGrantToPay.setPaidTime(DateUtils.getNow());
//			thirdPlatformGrantToPay.setPaidTime(result.getString("gmt_payment"));
			thirdPlatformGrantToPay.setPayAmount(convertAliPrice(result.getString("total_amount")));
			thirdPlatformGrantToPay.setMPayOrderNumber(grantPayOrder.getmPayOrderNumber());
			thirdPlatformGrantToPay.setOuterPayOrderNumber(result.getString("trade_no"));
			thirdPlatformGrantToPay.setAuthNo(grantPayOrder.getAuthNo());
			thirdPlatformGrantToPay.setPayStatus(DictionaryConstant.PAY_STATUS_YFK.getCode());
			return thirdPlatformGrantToPay;
		}else{
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_CLOSE_RESPONSE_ERROR);
		}
	}
	
	/**
	 * 支付宝预付订单退款申请方法
	 * @return
	 */
	@Override
	public ThirdPlatformRefundOrder refundPayOrderFromThirdPlatform(GrantPayOrder grantPayOrder,String refundNumber,Long refundAmount, MchPayChannel mchPayChannel,PayTypeDict payTypeDict){
		//1.处理数据
		String aliPayRefundRequestData =  aliPayRefundOrderRequestDataHandle(grantPayOrder,refundNumber,refundAmount);
		//2.请求支付宝退款接口
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.URL, mchPayChannel.getAppid(), mchPayChannel.getPrivateKey(), AliPayConstants.FORMAT, AliPayConstants.CHARSET, mchPayChannel.getPublicKey(), AliPayConstants.SIGN_TYPE);
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
		request.setBizContent(aliPayRefundRequestData); //设置业务参数
		String responseData = "";
		try{
			AlipayTradeRefundResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
			responseData = response.getBody();
		}catch (AlipayApiException e){
			throw new BusinessCommonException(PaymentErrorCode.ALIPAY_REFUND_ERROR);
		}finally {
			//3.记录日志
			LogUtils.savePaymentTradeLog(grantPayOrder.getMcode(),grantPayOrder.getmPayOrderNumber(), DictionaryConstant.PAYMENT_PAY_TYPE_ZFBZZSQ.getCode(),LogUtils.LOG_DESCRIPTION_SQTK,aliPayRefundRequestData,responseData,DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
		}
		
		return aliPayRefundOrderResponseDataHandle(grantPayOrder,responseData);
	}
	
	/**
	 * 支付宝退款请求数据绑定方法
	 * @param grantPayOrder
	 * @return
	 */
	private String aliPayRefundOrderRequestDataHandle(GrantPayOrder grantPayOrder, String refundNumber,Long refundAmount){
		if(null == refundAmount||refundAmount==0){
			refundAmount = grantPayOrder.getPayAmount();
		}
		//请求参数金额是以分为单位，支付宝接口金额是以元为单位，换算成元
		float orderAmount = (float)refundAmount / 100;
		String requestData = "{" +
				"    \"out_trade_no\":\"" + grantPayOrder.getmPayOrderNumber() + "\"," +
				"    \"out_request_no\":\"" + refundNumber + "\"," +
				"    \"refund_amount\":\"" + orderAmount + "\"}";
		return requestData;
	}
	
	/**
	 * 支付宝退款申请响应数据处理
	 * @param grantPayOrder
	 * @param responseData
	 * @return
	 */
	private ThirdPlatformRefundOrder aliPayRefundOrderResponseDataHandle(GrantPayOrder grantPayOrder, String responseData){
		JSONObject resData = JSONObject.fromObject(responseData);
		if (resData.has("alipay_trade_refund_response")) {
			
			JSONObject result = resData.getJSONObject("alipay_trade_refund_response");
			if (result.has("code") && !result.getString("code").equals(ApplicationConstants.ALIPAY_SUCC_CODE)&& !result.getString("code").equals("40004")){
				throw new BusinessCommonException(result.getString("code"), result.getString("msg") + "|" + (result.has("sub_code")?result.getString("sub_code"):"") + "|" + (result.has("sub_msg")?result.getString("sub_msg"):""));
			}
			
			val thirdPlatformOrder = new ThirdPlatformRefundOrder();
			thirdPlatformOrder.setMcode(grantPayOrder.getMcode());
			thirdPlatformOrder.setMOrderNumber(grantPayOrder.getmPayOrderNumber());
			thirdPlatformOrder.setPayType(grantPayOrder.getPayType());
			if(result.getString("code").equals("40004")){
				if(result.has("sub_code")&&result.getString("sub_code").equals("ACQ.TRADE_NOT_EXIST")) {
					thirdPlatformOrder.setRefundStatus("3");
				}else{
					thirdPlatformOrder.setRefundStatus("0");
				}
			}else{
				thirdPlatformOrder.setRefundNumber(result.getString("out_trade_no"));
				thirdPlatformOrder.setThirdRefundNumber(result.getString("trade_no"));
				thirdPlatformOrder.setRefundAmount(result.getLong("refund_fee"));
				thirdPlatformOrder.setRefundStatus("2");
			}
			return thirdPlatformOrder;
		}else{
			throw new BusinessCommonException(PaymentErrorCode.MCH_ORDER_REFUND_ERROR);
		}
		
	}
	
	private Long convertAliPrice(String price){
		BigDecimal priceB = BigDecimal.valueOf(Double.parseDouble(price));
		return priceB.multiply(BigDecimal.valueOf(100)).longValue();
	}
}
