package com.xhpc.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.AntCertificationUtil;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.api.UserTypeService;
import com.xhpc.common.core.annotation.NoRepeatSubmit;
import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.data.down.StartChargingData;
import com.xhpc.common.domain.XhpcRechargeOrder;
import com.xhpc.common.log.annotation.Log;
import com.xhpc.common.log.enums.BusinessType;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.payment.domain.AlipayNotifyParam;
import com.xhpc.payment.domain.XhpcAppUser;
import com.xhpc.common.domain.XhpcSettingConfig;
import com.xhpc.payment.domain.XhpcUserAccountStatement;
import com.xhpc.payment.mapper.XhpcUserAccountStatementMapper;
import com.xhpc.payment.service.IXhpcCommonPayment;
import com.xhpc.payment.service.IXhpcRechargeOrderService;
import com.xhpc.payment.service.IXhpcRefundOrderService;
import com.xhpc.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


@RestController
@RequestMapping("/alipay")
@Api(value = "支付宝支付接口", tags = "支付宝支付接口")
public class AlipayPaymentController {

    @Autowired
    private IXhpcRechargeOrderService iXhpcRechargeOrderService;
    @Autowired
    private XhpcUserAccountStatementMapper xhpcUserAccountStatementMapper;
    @Autowired
    private PowerPileService powerPileService;
    @Autowired
    private IXhpcRefundOrderService iXhpcRefundOrderService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IXhpcCommonPayment xhpcCommonPayment;
    @Autowired
    private UserTypeService userTypeService;
    @Autowired
    private RedisService redisService;



    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

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

    @Log(title = "支付宝-支付", businessType = BusinessType.INSERT)
    @NoRepeatSubmit(lockTime = 3)
    @PostMapping("/payment")
    @ApiOperation(value = "支付宝支付")
    public AjaxResult payment(HttpServletRequest servletRequest, @RequestBody Map<String, Object> map) throws Exception {
        String openid = StringUtils.valueOf(map.get("openid"));
        if (StringUtils.isEmpty(openid)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "openid不能为空");
        }
        //总金额(是)订单总金额，单位为元
        String amount = StringUtils.valueOf(map.get("amount"));
        if (StringUtils.isEmpty(amount)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "充值金额不能为空");
        }else{
            if(new BigDecimal(5).compareTo(new BigDecimal(amount))==1){
                return AjaxResult.error(HttpStatus.NOT_NULL, "充值金额不能少于5元");
            }
            if(new BigDecimal(600).compareTo(new BigDecimal(amount))==-1){
                return AjaxResult.error(HttpStatus.NOT_NULL, "充值金额不能大于600元");
            }
        }
        //用户信息id
        String userId = StringUtils.valueOf(map.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户信息不能为空");
        }

        LoginUser loginUser = tokenService.getLoginUser(servletRequest);
        Long userid = loginUser.getUserid();
        Integer userType = loginUser.getUserType();
        String tenantId = loginUser.getTenantId();
        if(UserTypeUtil.CUSTOMERS_TYPE.equals(userType)){
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "大客户不支持充值,请让管理员在平台充值");
        }
        Map<String, Object> refundOrder = iXhpcRefundOrderService.getNotRefundOrder(userid,userType,tenantId);
        if (StringUtils.isNotNull(refundOrder)) {
            return AjaxResult.error(HttpStatus.ALREADY_EXISTING, "用户存正在退款");
        }
        String orderNumber = StringUtils.numFormat(userid, 1, StatusConstants.FLOWING_WATER_RECHARGE_TYPE);

        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_ALI_PAY_TYPE, tenantId);
        if(xhpcSettingConfig ==null){
            return AjaxResult.error(HttpStatus.ALREADY_EXISTING, "支付宝充值失败,继续充值请联系客服");
        }
        //生成充值订单
        XhpcRechargeOrder xhpcRechargeOrder = iXhpcRechargeOrderService.addRechargeOrder(userId+"", new BigDecimal(amount), "2", orderNumber,userType,null);
        String attach = attachYu(StringUtils.valueOf(xhpcRechargeOrder.getRechargeOrderId()), StringUtils.valueOf(amount), null, orderNumber);

        /** 初始化 **/
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        /** 支付宝网关 **/
        certAlipayRequest.setServerUrl(xhpcSettingConfig.getZhbServerUrl());
        /** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        certAlipayRequest.setAppId(xhpcSettingConfig.getZfbAppId());
        /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport  **/
        certAlipayRequest.setPrivateKey(xhpcSettingConfig.getZfbPrivateKey());
        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        certAlipayRequest.setCertPath(xhpcSettingConfig.getZfbAppCertPublicKey());
        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setAlipayPublicCertPath(xhpcSettingConfig.getZfbAlipayCertPublicKeyRsa());
        /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setRootCertPath(xhpcSettingConfig.getZfbAlipayRootCert());
        /** 设置签名类型 **/
        certAlipayRequest.setSignType("RSA2");
        /** 设置请求格式，固定值json **/
        certAlipayRequest.setFormat("json");
        /** 设置编码格式 **/
        certAlipayRequest.setCharset("UTF-8");
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        //AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", environment.getProperty("ALIPAYAPPID"), environment.getProperty("ALIPAYPRIVATEKEY"), "json", "utf-8", environment.getProperty("ALIPAYPUBLICKEY"), "RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        String encode = URLEncoder.encode(attach);

        request.setBizContent("{" + "\"out_trade_no\":\""+orderNumber+"\"," +
                "\"product_code\":\"JSAPI_PAY\"," +
                "\"op_app_id\":\"2021002156615717\"," +
                "\"total_amount\":"+amount+"," +
                "\"subject\":\"翔桦充电\"," +
                "\"timeout_express\":\"30m\"," +
                "\"passback_params\":\""+encode+"\"," +
                "\"buyer_id\":\""+openid+"\"" +
                "}");
        request.setNotifyUrl(xhpcSettingConfig.getZfbCallbackUrl());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeCreateResponse response = alipayClient.certificateExecute(request);
            if(response.isSuccess()){
                String trade_no = response.getTradeNo();// 获取返回的tradeNO。
                return AjaxResult.success(trade_no);
            } else {
                return AjaxResult.error("生成订单失败，请稍后在试!");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("生成订单失败，请稍后在试");
    }

    @Log(title = "欠费支付", businessType = BusinessType.INSERT)
    @NoRepeatSubmit(lockTime = 3)
    @PostMapping("/arrearsPayment")
    @ApiOperation(value = "欠费支付")
    public AjaxResult arrearsPayment(HttpServletRequest servletRequest, @RequestBody Map<String, Object> map) throws Exception {
        String openid = StringUtils.valueOf(map.get("openid"));
        if (StringUtils.isEmpty(openid)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "openid不能为空");
        }
        //总金额(是)订单总金额，单位为元
        String amount = StringUtils.valueOf(map.get("amount"));
        if (StringUtils.isEmpty(amount)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "充值金额不能为空");
        }
        //用户信息id
        String userId = StringUtils.valueOf(map.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户信息不能为空");
        }

        LoginUser loginUser = tokenService.getLoginUser(servletRequest);
        Long userid = loginUser.getUserid();
        Integer userType = loginUser.getUserType();
        String tenantId = loginUser.getTenantId();
        if(UserTypeUtil.CUSTOMERS_TYPE.equals(userType)){
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "大客户不支持充值,请让管理员在平台充值");
        }
        Map<String, Object> refundOrder = iXhpcRefundOrderService.getNotRefundOrder(userid,userType,tenantId);
        if (StringUtils.isNotNull(refundOrder)) {
            return AjaxResult.error(HttpStatus.ALREADY_EXISTING, "用户存正在退款");
        }
        String orderNumber = StringUtils.numFormat(userid, 1, StatusConstants.FLOWING_WATER_RECHARGE_TYPE);

        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_ALI_PAY_TYPE, tenantId);
        if(xhpcSettingConfig ==null){
            return AjaxResult.error(HttpStatus.ALREADY_EXISTING, "支付宝充值失败,继续充值请联系客服");
        }
        //生成充值订单
        XhpcRechargeOrder xhpcRechargeOrder = iXhpcRechargeOrderService.addRechargeOrder(userId+"", new BigDecimal(amount), "2", orderNumber,userType,null);
        String attach = attachYu(StringUtils.valueOf(xhpcRechargeOrder.getRechargeOrderId()), StringUtils.valueOf(amount), null, orderNumber);

        /** 初始化 **/
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        /** 支付宝网关 **/
        certAlipayRequest.setServerUrl(xhpcSettingConfig.getZhbServerUrl());
        /** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        certAlipayRequest.setAppId(xhpcSettingConfig.getZfbAppId());
        /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport  **/
        certAlipayRequest.setPrivateKey(xhpcSettingConfig.getZfbPrivateKey());
        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        certAlipayRequest.setCertPath(xhpcSettingConfig.getZfbAppCertPublicKey());
        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setAlipayPublicCertPath(xhpcSettingConfig.getZfbAlipayCertPublicKeyRsa());
        /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setRootCertPath(xhpcSettingConfig.getZfbAlipayRootCert());
        /** 设置签名类型 **/
        certAlipayRequest.setSignType("RSA2");
        /** 设置请求格式，固定值json **/
        certAlipayRequest.setFormat("json");
        /** 设置编码格式 **/
        certAlipayRequest.setCharset("UTF-8");
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        //AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", environment.getProperty("ALIPAYAPPID"), environment.getProperty("ALIPAYPRIVATEKEY"), "json", "utf-8", environment.getProperty("ALIPAYPUBLICKEY"), "RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        String encode = URLEncoder.encode(attach);

        request.setBizContent("{" + "\"out_trade_no\":\""+orderNumber+"\"," +
                "\"product_code\":\"JSAPI_PAY\"," +
                "\"op_app_id\":\"2021002156615717\"," +
                "\"total_amount\":"+amount+"," +
                "\"subject\":\"翔桦充电\"," +
                "\"timeout_express\":\"30m\"," +
                "\"passback_params\":\""+encode+"\"," +
                "\"buyer_id\":\""+openid+"\"" +
                "}");
        request.setNotifyUrl(xhpcSettingConfig.getZfbCallbackUrl());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeCreateResponse response = alipayClient.certificateExecute(request);
            if(response.isSuccess()){
                String trade_no = response.getTradeNo();// 获取返回的tradeNO。
                return AjaxResult.success(trade_no);
            } else {
                return AjaxResult.error("生成订单失败，请稍后在试!");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("生成订单失败，请稍后在试");
    }
    /**
     * 2      * 支付宝服务器异步通知url
     * 3      * @throws Exception
     * 4
     */
    @RequestMapping(value = "/notifyUrl")
    public String notifyUrl(HttpServletRequest request) throws Exception {

        readWriteLock.writeLock().lock();
        logger.info("<<<<<<<<<<<<支付宝服务器异步通知>>>>>>>>>");
        Map<String, String> params = convertRequestParamsToMap(request);
        // 将异步通知中收到的待验证所有参数都存放到map中
        logger.info("<<<<<<<<<<<<params>>>>>>>>>"+params);
        try{
            XhpcRechargeOrder xhpcRechargeOrder = iXhpcRechargeOrderService.infoRechargeOrderNumber(params.get("out_trade_no").toString());
            if(xhpcRechargeOrder!=null){
                XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_ALI_PAY_TYPE, xhpcRechargeOrder.getTenantId());
                if(xhpcSettingConfig !=null){
                    //String publiccertpath = getAlipayPublicKey(environment.getProperty("PUBLICCERTPATH"));
                    String publiccertpath = getAlipayPublicKey(xhpcSettingConfig.getZfbAlipayCertPublicKeyRsa());
                    logger.info("<<<<<<<<<<<<支付宝公钥证书>>>>>>>>>"+publiccertpath);
                    // 调用SDK验证签名
                    boolean signVerified = AlipaySignature.rsaCheckV1(params, publiccertpath, "utf-8", "RSA2");
                    logger.info("<<<<<<<<<<<<验证签名>>>>>>>>>"+signVerified);
                    if (signVerified) {
                        //("支付宝回调签名认证成功");
                        AlipayNotifyParam param = buildAlipayNotifyParam(params);
                        String trade_status = param.getTradeStatus();
                        // 支付成功
                        if (trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED")) {
                            // 处理支付成功逻辑
                            try{
                                String passbackParams = param.getPassbackParams();
                                String tradeStatus = param.getTradeStatus();
                                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                                    // 业务参数主要转码回来
                                    JSONObject jsonObject = JSON.parseObject(URLDecoder.decode(passbackParams));
                                    String out_trade_no = jsonObject.getString("out_trade_no");
                                    String transaction_id = params.get("trade_no");
                                    paymentCallback(out_trade_no, transaction_id);
                                }
                            }catch (Exception e){
                                //("支付宝回调业务处理报错,params:" + paramsJson, e);
                            }
                        }else{
                            //("没有处理支付宝回调业务，支付宝交易状态：{},params:{}",trade_status,paramsJson);
                        }
                        // 业务处理失败，可查看日志进行补偿，跟支付宝已经没多大关系。
                        return "success";
                    }else{
                        return "failure";
                    }
                }
            }
            Thread.sleep(500);
            return "failure";
        }catch (Exception e){
            e.printStackTrace();
            //logger.error("支付宝回调签名认证失败,paramsJson:{},errorMsg:{}", paramsJson, e.getMessage());
            return "failure";
        }finally {
            readWriteLock.writeLock().unlock();//释放锁
        }
    }


    //附加参数
    public String attachYu(String id, String money, String payStyle, String out_trade_no) {
        // 发送请求参数  业务参数
        StringBuilder attachSB = new StringBuilder();
        attachSB.append(",{\"customerId\":" + id);
        attachSB.append(",\"money\":\"" + money + "\"");
        attachSB.append(",\"out_trade_no\":\"" + out_trade_no + "\"}");
        String attach = attachSB.substring(1);
        return attach;
    }

    private AlipayNotifyParam buildAlipayNotifyParam(Map<String, String> params) {
        String json = JSON.toJSONString(params);
        return JSON.parseObject(json, AlipayNotifyParam.class);
    }
    // 将request中的参数转换成Map
    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;
            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }

    /**
     * 修改支付订单
     *
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public void paymentCallback(String out_trade_no, String transaction_id) {
        //支付订单编号
        XhpcRechargeOrder xhpcRechargeOrder = iXhpcRechargeOrderService.infoRechargeOrderNumber(out_trade_no);
        if (StringUtils.isNotNull(xhpcRechargeOrder)) {
            if(xhpcRechargeOrder.getStatus() == 0){
                //修改充值订单状态
                iXhpcRechargeOrderService.updateRechargeOrder(xhpcRechargeOrder.getRechargeOrderId(), StatusConstants.OPERATION_ALI_PAY_TYPE, StatusConstants.RECHARGE_ORDER_STATUS_SUCCESS, transaction_id);

                Long userId = xhpcRechargeOrder.getUserId();
                Integer source = xhpcRechargeOrder.getSource();
                String tenantId = xhpcRechargeOrder.getTenantId();
                //判断用户
                R user = userTypeService.getUser(null,userId, source, null, tenantId);
                if(user !=null && user.getData() !=null){
                    Map<String, Object> map = (Map<String, Object>)user.getData();
                    Integer sunchaSwitch = Integer.valueOf(map.get("sunchaSwitch").toString());
                    if(sunchaSwitch==0){
                        String balance = StringUtils.valueOf(map.get("balance"));
                        BigDecimal money = BigDecimal.valueOf(Double.valueOf(balance)).add(xhpcRechargeOrder.getAmount());
                        //判断用户是否在充电中
                        String serialMumber = xhpcUserAccountStatementMapper.getUserHistotyChargeOrder(xhpcRechargeOrder.getUserId(),source,tenantId);
                        logger.info("<<<<<<<<<<<<充电终端>>>>>>>>>serialMumber："+serialMumber);
                        if(!"".equals(serialMumber) && serialMumber !=null){
                            //充电中
                            postRefreshBalance(money, serialMumber);
                        }
                        if(UserTypeUtil.USER_TYPE.equals(xhpcRechargeOrder.getSource())){
                            //增加用户余额
                            XhpcAppUser xhpcAppUser = new XhpcAppUser();
                            xhpcAppUser.setAppUserId(xhpcRechargeOrder.getUserId());
                            xhpcAppUser.setBalance(money);
                            xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);
                            XhpcUserAccountStatement xhpcUserAccountStatement = new XhpcUserAccountStatement();
                            xhpcUserAccountStatement.setType(StatusConstants.FLOWING_WATER_RECHARGE_TYPE);
                            xhpcUserAccountStatement.setRechargeOrderId(xhpcRechargeOrder.getRechargeOrderId());
                            xhpcUserAccountStatement.setUserId(xhpcRechargeOrder.getUserId());
                            xhpcUserAccountStatement.setAmount(xhpcRechargeOrder.getAmount());
                            xhpcUserAccountStatement.setRemainingSum(xhpcAppUser.getBalance());
                            xhpcUserAccountStatement.setCreateTime(new Date());
                            xhpcUserAccountStatement.setRemark("支付宝充值订单！");
                            xhpcUserAccountStatementMapper.insert(xhpcUserAccountStatement);
                        }else{
                            //增加用户余额
                            userTypeService.insertUserBalance(xhpcRechargeOrder.getAmount(),userId,source,tenantId,UserTypeUtil.RECHARGE_ZHB,UserTypeUtil.INSERT_BALANCE,null,xhpcRechargeOrder.getRechargeOrderId());
                        }
                    }else{
                        String balance = StringUtils.valueOf(map.get("balance"));
                        BigDecimal aBigDecimal = xhpcRechargeOrder.getAmount().divide(new BigDecimal(2)).setScale(0, BigDecimal.ROUND_UP);
                        BigDecimal bBigDecimal =xhpcRechargeOrder.getAmount().subtract(aBigDecimal);
                        BigDecimal aBalance = new BigDecimal(map.get("aBalance").toString()).add(aBigDecimal);
                        BigDecimal bBalance = new BigDecimal(map.get("bBalance").toString()).add(bBigDecimal);
                        String userType =UserTypeUtil.USER;
                        if(UserTypeUtil.COMMUNIT_TYPE==xhpcRechargeOrder.getSource()){
                            userType =UserTypeUtil.COMMUNIT;
                        }else if(UserTypeUtil.CUSTOMERS_TYPE==xhpcRechargeOrder.getSource()){
                            userType =UserTypeUtil.CUSTOMERS;
                        }
                        String key = "user:" + xhpcRechargeOrder.getUserId() + userType + ".order";

                        //判断用户是否在充电中
                        String serialMumberA = xhpcUserAccountStatementMapper.getUserHistotyChargeOrderSuncha(xhpcRechargeOrder.getUserId(),source,tenantId,1);
                        if(!"".equals(serialMumberA) && serialMumberA !=null){
                            //充电中
                            postRefreshBalance(aBalance, serialMumberA);
                            Map<String, Object> mapA = new HashMap<>();
                            map.put("aBalance", aBalance);
                            redisService.setCacheMap(key,mapA);
                        }
                        String serialMumberB = xhpcUserAccountStatementMapper.getUserHistotyChargeOrderSuncha(xhpcRechargeOrder.getUserId(),source,tenantId,2);
                        if(!"".equals(serialMumberB) && serialMumberB !=null){
                            //充电中
                            postRefreshBalance(bBalance, serialMumberB);
                            Map<String, Object> mapA = new HashMap<>();
                            map.put("bBalance", bBalance);
                            redisService.setCacheMap(key,mapA);
                        }

                        BigDecimal money = BigDecimal.valueOf(Double.valueOf(balance)).add(xhpcRechargeOrder.getAmount());
                        if(UserTypeUtil.USER_TYPE.equals(xhpcRechargeOrder.getSource())){
                            //增加用户余额
                            XhpcAppUser xhpcAppUser = new XhpcAppUser();
                            xhpcAppUser.setAppUserId(xhpcRechargeOrder.getUserId());
                            xhpcAppUser.setBalance(money);
                            xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);
                            XhpcUserAccountStatement xhpcUserAccountStatement = new XhpcUserAccountStatement();
                            xhpcUserAccountStatement.setType(StatusConstants.FLOWING_WATER_RECHARGE_TYPE);
                            xhpcUserAccountStatement.setRechargeOrderId(xhpcRechargeOrder.getRechargeOrderId());
                            xhpcUserAccountStatement.setUserId(xhpcRechargeOrder.getUserId());
                            xhpcUserAccountStatement.setAmount(xhpcRechargeOrder.getAmount());
                            xhpcUserAccountStatement.setRemainingSum(xhpcAppUser.getBalance());
                            xhpcUserAccountStatement.setCreateTime(new Date());
                            xhpcUserAccountStatement.setRemark("支付宝充值订单！");
                            xhpcUserAccountStatementMapper.insert(xhpcUserAccountStatement);
                        }else{
                            //增加用户余额
                            userTypeService.insertUserBalance(xhpcRechargeOrder.getAmount(),userId,source,tenantId,UserTypeUtil.RECHARGE_ZHB,UserTypeUtil.INSERT_BALANCE,null,xhpcRechargeOrder.getRechargeOrderId());
                        }
                    }



                }
            }

        }

    }

    private void postRefreshBalance(BigDecimal money, String serialMumber) {
        StartChargingData startChargingData =new StartChargingData();
        String su1 = serialMumber.substring(0, 14);
        String su2 = serialMumber.substring(14);
        startChargingData.setPileNo(su1);
        startChargingData.setGunId(su2);
        String s1 =money.multiply(new BigDecimal(100)).toString();
        startChargingData.setBalance(Double.valueOf(s1).intValue());
        R r = powerPileService.refreshBalance(startChargingData);

        //修改订单充电下发的金额
        Map<String, Object> cacheMap = redisService.getCacheMap("order:"+serialMumber);

        if(cacheMap.get("initBalance") !=null){
            cacheMap.put("initBalance",Double.valueOf(money.multiply(new BigDecimal(10000)).toString()).intValue());
            redisService.setCacheMap("order:"+serialMumber,cacheMap);

            redisService.setCacheObject("YE"+serialMumber,money);

        }
        logger.info("<<<<<<<<<<<<余额下发>>>>>>>>>"+s1);
        logger.info("<<<<<<<<<<<<"+r.getCode()+">>>>>>>>>");
        logger.info("<<<<<<<<<<<<"+r.getMsg()+">>>>>>>>>");

    }

    /**
     * 从公钥证书中提取公钥
     *
     * @param alipayPublicCertPath 公钥证书存放路径，例如:/home/admin/cert.crt
     * @return 公钥
     * @throws AlipayApiException
     */
    public static String getAlipayPublicKey(String alipayPublicCertPath) throws AlipayApiException {
        return AntCertificationUtil.getAlipayPublicKey(alipayPublicCertPath);
    }


}
