package com.xhpc.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayOpenAppMiniTemplatemessageSendModel;
import com.alipay.api.internal.util.AntCertificationUtil;
import com.alipay.api.request.AlipayOpenAppMiniTemplatemessageSendRequest;
import com.alipay.api.response.AlipayOpenAppMiniTemplatemessageSendResponse;
import com.alipay.api.FileItem;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.api.SmsService;
import com.xhpc.common.api.UserTypeService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.HttpUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.data.down.StartChargingData;
import com.xhpc.common.data.redis.CacheRealtimeData;
import com.xhpc.common.data.redis.StaticBeanUtil;
import com.xhpc.common.domain.XhpcRate;
import com.xhpc.common.domain.XhpcTerminal;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.order.domain.XhpcChargeOrder;
import com.xhpc.order.domain.XhpcOrderRedisRecord;
import com.xhpc.order.domain.XhpcRealTimeOrder;
import com.xhpc.order.mapper.XhpcChargeOrderMapper;
import com.xhpc.order.mapper.XhpcInternetUserMapper;
import com.xhpc.order.service.IXhpcChargeOrderService;
import com.xhpc.order.service.IXhpcPlaceholderOrderService;
import com.xhpc.order.service.IXhpcRealTimeOrderService;
import com.xhpc.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.common.data.redis.StaticBeanUtil.genOrder;

/**
 * @author yuyang
 * @date 2021/8/4 9:54
 */
@Service
public class XhpcChargeOrderServiceImpl extends BaseService implements IXhpcChargeOrderService {

    public static RedisService REDIS;

    @Autowired
    private XhpcChargeOrderMapper xhpcChargeOrderMapper;
    @Autowired
    private PowerPileService powerPileService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private XhpcInternetUserMapper xhpcInternetUserMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserTypeService userTypeService;
    @Autowired
    private IXhpcRealTimeOrderService xhpcRealTimeOrderService;
    @Resource
    private IXhpcPlaceholderOrderService xhpcPlaceholderOrderService;

    private final ExecutorService executorService = Executors.newFixedThreadPool(40);

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

    @PostConstruct
    public  void init(){
        REDIS =redisService;
    }

    @Override
    public AjaxResult getCYCHistotyChargeOrderMessage(Long userId, Integer userType, String tenantId,String thirdCode) {
        Map<String,Object> map = xhpcChargeOrderMapper.getHistotyChargeOrderMessageMap(userId,tenantId,userType,thirdCode);
        if(map !=null){
            if(map.get("status")==null){
                return AjaxResult.error(1201,"无实时数据");
            }else if("-1".equals(map.get("status").toString())){
                return AjaxResult.error(1201,"无实时数据");
            }else if("0".equals(map.get("status").toString())){
                return AjaxResult.success(map);
            }else if("1".equals(map.get("status").toString()) ||"3".equals(map.get("status").toString())){
                return AjaxResult.success(map);
            }else if("2".equals(map.get("status").toString())){
                return AjaxResult.success(map);
            }{
                return AjaxResult.error(1201,"无实时数据");
            }
        }
        return AjaxResult.error(1201,"无实时数据");
    }

    @Override
    public AjaxResult getHistotyChargeOrderMessage(HttpServletRequest request) {
        try{
            LoginUser loginUser = tokenService.getLoginUser(request);
            Integer type = loginUser.getUserType();
            if(UserTypeUtil.USER_TYPE.equals(type) || UserTypeUtil.COMMUNIT_TYPE.equals(type)|| UserTypeUtil.INTERNET_TYPE.equals(type)){
                int sunchaSwitch = xhpcChargeOrderMapper.getUserTypeSunchaSwitch(loginUser.getUserid(), loginUser.getTenantId(), loginUser.getUserType());
                if(sunchaSwitch==1){
                    int count = xhpcChargeOrderMapper.getHistotyChargeOrderMessage(loginUser.getUserid(),loginUser.getTenantId(),loginUser.getUserType(),1);
                    if(count>1){
                        return  AjaxResult.success();
                    }
                    return AjaxResult.error(1201,"无实时数据");
                }else{
                    int count = xhpcChargeOrderMapper.getHistotyChargeOrderMessage(loginUser.getUserid(),loginUser.getTenantId(),loginUser.getUserType(),0);
                    if(count>0){
                        return  AjaxResult.success();
                    }
                    return AjaxResult.error(1201,"无实时数据");
                }
            }else{
                int count = xhpcChargeOrderMapper.getHistotyChargeOrderMessage(loginUser.getUserid(),loginUser.getTenantId(),loginUser.getUserType(),0);
                if(count>0){
                    return  AjaxResult.success();
                }
                return AjaxResult.error(1201,"无实时数据");
            }
        }catch (Exception e){
            return AjaxResult.error("数据异常，请联系客服或拨打桩上电话");
        }
        //return AjaxResult.success(xhpcChargeOrderMapper.getMessage(userId));
    }

    @Override
    public AjaxResult getUserHistotyChargeOrderMessage(HttpServletRequest request) {
        try{
            LoginUser loginUser = tokenService.getLoginUser(request);

            int count = xhpcChargeOrderMapper.getHistotyChargeOrderMessage(loginUser.getUserid(),loginUser.getTenantId(),loginUser.getUserType(),0);
            if(count>0){
                return  AjaxResult.success();
            }
            return AjaxResult.error(1201,"无实时数据");
        }catch (Exception e){
            return AjaxResult.error("数据异常，请联系客服或拨打桩上电话");
        }
    }

    @Override
    public Map<String, Object> getOrderMessage(Long userId) {
        return xhpcChargeOrderMapper.getMessage(userId);
    }

    @Override
    public List<Map<String, Object>> getHistotyChargeOrderStatusList(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        startPage();
        List<Map<String, Object>> list = xhpcChargeOrderMapper.getHistotyChargeOrderStatusList(loginUser.getUserid(), loginUser.getTenantId(), loginUser.getUserType());
        if(list !=null && list.size()>0){
            for (int i = 0; i <list.size() ; i++) {
                Map<String, Object> map = list.get(i);
                //获取该订单最后一条实时数据
                Map<String, Object> cacheMap = redisService.getCacheMap("order:" + map.get("serialNumber").toString());
                if(cacheMap !=null && cacheMap.size()>0){
                    List<CacheRealtimeData> CacheRealtimeDataList = (List<CacheRealtimeData>) cacheMap.get("realtimeDataList");
                    if(CacheRealtimeDataList !=null && CacheRealtimeDataList.size()>0){
                        CacheRealtimeData endData = CacheRealtimeDataList.get(list.size() - 1);
                        if (endData != null) {
                            map.put("actPrice", new BigDecimal(endData.getAmountCharged()).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP));
                        }
                    }
                }else{
                    XhpcRealTimeOrder endRealTimeOrder = xhpcRealTimeOrderService.getChargingOrderId(Long.valueOf(map.get("chargeOrderId").toString()), 2);
                    if (endRealTimeOrder != null) {
                        map.put("actPrice", endRealTimeOrder.getAmountCharged());
                    }
                }
            }
        }
        return list;
    }

    @Override
    @Transactional
    public AjaxResult startUp(HttpServletRequest request, Long userId, String terminalSerialNumber, Integer type) {
        try{
            //占位订单
            xhpcPlaceholderOrderService.getTimingPriceTime(terminalSerialNumber);
        }catch (Exception e){
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<占位订单错误>>>>>>>>>>>>>>>>>"+e);
        }
        try{
            XhpcChargeOrder xhpcChargeOrder = new XhpcChargeOrder();
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser)) {
                String username = loginUser.getUsername();
                Integer userType = loginUser.getUserType();
                Long userid = loginUser.getUserid();
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<登录用户id>>>>>>>>>>>>>>>>>"+userid);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<桩号>>>>>>>>>>>>>>>>>"+terminalSerialNumber);
                String openId = loginUser.getOpenId();
                String tenantId = loginUser.getTenantId();
                long l1 = System.currentTimeMillis();
                logger.info("<<<<<<<"+terminalSerialNumber+"开始启动充电获取用户时间>>>>>："+l1);
                R user = userTypeService.getUser(null, userid, userType, terminalSerialNumber,loginUser.getTenantId());
                long l2 = System.currentTimeMillis();
                logger.info("<<<<<<<"+terminalSerialNumber+"结束启动充电获取用户时间>>>>>："+l2);
                logger.info("<<<<<<<"+terminalSerialNumber+"启动充电时间差>>>>>："+(l2-l1));
                if (!userid.equals(userId) || user == null || user.getData() == null) {
                    return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "请重新登录");
                }
                Map<String, Object> userMessage = (Map<String, Object>)user.getData();
                if(UserTypeUtil.USER_TYPE !=userType){
                    if(Integer.valueOf(userMessage.get("number").toString())==0){
                        return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "此账号不能在该场站充电，请使用手机号登录");
                    }
                }
                xhpcChargeOrder.setDriverId(userMessage.get("phone").toString());
                String pattern = "^([0-9]{16})";
                Pattern compile = Pattern.compile(pattern);
                Matcher m = compile.matcher(terminalSerialNumber);
                if (terminalSerialNumber.length() != 16 || !m.matches()) {
                    return AjaxResult.error(1104, "无效的终端编号");
                }
                //终端信息
                XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(terminalSerialNumber,tenantId);
                if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
                    return AjaxResult.error(1104, "因限电该桩已停用,请选择其他桩进行充电");
                }else {
                    if(xhpcTerminal.getStatus()==1){
                        if(xhpcTerminal.getPrompt() !=null){
                            return AjaxResult.error(1104, xhpcTerminal.getPrompt());
                        }else{
                            return AjaxResult.error(1104, "桩已停用,请选择其他桩进行充电");
                        }
                    }
                }
                //查看充电用户金额是否大于5元
                //Map<String, Object> userMessage = xhpcChargeOrderMapper.getUserMessage(userId);
                BigDecimal a = new BigDecimal(5);
                if(userMessage != null && userMessage.get("userType") != null && UserTypeUtil.MOTORCADE_USER_TYPE==Integer.valueOf(userMessage.get("userType").toString())){
                    int motorcadeType = Integer.valueOf(userMessage.get("type").toString());
                    if(motorcadeType==0 && userMessage.get("remainingAmount") != null && a.compareTo(new BigDecimal(userMessage.get("remainingAmount").toString())) == 1){
                        return AjaxResult.error(1100, "金额小于5元,不能充电，请负责人充值");
                    }
                    if(motorcadeType==1 && a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1){
                        return AjaxResult.error(1100, "金额小于5元,不能充电，请负责人充值");
                    }
                }else{
                    if(4==Integer.valueOf(userMessage.get("userType").toString())){
                        if (userMessage == null || userMessage.get("balance") == null || a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1) {
                            return AjaxResult.error(1100, "金额小于5元,不能充电，请联系管理员充值");
                        }
                    }else{
                        if (userMessage == null || userMessage.get("balance") == null || a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1) {
                            return AjaxResult.error(1100, "金额小于5元,不能充电，请充值后再进行充电");
                        }
                    }

                }



                //充电用户是否存在异常的订单
                int j = xhpcChargeOrderMapper.countXhpcChargeOrder(userId,userType,tenantId);
                if (j > 0) {
                    return AjaxResult.error(1103, "你有异常订单未解决，请拨打客服电话进行解决");
                }
                //查看充电用户是否有申请退款的订单，还未处理
                if (Integer.parseInt(userMessage.get("isRefundApplication").toString()) != 0) {
                    return AjaxResult.error(1101, "你有申请退款订单在审核中,需要充电请取消申请退款");
                }
//                String i = xhpcChargeOrderMapper.countXhpcRealTimeOrder(userId,userType,tenantId);
//                if (!"".equals(i) && i!=null) {
//                    return AjaxResult.error(1102, "车辆正在充电,请查询车辆充电信息");
//                }
                if(Integer.valueOf(userMessage.get("sunchaSwitch").toString()) ==0 && userType != UserTypeUtil.MOTORCADE_TYPE){
                    //充电用户是否在充电中
                    String i = xhpcChargeOrderMapper.countXhpcRealTimeOrder(userId,userType,tenantId);
                    if (!"".equals(i) && i!=null) {
                        return AjaxResult.error(1102, "车辆正在充电,请查询车辆充电信息");
                    }
                }

                int internal = xhpcChargeOrderMapper.getInternalChargingStation(xhpcTerminal.getChargingStationId());

                if(internal==1){
                    if("BE".equals(userMessage.get("userTypeName").toString()) || "B".equals(userMessage.get("userTypeName").toString())){
                        int customersId = xhpcChargeOrderMapper.getInternalUserType(xhpcTerminal.getChargingStationId(), 1, Long.valueOf(userMessage.get("customersId").toString()));
                        if(customersId==0){
                            return AjaxResult.error(1102, "内部使用,请登录相应账号");
                        }
                    }else if("ST".equals(userMessage.get("userTypeName").toString()) || "S".equals(userMessage.get("userTypeName").toString())){
                        int customersId = xhpcChargeOrderMapper.getInternalUserType(xhpcTerminal.getChargingStationId(), 0, Long.valueOf(userMessage.get("communityId").toString()));
                        if(customersId==0){
                            return AjaxResult.error(1102, "内部使用,请登录相应账号");
                        }
                    }else if("CD".equals(userMessage.get("userTypeName").toString()) ||"D".equals(userMessage.get("userTypeName").toString()) ||"Z".equals(userMessage.get("userTypeName").toString())){
                        int customersId = xhpcChargeOrderMapper.getInternalUserType(xhpcTerminal.getChargingStationId(), 3, Long.valueOf(userMessage.get("motorcadeId").toString()));
                        if(customersId==0){
                            return AjaxResult.error(1102, "内部使用,请登录相应账号");
                        }
                    }else{
                        return AjaxResult.error(1102, "内部使用,请登录相应账号");
                    }
                }
                //是否插枪
                Map<String, Object> cacheMap = REDIS.getCacheMap("gun:" + terminalSerialNumber);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + terminalSerialNumber);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + cacheMap.toString());
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
                if(cacheMap==null){
                    return AjaxResult.error(1105, "未注册的终端,请选择其他终端充电");
                }else{
                    if(cacheMap.get("status") ==null){
                        return AjaxResult.error(1106, "未知的终端状态,请选择其他终端充电");
                    }else{
                        String status = cacheMap.get("status").toString();
                        //不同的状态
                        if("离线".equals(status)||"故障".equals(status) ||"充电".equals(status)){
                            return AjaxResult.error(1107, "此终端"+status+"中,请选择其他终端充电");
                        }
                    }
                    if(cacheMap.get("vehicleGunStatus") ==null){
                        return AjaxResult.error(1108, "未知的枪状态,请选择其他终端充电");
                    }else{
                        String vehicleGunStatus = cacheMap.get("vehicleGunStatus").toString();
                        if(!"是".equals(vehicleGunStatus)){
                            return AjaxResult.error(1109, "请插好充电枪");
                        }
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<终端编号>>>>"+terminalSerialNumber+">>>>>>>>>>>>>"+tenantId);

                //查询该场站是否有运行充电权限
                Map<String, Object> cacheMap1 = redisService.getCacheMap("chargingMethod:" + xhpcTerminal.getChargingStationId());

                if(cacheMap1 ==null){
                    return AjaxResult.error(1104, "该充电场站不支持扫描充电");
                }else{
                    if(cacheMap1.get("1")==null){
                        return AjaxResult.error(1104, "该充电场站不支持扫描充电");
                    }
                }

                //判断是否可以充电(黑名单)
                int blacklistUser =0;
                if(userMessage.get("vinSpecCode") !=null && userMessage.get("vehicleName") !=null){
                    blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(userMessage.get("phone").toString(), userMessage.get("vinSpecCode").toString(), userMessage.get("vehicleName").toString(), xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }else if(userMessage.get("vinSpecCode") !=null && userMessage.get("vehicleName") ==null){
                    blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(userMessage.get("phone").toString(), userMessage.get("vinSpecCode").toString(), null, xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }else if(userMessage.get("vinSpecCode") ==null && userMessage.get("vehicleName") !=null){
                    blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(userMessage.get("phone").toString(), null, userMessage.get("vehicleName").toString(), xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }else{
                    blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(userMessage.get("phone").toString(), null, null, xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }
                if(blacklistUser>0){
                    return AjaxResult.error(1104, "该车辆暂停充电,请联系客服");
                }

                if(Integer.valueOf(userMessage.get("sunchaSwitch").toString()) !=0){
                    return startUpSuncha(userMessage,xhpcChargeOrder,xhpcTerminal,tenantId,userType,terminalSerialNumber,type);
                }
                //余额
                String balance =null;
                if(userMessage != null && userMessage.get("userType") != null && UserTypeUtil.MOTORCADE_USER_TYPE==Integer.valueOf(userMessage.get("userType").toString())){
                    int motorcadeType = Integer.valueOf(userMessage.get("type").toString());
                    if(motorcadeType==0){
                        balance = new BigDecimal(userMessage.get("remainingAmount").toString()).multiply(new BigDecimal(100)).toString();
                    }else{
                        balance = new BigDecimal(userMessage.get("balance").toString()).multiply(new BigDecimal(100)).toString();
                    }
                }else{
                    balance = new BigDecimal(userMessage.get("balance").toString()).multiply(new BigDecimal(100)).toString();

                }
                //获取桩信息
                Map<String, Object> xhpcChargingPileById =xhpcChargeOrderMapper.getXhpcChargingPileById(xhpcTerminal.getChargingPileId(),tenantId);
                //启动充电
                StartChargingData startChargingData = new StartChargingData();
                //订单流水号 终端号+年月日时分秒+自增4位 共32位
                String orderNo = genOrder(terminalSerialNumber);

                startChargingData.setOrderNo(orderNo);
                if(userMessage.get("phone") !=null){
                    startChargingData.setTel(userMessage.get("phone").toString());
                    xhpcChargeOrder.setDriverId(userMessage.get("phone").toString());
                }
                startChargingData.setPileNo(xhpcTerminal.getPileSerialNumber());
                startChargingData.setGunId(xhpcTerminal.getSerialNumber().substring(14));
                startChargingData.setBalance(Double.valueOf(balance).intValue());
                if(xhpcChargingPileById.get("communicationProtocolVersion")!=null && !"".equals(xhpcChargingPileById.get("communicationProtocolVersion").toString())){
                    startChargingData.setVersion(xhpcChargingPileById.get("communicationProtocolVersion").toString());
                }else{
                    startChargingData.setVersion("0A");
                }
                //用户、桩、平台（最小的）
                int number =0;
                if(!"".equals(userMessage.get("socUser")) && userMessage.get("socUser") !=null && userMessage.get("socProtect") !=null && !"0".equals(userMessage.get("socProtect").toString())){
                    number =Integer.parseInt(userMessage.get("socUser").toString());
                }
                Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
                if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))  && !"".equals(operatorMessage.get("type")) ){
                    int operatorType = Integer.valueOf(operatorMessage.get("type").toString());
                    if(operatorType ==0){
                        if(number!=0){
                            if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                                number=Integer.parseInt(operatorMessage.get("soc").toString());
                            }
                        }else{
                            number=Integer.parseInt(operatorMessage.get("soc").toString());
                        }
                    }else{
                        String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                        if(!"".equals(soc) && soc!=null){
                            if(number!=0){
                                if(Integer.parseInt(soc)-number<0){
                                    number=Integer.parseInt(soc);
                                }
                            }else{
                                number=Integer.parseInt(soc);
                            }
                        }
                    }

                }else{
                    //平台
                    String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                    if(!"".equals(soc) && soc!=null){
                        if(number!=0){
                            if(Integer.parseInt(soc)-number<0){
                                number=Integer.parseInt(soc);
                            }
                        }else{
                            number=Integer.parseInt(soc);
                        }
                    }
                }
                if(number !=0){
                    startChargingData.setSoc(number);
                }
                //创建充电订单(充电启动soc初始值，结束是获取,并修改状态)
                xhpcChargeOrder.setChargingStationId(xhpcTerminal.getChargingStationId());
                xhpcChargeOrder.setUserId(userId);
                xhpcChargeOrder.setTerminalId(xhpcTerminal.getTerminalId());
                xhpcChargeOrder.setGunId(xhpcTerminal.getSerialNumber());
                xhpcChargeOrder.setSerialNumber(orderNo);
                xhpcChargeOrder.setSource(userType);
                xhpcChargeOrder.setStatus(-1);
                xhpcChargeOrder.setTenantId(tenantId);
                if (xhpcChargingPileById != null && xhpcChargingPileById.get("power") != null) {
                    xhpcChargeOrder.setPower(xhpcChargingPileById.get("power").toString());
                }
                if (type == 1) {
                    xhpcChargeOrder.setChargingMode("微信");
                } else if (type == 2){
                    xhpcChargeOrder.setChargingMode("支付宝");
                }else{
                    xhpcChargeOrder.setChargingMode("App");
                }
                xhpcChargeOrder.setCreateTime(Calendar.getInstance().getTime());
                xhpcChargeOrder.setType("91");
                if(userType==5 || userType==4){
                    xhpcChargeOrder.setMark(userMessage.get("mark").toString());
                    Long motorcadeId =Long.valueOf(userMessage.get("motorcadeId").toString());
                    xhpcChargeOrder.setMotorcadeId(motorcadeId);
                    if(0==Integer.valueOf(userMessage.get("type").toString()) && userType==5) {
                        BigDecimal remainingAmount = new BigDecimal(userMessage.get("remainingAmount").toString());
                        String totalKey =userMessage.get("mark").toString()+":"+motorcadeId;
                        redisService.setCacheObject(totalKey,remainingAmount);
                        xhpcChargeOrder.setMotorcadeType(0);
                    }else if (userType==4){
                        BigDecimal remainingAmount = new BigDecimal(userMessage.get("balance").toString());
                        String totalKey =userMessage.get("mark").toString()+":"+motorcadeId;
                        redisService.setCacheObject(totalKey,remainingAmount);
                        xhpcChargeOrder.setMotorcadeType(0);
                    }else{
                        xhpcChargeOrder.setMotorcadeType(1);
                    }
                }
                //获取车牌
                Map<String, Object> xhpcUserVehicleMessage = xhpcChargeOrderMapper.getXhpcUserVehicleMessage(xhpcChargeOrder.getUserId(), xhpcChargeOrder.getSource());
                if(xhpcUserVehicleMessage !=null && xhpcUserVehicleMessage.get("vehicleName") !=null){
                    xhpcChargeOrder.setPlateNum(xhpcUserVehicleMessage.get("vehicleName").toString());
                }

                if(userMessage.get("clearingType")!=null){
                    int clearingType = Integer.valueOf(userMessage.get("clearingType").toString());
                    xhpcChargeOrder.setClearingType(clearingType);
                }


                xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);

                //加用户金额缓存
                redisService.setCacheObject("YE"+xhpcChargeOrder.getSerialNumber(),new BigDecimal(userMessage.get("balance").toString()));

                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        R r1 = powerPileService.startCharging(startChargingData);
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<充电返回>>>>>>>>>>>>>>>>>");
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getCode() + ">>>>>>>>>>>>>>>>>");
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getMsg() + ">>>>>>>>>>>>>>>>>");
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getData() + ">>>>>>>>>>>>>>>>>");
                        if(r1.getCode() == 200){
                            try{
                                xhpcChargeOrder.setRateModelId(Long.valueOf(r1.getData().toString()));
                                xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);
                                //插一帧实时数据
                                extracted(xhpcChargeOrder);
                            }catch (Exception e){
                                e.printStackTrace();
                                logger.error("update order[{}] failed.", orderNo);
                            }
                        }
                    }
                });
                logger.info("<<<<<<<<<1111<<<<<<<<<<<<<<<C端订单号>>>>>>>>>>>>>>>>>:" + orderNo+"用户id:"+userId);
                logger.info("<<<<<<<<<2222<<<<<<<<<<<<<<<C端订单号>>>>>>>>>>>>>>>>>:" + orderNo+"用户id:"+userId);
                return AjaxResult.success();
            }else{
                return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "请重新登录");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "请确认设备网络状况正常和枪正确插好后重新尝试");
    }

    @Override
    public AjaxResult stopUp(HttpServletRequest request,Long userId, String serialNumber,Long chargingOrderId) {

        LoginUser loginUser = tokenService.getLoginUser(request);
        String tenantId = loginUser.getTenantId();
        String pattern = "^([0-9]{16})";
        Pattern compile = Pattern.compile(pattern);
        Matcher m = compile.matcher(serialNumber);
        if (serialNumber.length()!=16 || !m.matches()) {
            return AjaxResult.error(1104, "无效的终端编号");
        }
        //终端信息
        XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(serialNumber,tenantId);
        if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
            return AjaxResult.error(1104, "因限电该桩已停用,请选择其他桩进行充电");
        }else {
            if(xhpcTerminal.getStatus()==1){
                if(xhpcTerminal.getPrompt() !=null){
                    return AjaxResult.error(1104, xhpcTerminal.getPrompt());
                }else{
                    return AjaxResult.error(1104, "桩已停用,请选择其他桩进行充电");
                }
            }
        }

        //获取桩信息
        Map<String, Object> xhpcChargingPileById =
                xhpcChargeOrderMapper.getXhpcChargingPileById(xhpcTerminal.getChargingPileId(),tenantId);
        String version ="0A";
        if(xhpcChargingPileById.get("communicationProtocolVersion")!=null && !"".equals(xhpcChargingPileById.get("communicationProtocolVersion").toString())){
            version=xhpcChargingPileById.get("communicationProtocolVersion").toString();
        }
        //获取充电订单号
        XhpcChargeOrder order = xhpcChargeOrderMapper.getChargingOrderId(chargingOrderId);
        if(order ==null){
            return AjaxResult.error(1104, "未获取到充电订单,拨打客服电话或按急停按钮停止充电");
        }else{
            if(order.getSource()==UserTypeUtil.INTERNET_TYPE && order.getUserId()<10000){
                return AjaxResult.error(1104, "请在启动方停止充电");
            }
            if(!order.getUserId().equals(userId)){
                return AjaxResult.error(1104, "请登陆相应账号停止充电");
            }
        }

        R oa = powerPileService.stopCharging(order.getSerialNumber(), xhpcTerminal.getPileSerialNumber(),
                xhpcTerminal.getSerialNumber(), version);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<停止充电返回>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<"+oa.getCode()+">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<"+oa.getMsg()+">>>>>>>>>>>>>>>>>");
        if(oa.getCode() !=200){
            return AjaxResult.error(oa.getMsg());
        }
        return AjaxResult.success();
    }

    @Override
    public XhpcChargeOrder getSerialNumberMessage(String serialNumber) {

        return xhpcChargeOrderMapper.getSerialNumberMessage(serialNumber);
    }

    @Override
    public int getCount(Long userId,Long chargeOrderId,Integer source,String tenantId) {

        return xhpcChargeOrderMapper.getCount(userId,chargeOrderId,source,tenantId);
    }

    @Override
    public Map<String, Object> getPromotion() {

        return xhpcChargeOrderMapper.getPromotion();
    }

    @Override
    public void updateXhpcChargeOrder(XhpcChargeOrder xhpcChargeOrder) {

        xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);
    }

    @Override
    public Map<String, Object> getUserMessage(Long userId){

        return xhpcChargeOrderMapper.getUserMessage(userId);
    }

    @Override
    public int updateUserBalance(Long userId, BigDecimal balance,Integer source,String tenantId) {
        //修改用户余额
        if(UserTypeUtil.USER_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateUserBalance(userId, balance);
        }else if (UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateCommunityBalance(userId, balance);
        }else if(UserTypeUtil.CUSTOMERS_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateCustomersBalance(userId, balance);
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateAppInternetUserBalance(userId, balance);
        }
        return 0;
    }

    @Override
    public int updateeMotorcadeAmount(Long userId, BigDecimal surplusMoney,BigDecimal consumeMoney,Integer source,String tenantId) {
        //修改用户余额
        if(UserTypeUtil.MOTORCADE_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateMotorcadeRemainingAmont(userId, surplusMoney,consumeMoney);
        }else if(UserTypeUtil.MOTORCADE_USER_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateMotorcadeUserSurplusMoney(userId, surplusMoney,consumeMoney);
        }
        return 0;
    }


    @Override
    public int updateUserSunchaBalance(Long userId, BigDecimal balance, Integer source, String tenantId,Integer sunchaStatus) {
        //修改用户余额
        if(UserTypeUtil.USER_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateUserSunchaBalance(userId, balance,sunchaStatus);
        }else if (UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateCommunitySunchaBalance(userId, balance,sunchaStatus);
        }else if(UserTypeUtil.CUSTOMERS_TYPE.equals(source)){
            return xhpcChargeOrderMapper.updateCustomersSunchaBalance(userId, balance,sunchaStatus);
        }
        return 0;
    }

    @Override
    public Map<String, Object> getOperatorMessage(Long chargingStationId) {

        return xhpcChargeOrderMapper.getOperatorMessage(chargingStationId);
    }

    @Override
    public void addXhpcOrderRedisRecord(XhpcOrderRedisRecord xhpcOrderRedisRecord) {

        xhpcChargeOrderMapper.addXhpcOrderRedisRecord(xhpcOrderRedisRecord);
    }


    @Override
    public int addUserAccountStatement(Long userId, BigDecimal amount, BigDecimal remainingSum, Long chargeOrderId,
                                       Integer type, Date date,Integer source) {
        if(type ==7){
            return xhpcChargeOrderMapper.insertUserAccountStatementPlaceholder(userId, amount, remainingSum, chargeOrderId, type, date,source);
        }
        return xhpcChargeOrderMapper.insertUserAccountStatement(userId, amount, remainingSum, chargeOrderId, type, date,source);
    }

    @Override
    public XhpcChargeOrder getChargingOrderId(Long chargingOrderId) {

        return xhpcChargeOrderMapper.getChargingOrderId(chargingOrderId);
    }

    @Override
    public List<XhpcRate> getRateModelId(Long rateModelId) {
        return xhpcChargeOrderMapper.getRateModelId(rateModelId);
    }

    @Override
    public Map<String, Object> getXhpcChargingPile(Long terminalId) {
        return xhpcChargeOrderMapper.getXhpcChargingPile(terminalId);
    }

    @Override
    public List<Map<String,Object>> getXhpcChargeOrderStatus(Integer status,Integer number) {
        return xhpcChargeOrderMapper.getXhpcChargeOrderStatus(status,number);
    }

    @Override
    @Transactional
    public R startUpBy3rd(String internetSerialNumber, String driverId, Integer chargingAmt, String plateNum, Integer status, String connectorId) {
        try{
            //占位订单
            xhpcPlaceholderOrderService.getTimingPriceTime(connectorId);
        }catch (Exception e){
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<占位订单错误>>>>>>>>>>>>>>>>>"+e);
        }
        R r = new R();
//        String day = internetSerialNumber.substring(9, internetSerialNumber.length() - 4);
//        if (!isValidDate(day)) {
//            r.setCode(500);
//            return r;
//        }

        int resTime = xhpcInternetUserMapper.selectByOperatorIdEvcs(internetSerialNumber.substring(0, 9));
        if (resTime == 0) {
            r.setCode(500);
            r.setMsg("运营商无权限对此桩进行操作");
            return r;
        }

        //运营商该场站是否参与第三方充电
        int black = xhpcInternetUserMapper.getXhpcStationInternetBlacklist(internetSerialNumber.substring(0, 9), connectorId);
        if (black > 0) {
            r.setCode(500);
            r.setMsg("场站不支持该流量方充电");
            return r;
        }

        StartChargingData startChargingData = new StartChargingData();
        //500000 equals 500 yuan
        startChargingData.setBalance(chargingAmt * 100);
        startChargingData.setGunId(connectorId);
        startChargingData.setTel(driverId);
        startChargingData.setPileNo(connectorId.substring(0, connectorId.length() - 3));
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<第三方启动>>>>>>connectorId>>>>>>>>>>>"+connectorId);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<第三方启动>>>>>>>connectorId>>>>>>>>>>"+connectorId);
        //终端信息
        XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(connectorId,null);
        if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
            r.setCode(500);
//            String pilePrompt = redisService.getCacheObject("pilePrompt:000000");
//            if(!"".equals(pilePrompt) && pilePrompt !=null){
//                r.setMsg(pilePrompt);
//            }else{
//                r.setMsg("因限电该桩已停用,请选择其他桩进行充电");
//            }
            r.setMsg("因限电该桩已停用请选择其他桩进行充电");
            return r;
        }else {
            if(xhpcTerminal.getStatus()==1){
                if(xhpcTerminal.getPrompt() !=null){
                    r.setMsg(xhpcTerminal.getPrompt());
                }else{
                    r.setMsg("桩已停用,请选择其他桩进行充电");
                }
                return r;
            }
        }
        //终端状态是否空闲
        //是否插枪
        Map<String, Object> cacheMap = REDIS.getCacheMap("gun:" + connectorId);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + connectorId);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + cacheMap.toString());
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");

        if (cacheMap == null) {
            r.setCode(500);
            r.setMsg("未注册的终端,请选择其他终端充电");
            return r;
        } else {
            if (cacheMap.get("status") == null) {
                r.setCode(500);
                r.setMsg("未知的终端状态");
                return r;
            } else {
                String statusCache = cacheMap.get("status").toString();
                //不同的状态
                if ("离线".equals(statusCache) || "故障".equals(statusCache) || "充电".equals(statusCache)) {
                    if ("离线".equals(statusCache)) {
                        r.setCode(2);
                    } else {
                        r.setCode(500);
                    }
                    r.setMsg("此终端" + statusCache + "中,请选择其他终端充电");
                    return r;
                }
            }
            if (cacheMap.get("vehicleGunStatus") == null) {
                r.setCode(500);
                r.setMsg("未知的枪状态");
                return r;
            } else {
                String vehicleGunStatus = cacheMap.get("vehicleGunStatus").toString();
                if (!"是".equals(vehicleGunStatus)) {
                    r.setCode(500);
                    r.setMsg("未插枪");
                    return r;
                }
            }
        }

        //判断是否可以充电(黑名单)
        int blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(driverId, null, plateNum, xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        if(blacklistUser>0){
            r.setCode(500);
            r.setMsg("该车辆暂停充电,请联系客服");
            return r;
        }

        //启动充电
        //订单流水号 终端号+年月日时分秒+自增4位 共32位
        Date date = Calendar.getInstance().getTime();
        String format = DateUtil.format(date, "yyMMddHHmmss");
        //自增
        String orderNo = connectorId + format + StaticBeanUtil.seqDec("gun:" + connectorId + ".seqdec");

        startChargingData.setOrderNo(orderNo);
        startChargingData.setPileNo(xhpcTerminal.getPileSerialNumber());
        startChargingData.setGunId(xhpcTerminal.getSerialNumber().substring(14));
        startChargingData.setVersion("0A");


        //桩、平台（最小的）
        int number =0;

        logger.info("<<<<<<<<<<11<<<<<<<<<<<<<<number>>>>>>>>11>>>>>>>>>:" + number);
        Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
        if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))  && !"".equals(operatorMessage.get("type")) ){
            int operatorType = Integer.valueOf(operatorMessage.get("type").toString());
            if(operatorType ==0){
                if(number!=0){
                    if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                        number=Integer.parseInt(operatorMessage.get("soc").toString());
                    }
                }else{
                    number=Integer.parseInt(operatorMessage.get("soc").toString());
                }
            }else{
                String soc = redisService.getCacheObject("global:"+xhpcTerminal.getTenantId()+":SOC");
                if(!"".equals(soc) && soc!=null){
                    if(number!=0){
                        if(Integer.parseInt(soc)-number<0){
                            number=Integer.parseInt(soc);
                        }
                    }else{
                        number=Integer.parseInt(soc);
                    }
                }
            }

        }else{
            //平台
            String soc = redisService.getCacheObject("global:"+xhpcTerminal.getTenantId()+":SOC");
            if(!"".equals(soc) && soc!=null){
                if(number!=0){
                    if(Integer.parseInt(soc)-number<0){
                        number=Integer.parseInt(soc);
                    }
                }else{
                    number=Integer.parseInt(soc);
                }
            }
        }
        startChargingData.setSoc(number);

        int internal = xhpcChargeOrderMapper.getInternalChargingStation(xhpcTerminal.getChargingStationId());

        if(internal==1){
            return R.fail(500, "内部使用,请登录相应账号");
        }

        logger.info("<<<<<<<<<22<<<<<<<<<<<<<<<number>>>>>>>>>22>>>>>>>>:" + number);
        String startTime = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        Map<String, Object> extraData1 = xhpcChargeOrderMapper.selectDate3rdNeedBy(connectorId).get(0);
        Long terminalId = (Long) extraData1.get("terminalId");
        Double power = (Double) extraData1.get("power");
        Long chargingStationId = (Long) extraData1.get("chargingStationId");
        Map<String, Object> extraData2 = xhpcChargeOrderMapper.select3rdNameBy(internetSerialNumber.substring(0, 9)).get(0);
        String chargingMode = (String) extraData2.get("name");
        Long userId = (Long) extraData2.get("userId");

        XhpcChargeOrder xhpcChargeOrder =new XhpcChargeOrder();
        xhpcChargeOrder.setChargingStationId(chargingStationId);
        xhpcChargeOrder.setInternetSerialNumber(internetSerialNumber);
        xhpcChargeOrder.setSerialNumber(orderNo);
        xhpcChargeOrder.setDriverId(driverId);
        xhpcChargeOrder.setChargingAmt(chargingAmt);
        xhpcChargeOrder.setPlateNum(plateNum);
        xhpcChargeOrder.setStatus(status);
        xhpcChargeOrder.setCreateTime(new Date());
        xhpcChargeOrder.setTerminalId(terminalId);
        xhpcChargeOrder.setPower(power == null ? "120" : power.toString());
        xhpcChargeOrder.setSource(1);
        xhpcChargeOrder.setUserId(userId);
        xhpcChargeOrder.setChargingMode(chargingMode);
        xhpcChargeOrder.setClearingType(0);
        int res = xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);
        //int res = xhpcChargeOrderMapper.addBy3rd(internetSerialNumber, orderNo, driverId, chargingAmt, plateNum, status,
        // date,null, terminalId, power, chargingStationId, chargingMode, 1, userId);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<第三方启动订单号>>>>>>>>>>>>>>>>>:" + internetSerialNumber);



        executorService.execute(new Runnable() {
            @Override
            public void run() {
                R r1 = powerPileService.startCharging(startChargingData);
                try {
                    Long rateModelId = Long.valueOf(r1.getData().toString());
                    xhpcChargeOrder.setRateModelId(rateModelId);
                    xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("update order[{}] failed.", orderNo);
                }
            }
        });
        Map<String, Object> data = new HashMap<>();
        data.put("startTime", startTime);
        data.put("orderNo", orderNo);
        r.setData(data);
        if (res != 0) {
            r.setCode(200);
            r.setMsg("成功");
        } else {
            r.setCode(500);
            r.setMsg("内部服务调用错误");
        }
        return r;
    }

    @Override
    public void updateStatus() {
        //标记异常大于创建4小时，标记为异常 且没有实时数据的订单
        //查询是否有实时数据，没有实时数据查看该桩是否有成功的数据，有成功的数据表示该订单是无效的
        List<XhpcChargeOrder> list = xhpcChargeOrderMapper.getFourTimsStatus();
        if(list !=null && list.size()>0){
            for (XhpcChargeOrder xhpcChargeOrder:list) {
                Long chargeOrderId = xhpcChargeOrder.getChargeOrderId();
                if(UserTypeUtil.INTERNET_TYPE.equals(xhpcChargeOrder.getSource())){
                    //标记异常
                    xhpcChargeOrderMapper.updateStatus(2,chargeOrderId,"大于4小时没有结算的第三方订单，系统自动修改为异常订单");
                }else{
                    CacheRealtimeData cacheRealtimeData = redisService.getCacheObject("order:" + xhpcChargeOrder.getSerialNumber() + ".lord");
                    if(cacheRealtimeData ==null){
                        int count = xhpcChargeOrderMapper.getSerialNumberLike(xhpcChargeOrder.getSerialNumber().substring(0, 16), chargeOrderId);
                        if(count>0){
                            //有充电改为 由充电中变为启动充电中
                            xhpcChargeOrderMapper.updateStatus(-1,chargeOrderId,null);
                        }else{
                            //标记异常
                            xhpcChargeOrderMapper.updateStatus(2,chargeOrderId,"大于4小时没有结算的C端用户订单，系统自动修改为异常订单");
                        }
                    }else{

                        if(cacheRealtimeData.getCreateTime() !=null){
                            long l = System.currentTimeMillis();//秒
                            Date date = DateUtil.parse(cacheRealtimeData.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                            if(l-date.getTime()>360000){
                                xhpcChargeOrderMapper.updateStatus(2,chargeOrderId,"大于4小时没有结算的C端用户订单，系统自动修改为异常订单");
                            }
                        }else{
                            xhpcChargeOrderMapper.updateStatus(2,chargeOrderId,"大于4小时没有结算的C端用户订单，系统自动修改为异常订单");
                        }
                    }
                }
            }
        }
    }

    @Override
    public void updateStatusNull() {
        xhpcChargeOrderMapper.updateStatusNull();
    }

    @Override
    public void updateStatusNegativeOne() {
        xhpcChargeOrderMapper.updateStatusNegativeOne();
    }
    /**
     * 查询是否有异常订单
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getChargeOrderStatus() {
        return xhpcChargeOrderMapper.getChargeOrderStatus();
    }

    @Override
    public Map<String, Object> getXhpcChargingPileById(Long chargingPileId) {
        return xhpcChargeOrderMapper.getXhpcChargingPileById(chargingPileId,null);
    }

    @Override
    @Transactional
    public R cardStartup(Long userId, String serialNumber, Integer userType, String tenantId, Integer type,
                         String grantOperator, String rateModelId) {

        try{
            //占位订单
            xhpcPlaceholderOrderService.getTimingPriceTime(serialNumber);
        }catch (Exception e){
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<占位订单错误>>>>>>>>>>>>>>>>>"+e);
        }
        try {
            R user = userTypeService.getUser(null, userId, userType, null, tenantId);
            if (user == null || user.getData() == null) {
                return R.fail(1200, "无效用户");
            }
            Map<String, Object> userMessage = (Map<String, Object>) user.getData();
            //桩号是否有效
            String pattern = "^([0-9]{16})";
            Pattern compile = Pattern.compile(pattern);
            Matcher m = compile.matcher(serialNumber);
            if (serialNumber.length() != 16 || !m.matches()) {
                return R.fail(1104, "无效的终端编号");
            }
            //终端信息
            XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(serialNumber, tenantId);
            if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
                return R.fail(1104, "无效的终端编号");
            }else{
                if(xhpcTerminal.getStatus()==1){
                    if(xhpcTerminal.getPrompt() !=null){
                        return R.fail(1104, xhpcTerminal.getPrompt());
                    }
                    return R.fail(1104, "无效的终端编号");
                }
            }
            Map<String, Object> xhpcChargingPileById =
                    xhpcChargeOrderMapper.getXhpcChargingPileById(xhpcTerminal.getChargingPileId(), tenantId);
            if (xhpcChargingPileById.size() == 0) {
                return R.fail(1201, "无效运营商（桩的运营商和卡不对应）");
            }
            if (type != 0) {
                //获取桩信息
                if (!grantOperator.equals(xhpcChargingPileById.get("corpNo").toString())) {
                    return R.fail(1201, "无效运营商（桩的运营商和卡不对应）");
                }
            }
            BigDecimal a = new BigDecimal(5);
            if (userMessage == null || userMessage.get("balance") == null || a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1) {
                return R.fail(1100, "金额小于5元,不能充电，请充值后再进行充电");
            }
            //充电用户是否存在异常的订单
            int j = xhpcChargeOrderMapper.countXhpcChargeOrder(userId,userType,tenantId);
            if (j > 0) {
                return R.fail(1103, "你有异常订单未解决，请拨打客服电话进行解决");
            }
            //查看充电用户是否有申请退款的订单，还未处理
            if (Integer.parseInt(userMessage.get("isRefundApplication").toString()) != 0) {
                return R.fail(1101, "你有申请退款订单在审核中,需要充电请取消申请退款");
            }
            //充电用户是否在充电中
            if(Integer.valueOf(userMessage.get("sunchaSwitch").toString()) ==0) {
                String i = xhpcChargeOrderMapper.countXhpcRealTimeOrder(userId, userType, tenantId);
                if (!"".equals(i) && i != null) {
                    return R.fail(1102, "车辆正在充电,请查询车辆充电信息");
                }
            }
            Map<String, Object> cacheMap = REDIS.getCacheMap("gun:" + serialNumber);
            if(cacheMap==null){
                return R.fail(1105, "未注册的终端,请选择其他终端充电");
            }else{
                if(cacheMap.get("status") ==null){
                    return R.fail(1108, "未知的终端状态,请选择其他终端充电");
                }else{
                    String status = cacheMap.get("status").toString();
                    //不同的状态
                    if("离线".equals(status)){
                        return R.fail(1107, "此终端"+status+"中,请选择其他终端充电");
                    }
                    if ("故障".equals(status)) {
                        return R.fail(1111, "此终端"+status+"中,请选择其他终端充电");
                    }
                    if ("充电".equals(status) || StringUtils.isNumeric(status)) {
                        return R.fail(1112, "此终端"+status+"中,请选择其他终端充电");
                    }
                }
                if(cacheMap.get("vehicleGunStatus") ==null){
                    return R.fail(1108, "未知的枪状态,请选择其他终端充电");
                }else{
                    String vehicleGunStatus = cacheMap.get("vehicleGunStatus").toString();
                    if(!"是".equals(vehicleGunStatus)){
                        return R.fail(1109, "请插好充电枪");
                    }
                }
            }
            //查询该场站是否有运行充电权限
            Map<String, Object> cacheMap1 = redisService.getCacheMap("chargingMethod:" + xhpcTerminal.getChargingStationId());

            if(cacheMap1 ==null){
                return R.fail(1104, "该充电场站不支持刷卡充电");
            }else{
                if(cacheMap1.get("3")==null){
                    return R.fail(1104, "该充电场站不支持扫描充电");
                }
            }
            //判断是否可以充电(黑名单)
            int blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(userMessage.get("phone").toString(), userMessage.get("vinSpecCode").toString(), userMessage.get("vehicleName").toString(), xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            if(blacklistUser>0){
                return  R.fail(1104, "该车辆暂停充电,请联系客服");
            }
            //创建订单
            //订单流水号 终端号+年月日时分秒+自增4位 共32位
            String orderNo = genOrder(serialNumber);
            XhpcChargeOrder xhpcChargeOrder = new XhpcChargeOrder();
            xhpcChargeOrder.setChargingStationId(xhpcTerminal.getChargingStationId());
            xhpcChargeOrder.setUserId(userId);
            xhpcChargeOrder.setTerminalId(xhpcTerminal.getTerminalId());
            xhpcChargeOrder.setGunId(xhpcTerminal.getSerialNumber());
            xhpcChargeOrder.setSerialNumber(orderNo);
            xhpcChargeOrder.setSource(userType);
            xhpcChargeOrder.setStatus(-1);
            xhpcChargeOrder.setTenantId(tenantId);
            //获取桩信息
            Object power = xhpcChargingPileById.get("power");
            xhpcChargeOrder.setPower(power == null ? "120.0" : power.toString());
            xhpcChargeOrder.setRateModelId(Long.valueOf(rateModelId));
            xhpcChargeOrder.setChargingMode("刷卡");

            xhpcChargeOrder.setCreateTime(Calendar.getInstance().getTime());
            xhpcChargeOrder.setType("91");

            if(Integer.valueOf(userMessage.get("sunchaSwitch").toString()) !=0){
                startUpSuncha(userMessage, xhpcChargeOrder, xhpcTerminal, tenantId, userType, serialNumber, 4);
                return R.ok();
            }

            if(userMessage.get("clearingType")!=null){
                int clearingType = Integer.valueOf(userMessage.get("clearingType").toString());
                xhpcChargeOrder.setClearingType(clearingType);
            }
            xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);

            //插一帧实时数据
            extracted(xhpcChargeOrder);

            Map<String,Object> map =new HashMap<>();
            map.put("balance",userMessage.get("balance"));
            map.put("serialNumber",orderNo);
            //用户、桩、平台（最小的）
            int number =0;
            if(!"".equals(userMessage.get("socUser")) && userMessage.get("socUser") !=null && userMessage.get("socProtect") !=null && !"0".equals(userMessage.get("socProtect").toString())){
                number =Integer.parseInt(userMessage.get("socUser").toString());
            }
            Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
            if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))  && !"".equals(operatorMessage.get("type")) ){
                int operatorType = Integer.valueOf(operatorMessage.get("type").toString());
                if(operatorType ==0){
                    if(number!=0){
                        if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                            number=Integer.parseInt(operatorMessage.get("soc").toString());
                        }
                    }else{
                        number=Integer.parseInt(operatorMessage.get("soc").toString());
                    }
                }else{
                    String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                    if(!"".equals(soc) && soc!=null){
                        if(number!=0){
                            if(Integer.parseInt(soc)-number<0){
                                number=Integer.parseInt(soc);
                            }
                        }else{
                            number=Integer.parseInt(soc);
                        }
                    }
                }

            }else{
                //平台
                String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                if(!"".equals(soc) && soc!=null){
                    if(number!=0){
                        if(Integer.parseInt(soc)-number<0){
                            number=Integer.parseInt(soc);
                        }
                    }else{
                        number=Integer.parseInt(soc);
                    }
                }
            }
            map.put("soc",number);
            //加用户金额缓存
            redisService.setCacheObject("YE"+xhpcChargeOrder.getSerialNumber(),new BigDecimal(userMessage.get("balance").toString()));
            return R.ok(map);
        }catch (Exception e){
            //数据回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return R.fail();
    }

    @Override
    public R pileVin(String serialNumber, String vinNumber) {
        try{
            //占位订单
            xhpcPlaceholderOrderService.getTimingPriceTime(serialNumber);
        }catch (Exception e){
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<占位订单错误>>>>>>>>>>>>>>>>>"+e);
        }
        try{
            System.out.println("=========vin======serialNumber======="+serialNumber);
            System.out.println("=========vin======vinNumber======="+vinNumber);
            if("".equals(vinNumber) || vinNumber ==null ){
                return R.fail(1888, "VIN码为空");
            }else if (vinNumber.length()!=17){
                return R.fail(1880, "无效VIN码");
            }

            XhpcChargeOrder xhpcChargeOrder = new XhpcChargeOrder();
            String reverseVinNumber = new StringBuilder(vinNumber).reverse().toString();
            System.out.println("=========vin======reverseVinNumber======="+reverseVinNumber);
            Map<String, Object> stringObjectMap = xhpcChargeOrderMapper.getvVinNumber(vinNumber,reverseVinNumber);
            if(stringObjectMap ==null && stringObjectMap.get("appUerId")==null ||  stringObjectMap.get("source")==null){
                return R.fail(1888, "无效VIN码");
            }
            Long userId =Long.valueOf(stringObjectMap.get("appUerId").toString());
            Integer userType = Integer.parseInt(stringObjectMap.get("source").toString());
            //终端信息
            XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(serialNumber,null);
            if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
                return R.fail(1104, "因限电该桩已停用,请选择其他桩进行充电");
            }else {
                if(xhpcTerminal.getStatus()==1){
                    if(xhpcTerminal.getPrompt() !=null){
                        return R.fail(1104, xhpcTerminal.getPrompt());
                    }else{
                        return R.fail(1104, "桩已停用,请选择其他桩进行充电");
                    }
                }
            }
            String tenantId = xhpcTerminal.getTenantId();
            long l1 = System.currentTimeMillis();
            logger.info("<<<<<<<<<<1111<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
            R user = userTypeService.getUser(null, userId, userType, serialNumber,tenantId);
            long l2 = System.currentTimeMillis();
            logger.info("<<<<<<<<<<2222<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
            Map<String, Object> userMessage = (Map<String, Object>)user.getData();
            if(UserTypeUtil.USER_TYPE !=userType){
                if(Integer.valueOf(userMessage.get("number").toString())==0){
                    return R.fail(UserTypeUtil.LOGIN_TYPE, "此账号不能在该场站充电，请使用手机号登录");
                }
                logger.info("<<<<<<<<<<66666<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
            }
            String pattern = "^([0-9]{16})";
            Pattern compile = Pattern.compile(pattern);
            Matcher m = compile.matcher(serialNumber);
            if (serialNumber.length() != 16 || !m.matches()) {
                return R.fail(1104, "无效的终端编号");
            }
            //查看充电用户金额是否大于5元
            BigDecimal a = new BigDecimal(5);
            if(userMessage != null && userMessage.get("userType") != null && UserTypeUtil.MOTORCADE_USER_TYPE==Integer.valueOf(userMessage.get("userType").toString())){
                int motorcadeType = Integer.valueOf(userMessage.get("type").toString());
                if(motorcadeType==0 && userMessage.get("remainingAmount") != null && a.compareTo(new BigDecimal(userMessage.get("remainingAmount").toString())) == 1){
                    return R.fail(1100, "金额小于5元,不能充电，请负责人充值");
                }
                if(motorcadeType==1 && a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1){
                    return R.fail(1100, "金额小于5元,不能充电，请负责人充值");
                }
            }else{
                if(4==Integer.valueOf(userMessage.get("userType").toString())){
                    if (userMessage == null || userMessage.get("balance") == null || a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1) {
                        return R.fail(1100, "金额小于5元,不能充电，请联系管理员充值");
                    }
                }else{
                    if (userMessage == null || userMessage.get("balance") == null || a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1) {
                        return R.fail(1100, "金额小于5元,不能充电，请充值后再进行充电");
                    }
                }
            }
            logger.info("<<<<<<<<<<333<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
            //充电用户是否存在异常的订单
            int j = xhpcChargeOrderMapper.countXhpcChargeOrder(userId,userType,tenantId);
            if (j > 0) {
                return R.fail(1103, "你有异常订单未解决，请拨打客服电话进行解决");
            }
            //查看充电用户是否有申请退款的订单，还未处理
            if (Integer.parseInt(userMessage.get("isRefundApplication").toString()) != 0) {
                return R.fail(1101, "你有申请退款订单在审核中,需要充电请取消申请退款");
            }
            if(Integer.valueOf(userMessage.get("sunchaSwitch").toString()) ==0) {
                //充电用户是否在充电中
                String i = xhpcChargeOrderMapper.countXhpcRealTimeOrder(userId, userType, tenantId);
                if (!"".equals(i) && i != null) {
                    return R.fail(1102, "车辆正在充电,请查询车辆充电信息");
                }
            }
            //终端状态是否空闲
            //是否插枪
            Map<String, Object> cacheMap = REDIS.getCacheMap("gun:" + serialNumber);
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + serialNumber);
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + cacheMap.toString());
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");

            if(cacheMap==null){
                return R.fail(1105, "未注册的终端,请选择其他终端充电");
            }else{
                if(cacheMap.get("status") ==null){
                    return R.fail(1108, "未知的终端状态,请选择其他终端充电");
                }else{
                    String status = cacheMap.get("status").toString();
                    //不同的状态
                    if("离线".equals(status)){
                        return R.fail(1107, "此终端"+status+"中,请选择其他终端充电");
                    }
                    if("故障".equals(status)){
                        return R.fail(1111, "此终端"+status+"中,请选择其他终端充电");
                    }
                    if("充电".equals(status)){
                        return R.fail(1112, "此终端"+status+"中,请选择其他终端充电");
                    }
                }
                if(cacheMap.get("vehicleGunStatus") ==null){
                    return R.fail(1108, "未知的枪状态,请选择其他终端充电");
                }else{
                    String vehicleGunStatus = cacheMap.get("vehicleGunStatus").toString();
                    if(!"是".equals(vehicleGunStatus)){
                        return R.fail(1109, "请插好充电枪");
                    }
                }
            }

            //查询该场站是否有运行充电权限
            Map<String, Object> cacheMap1 = redisService.getCacheMap("chargingMethod:" + xhpcTerminal.getChargingStationId());

            if(cacheMap1 ==null){
                return R.fail(1104, "该充电场站不支持刷卡充电");
            }else{
                if(cacheMap1.get("2")==null){
                    return R.fail(1104, "该充电场站不支持扫描充电");
                }
            }
            //判断是否可以充电(黑名单)
//            int blacklistUser = xhpcChargeOrderMapper.getBlacklistUser(userMessage.get("phone").toString(), userMessage.get("vinSpecCode").toString(), userMessage.get("vehicleName").toString(), xhpcTerminal.getChargingStationId(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//            if(blacklistUser>0){
//                return  R.fail(1104, "该车辆暂停充电,请联系客服");
//            }
            //获取桩信息
            Map<String, Object> xhpcChargingPileById =xhpcChargeOrderMapper.getXhpcChargingPileById(xhpcTerminal.getChargingPileId(),tenantId);
            //启动充电
            StartChargingData startChargingData = new StartChargingData();
            //订单流水号 终端号+年月日时分秒+自增4位 共32位
            String orderNo = genOrder(serialNumber);

            startChargingData.setOrderNo(orderNo);
            if(userMessage.get("phone") !=null){
                startChargingData.setTel(userMessage.get("phone").toString());
                xhpcChargeOrder.setDriverId(userMessage.get("phone").toString());
            }
            startChargingData.setPileNo(xhpcTerminal.getPileSerialNumber());
            startChargingData.setGunId(xhpcTerminal.getSerialNumber().substring(14));
            if(userType==4 && 0==Integer.valueOf(userMessage.get("type").toString())){
                String balance = new BigDecimal(userMessage.get("remainingAmount").toString()).multiply(new BigDecimal(100)).toString();
                startChargingData.setBalance(Double.valueOf(balance).intValue());
            }else{
                String balance = new BigDecimal(userMessage.get("balance").toString()).multiply(new BigDecimal(100)).toString();
                startChargingData.setBalance(Double.valueOf(balance).intValue());
            }
            if(xhpcChargingPileById.get("communicationProtocolVersion")!=null && !"".equals(xhpcChargingPileById.get("communicationProtocolVersion").toString())){
                startChargingData.setVersion(xhpcChargingPileById.get("communicationProtocolVersion").toString());
            }else{
                startChargingData.setVersion("0A");
            }
            //用户、桩、平台（最小的）
            int number =0;
            if(!"".equals(userMessage.get("socUser")) && userMessage.get("socUser") !=null && userMessage.get("socProtect") !=null && !"0".equals(userMessage.get("socProtect").toString())){
                number =Integer.parseInt(userMessage.get("socUser").toString());
            }
            Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
            if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))  && !"".equals(operatorMessage.get("type")) ){
                int operatorType = Integer.valueOf(operatorMessage.get("type").toString());
                if(operatorType ==0){
                    if(number!=0){
                        if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                            number=Integer.parseInt(operatorMessage.get("soc").toString());
                        }
                    }else{
                        number=Integer.parseInt(operatorMessage.get("soc").toString());
                    }
                }else{
                    String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                    if(!"".equals(soc) && soc!=null){
                        if(number!=0){
                            if(Integer.parseInt(soc)-number<0){
                                number=Integer.parseInt(soc);
                            }
                        }else{
                            number=Integer.parseInt(soc);
                        }
                    }
                }

            }else{
                //平台
                String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                if(!"".equals(soc) && soc!=null){
                    if(number!=0){
                        if(Integer.parseInt(soc)-number<0){
                            number=Integer.parseInt(soc);
                        }
                    }else{
                        number=Integer.parseInt(soc);
                    }
                }
            }
            if(number !=0){
                startChargingData.setSoc(number);
            }
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<number>>>>>>>>>>>>>>>>>:"+number);
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<Soc>>>>>>>>>>>>>>>>>:"+startChargingData.getSoc());
            //创建充电订单(充电启动soc初始值，结束是获取,并修改状态)

            int internal = xhpcChargeOrderMapper.getInternalChargingStation(xhpcTerminal.getChargingStationId());

            if(internal==1){
                if("BE".equals(userMessage.get("userTypeName").toString()) || "B".equals(userMessage.get("userTypeName").toString())){
                    int customersId = xhpcChargeOrderMapper.getInternalUserType(xhpcTerminal.getChargingStationId(), 1, Long.valueOf(userMessage.get("customersId").toString()));
                    if(customersId==0){
                        return R.fail(1102, "内部使用,请登录相应账号");
                    }
                }else if("ST".equals(userMessage.get("userTypeName").toString()) || "S".equals(userMessage.get("userTypeName").toString())){
                    int customersId = xhpcChargeOrderMapper.getInternalUserType(xhpcTerminal.getChargingStationId(), 0, Long.valueOf(userMessage.get("communityId").toString()));
                    if(customersId==0){
                        return R.fail(1102, "内部使用,请登录相应账号");
                    }
                }else if("CD".equals(userMessage.get("userTypeName").toString())||"D".equals(userMessage.get("userTypeName").toString())||"Z".equals(userMessage.get("userTypeName").toString())){
                    int customersId = xhpcChargeOrderMapper.getInternalUserType(xhpcTerminal.getChargingStationId(), 3, Long.valueOf(userMessage.get("motorcadeId").toString()));
                    if(customersId==0){
                        return R.fail(1102, "内部使用,请登录相应账号");
                    }
                }else{
                    return R.fail(1102, "内部使用,请登录相应账号");
                }
            }


            xhpcChargeOrder.setChargingStationId(xhpcTerminal.getChargingStationId());
            xhpcChargeOrder.setUserId(userId);
            xhpcChargeOrder.setTerminalId(xhpcTerminal.getTerminalId());
            xhpcChargeOrder.setGunId(xhpcTerminal.getSerialNumber());
            xhpcChargeOrder.setSerialNumber(orderNo);
            xhpcChargeOrder.setSource(userType);
            xhpcChargeOrder.setStatus(-1);
            xhpcChargeOrder.setTenantId(tenantId);
            if (xhpcChargingPileById != null && xhpcChargingPileById.get("power") != null) {
                xhpcChargeOrder.setPower(xhpcChargingPileById.get("power").toString());
            }
            if(userMessage.get("vehicleName") !=null){
                xhpcChargeOrder.setPlateNum(userMessage.get("vehicleName").toString());
            }
            xhpcChargeOrder.setChargingMode("VIN码");
            xhpcChargeOrder.setCreateTime(Calendar.getInstance().getTime());
            xhpcChargeOrder.setType("91");
            xhpcChargeOrder.setVinNormal(vinNumber);
            if(userType==5 || userType==4){
                xhpcChargeOrder.setMark(userMessage.get("mark").toString());
                Long motorcadeId =Long.valueOf(userMessage.get("motorcadeId").toString());
                xhpcChargeOrder.setMotorcadeId(motorcadeId);
                if(0==Integer.valueOf(userMessage.get("type").toString()) || userType==4) {
                    BigDecimal remainingAmount = new BigDecimal(userMessage.get("remainingAmount").toString());
                    String totalKey =userMessage.get("mark").toString()+":"+motorcadeId;
                    redisService.setCacheObject(totalKey,remainingAmount);
                }else{
                    xhpcChargeOrder.setMotorcadeType(1);
                }
            }
            if(Integer.valueOf(userMessage.get("sunchaSwitch").toString()) !=0){
                startUpSuncha(userMessage,xhpcChargeOrder,xhpcTerminal,tenantId,userType,serialNumber,5);
                return R.ok();
            }
            if(userMessage.get("clearingType")!=null){
                int clearingType = Integer.valueOf(userMessage.get("clearingType").toString());
                xhpcChargeOrder.setClearingType(clearingType);
            }
            //加用户金额缓存
            //redisService.setCacheObject("YE"+xhpcChargeOrder.getSerialNumber(),new BigDecimal(userMessage.get("balance").toString()));
            xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);

//            executorService.execute(new Runnable() {
//                @Override
//                public void run() {
//                    R r1 = powerPileService.startCharging(startChargingData);
//                    logger.info("<<<<<<<<<<<<<<<<<<<<<VIN<<<充电返回>>>>>>VIN>>>>>>>>>>>");
//                    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getCode() + ">>>>>>>>>>>>>>>>>");
//                    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getMsg() + ">>>>>>>>>>>>>>>>>");
//                    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getData() + ">>>>>>>>>>>>>>>>>");
//                    if(r1.getCode() == 200){
//                        try{
//                            xhpcChargeOrder.setRateModelId(Long.valueOf(r1.getData().toString()));
//                            xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);
//                            //插一帧实时数据
//                            extracted(xhpcChargeOrder);
//                        }catch (Exception e){
//                            e.printStackTrace();
//                            logger.error("update order[{}] failed.", orderNo);
//                        }
//                    }
//
//                }
//            });
            Map<String,Object> map =new HashMap<>();
            if(userType==4 && 0==Integer.valueOf(userMessage.get("type").toString())){
                map.put("balance",userMessage.get("remainingAmount"));
            }else{
                map.put("balance",userMessage.get("balance"));
            }

            map.put("serialNumber",orderNo);
            //用户、桩、平台（最小的）
            map.put("soc",number);
            return R.ok(map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    @Override
    public Map<String, Object> getSerialNumberOrder(String serialNumber) {

        return xhpcChargeOrderMapper.getSerialNumberOrder(serialNumber);
    }

    @Override
    public void constantSoc(String orderNo, String soc) {
        try{

            XhpcChargeOrder serialNumberMessage = xhpcChargeOrderMapper.getSerialNumberMessage(orderNo);

            Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(serialNumberMessage.getChargingStationId());
            if(UserTypeUtil.USER_TYPE.equals(serialNumberMessage.getSource())){
                Map<String, Object> userMessage = xhpcChargeOrderMapper.getUserMessage(serialNumberMessage.getUserId());
                if(serialNumberMessage.getChargingMode().equals("微信")){
                    String phoneObject = redisService.getCacheObject("WXToken:wxd0a48e00319ef8a7");
                    String serialNumber = serialNumberMessage.getSerialNumber();
                    int zhuang = Integer.parseInt(serialNumber.substring(10,14));
                    int qiang = Integer.parseInt(serialNumber.substring(14,16));
                    String spear = "A";
                    if(qiang==2){
                        spear = "B";
                    }else if(qiang==3){
                        spear = "C";
                    }else if(qiang==4){
                        spear = "D";
                    }
                    operatorMessage.get("chargingStationName").toString().replace("翔桦充电","");
                    String str = operatorMessage.get("chargingStationName").toString().replace("翔桦充电", "");
                    if(str.length()>13){
                        str =str.substring(0,13);
                    }
                    WxMessageSend(userMessage.get("weixinOpenId").toString(),phoneObject,str+"-"+zhuang+"桩"+"-"+spear+"枪",soc);
                }else if(serialNumberMessage.getChargingMode().equals("支付宝")){
                    HashMap<String, String> paramMap = new HashMap<>();
                    paramMap.put("battery", soc);
                    paramMap.put("phone", userMessage.get("phone").toString());
                    paramMap.put("content", "【翔桦充电】尊敬的用户，你的车辆已充电达至设定的SOC(" + soc + "%)。");
                    smsService.sendNotice(paramMap);
                }
            }
        }catch (Exception e){

        }
    }

    public static boolean isValidDate(String str) {
        try {
            if (0 != str.length()) {
                if (str.length() == 14) {
                    // 闰年标志
                    boolean isLeapYear = false;
                    String year = str.substring(0, 4);
                    String month = str.substring(4, 6);
                    String day = str.substring(6, 8);
                    String hour = str.substring(8, 10);
                    String minute = str.substring(10, 12);
                    String second = str.substring(12, 14);
                    int intYear = Integer.parseInt(year);
                    // 判断年份是否合法
                    if (intYear < 1900 || intYear > 2200) {
                        return false;
                    }
                    // 判断是否为闰年
                    if (intYear % 4 == 0 && intYear % 100 != 0 || intYear % 400 == 0) {
                        isLeapYear = true;
                    }
                    // 判断月份
                    // 1.判断月份
                    if (month.startsWith("0")) {
                        String unitMonth = month.substring(1, 2);
                        int intUnitMonth = Integer.parseInt(unitMonth);
                        if (intUnitMonth == 0) {
                            return false;
                        }
                        if (intUnitMonth == 2) {
                            // 获取2月的天数
                            int intDay4February = Integer.parseInt(day);
                            if (isLeapYear) {
                                if (intDay4February > 29) {
                                    return false;
                                }
                            } else {
                                if (intDay4February > 28) {
                                    return false;
                                }
                            }
                        }
                    } else {
                        // 2.判断非0打头的月份是否合法
                        int intMonth = Integer.parseInt(month);
                        if (intMonth != 10 && intMonth != 11 && intMonth != 12) {
                            return false;
                        }
                    }
                    // 判断日期
                    // 1.判断日期
                    if (day.startsWith("0")) {
                        String unit4Day = day.substring(1, 2);
                        int intUnit4Day = Integer.parseInt(unit4Day);
                        if (intUnit4Day == 0) {
                            return false;
                        }
                    } else {
                        // 2.判断非0打头的日期是否合法
                        int intDay = Integer.parseInt(day);
                        if (intDay < 10 || intDay > 31) {
                            return false;
                        }
                    }
                    // 判断时间
                    int intHour = Integer.parseInt(hour);
                    int intMinute = Integer.parseInt(minute);
                    int intSecond = Integer.parseInt(second);
                    return intHour >= 0 && intHour <= 23 && intMinute >= 0 && intMinute <= 59 && intSecond >= 0 && intSecond <= 59;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void extracted(XhpcChargeOrder xhpcChargeOrder) {
        try{
            XhpcRealTimeOrder xhpcRealTimeOrder = new XhpcRealTimeOrder();
            String orderNo = xhpcChargeOrder.getSerialNumber();
            xhpcRealTimeOrder.setChargingOrderId(xhpcChargeOrder.getChargeOrderId());
            xhpcRealTimeOrder.setTransactionNumber(orderNo);
            xhpcRealTimeOrder.setPileNumber(orderNo.substring(0,14));
            xhpcRealTimeOrder.setGunNumber(orderNo.substring(15,16));
            xhpcRealTimeOrder.setPileGunStatus(0);
            xhpcRealTimeOrder.setVehicleGunStatus(0);
            xhpcRealTimeOrder.setSoc("0");
            xhpcRealTimeOrder.setChargingTime("0分");
            xhpcRealTimeOrder.setChargingDegree(new BigDecimal(0));
            xhpcRealTimeOrder.setStatus(3);
            xhpcRealTimeOrder.setCreateTime(Calendar.getInstance().getTime());
            xhpcRealTimeOrder.setUserId(xhpcChargeOrder.getUserId());
            Long chargingStationId = xhpcChargeOrder.getChargingStationId();
            xhpcRealTimeOrder.setChargingStationId(chargingStationId);
            xhpcRealTimeOrderService.addXhpcRealTimeOrder(xhpcRealTimeOrder);
        }catch (Exception e){

        }
    }

    public static void WxMessageSend(String openid,String token,String chargingStationName,String soc){
        try{
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;

            Map<String, Object> map = new HashMap<>();
            map.put("touser", openid);
            map.put("template_id", "z7Eh6_fjwMQ-JYtpD2K0KegtGaDsKZwd7h8IZznAm1k");
            map.put("page", "pages/transition/transition");
            map.put("miniprogram_state", "developer");
            map.put("lang", "zh_CN");

            Map<String, Object> map1 = new LinkedHashMap<>();
            map1.put("value", chargingStationName);
            Map<String, Object> map11 = new LinkedHashMap<>();
            map11.put("thing1", map1);

            Map<String, Object> map2 = new LinkedHashMap<>();
            map2.put("value", "车辆已充电达至设定的SOC:"+soc+"%");
            Map<String, Object> map22 = new LinkedHashMap<>();
            map22.put("thing2", map2);
            map11.putAll(map22);
            Map<String, Object> map3 = new LinkedHashMap<>();
            map3.put("value", "充电已完成请尽快离场,超时要收占位费哟");
            Map<String, Object> map33 = new LinkedHashMap<>();
            map33.put("thing3", map3);
            map11.putAll(map33);

            Map<String, Object> map4 = new LinkedHashMap<>();
            map4.put("value", "028-87500096");
            Map<String, Object> map44 = new LinkedHashMap<>();
            map44.put("phone_number4", map4);
            map11.putAll(map44);

            map.put("data", map11);
            JSONObject json = new JSONObject(map);
            System.out.println("json :"+json);
            String result = HttpUtils.post(url, json);
            JSONObject jsonObject =JSON.parseObject(result);
            System.out.println("jsonObject :"+jsonObject);
        }catch (Exception e){

        }
    }
    @Override
    public void zhbSoc(String orderNo, String soc) {

    }

    @Override
    public Map<String, Object> getXhpcBarrierGate(Long chargingStationId) {
        return xhpcChargeOrderMapper.getXhpcBarrierGate(chargingStationId);
    }

    @Override
    public R cycStartUp(HttpServletRequest request, Long userId, String serialNumber, Integer type, Integer source,BigDecimal money,String phone,String PlateNum) {
        try{
            //占位订单
            xhpcPlaceholderOrderService.getTimingPriceTime(serialNumber);
        }catch (Exception e){
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<占位订单错误>>>>>>>>>>>>>>>>>"+e);
        }
        R r = new R();
        //川逸充的对接平爱operatorId
        String operatorIdEvcs ="MA6CC2LK7";
        int resTime = xhpcInternetUserMapper.selectByOperatorIdEvcs(operatorIdEvcs);
        if (resTime == 0) {
            r.setCode(500);
            r.setMsg("运营商无权限对此桩进行操作");
            return r;
        }
        //运营商该场站是否参与第三方充电
        int black = xhpcInternetUserMapper.getXhpcStationInternetBlacklist(operatorIdEvcs, serialNumber);
        if (black > 0) {
            r.setCode(500);
            r.setMsg("场站不支持该流量方充电");
            return r;
        }
        StartChargingData startChargingData = new StartChargingData();
        startChargingData.setBalance(money.multiply(new BigDecimal(100)).intValue());
        startChargingData.setGunId(serialNumber);
        startChargingData.setTel(phone);
        startChargingData.setPileNo(serialNumber.substring(0, serialNumber.length() - 3));

        XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(serialNumber,null);
        if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
            r.setCode(500);
            r.setMsg("因限电该桩已停用请选择其他桩进行充电");
            return r;
        }else {
            if(xhpcTerminal.getStatus()==1){
                if(xhpcTerminal.getPrompt() !=null){
                    r.setMsg(xhpcTerminal.getPrompt());
                }else{
                    r.setMsg("桩已停用,请选择其他桩进行充电");
                }
                return r;
            }
        }
        //终端状态是否空闲\是否插枪
        Map<String, Object> cacheMap = REDIS.getCacheMap("gun:" + serialNumber);
        if (cacheMap == null) {
            r.setCode(500);
            r.setMsg("未注册的终端,请选择其他终端充电");
            return r;
        } else {
            if (cacheMap.get("status") == null) {
                r.setCode(500);
                r.setMsg("未知的终端状态");
                return r;
            } else {
                String statusCache = cacheMap.get("status").toString();
                //不同的状态
                if ("离线".equals(statusCache) || "故障".equals(statusCache) || "充电".equals(statusCache)) {
                    if ("离线".equals(statusCache)) {
                        r.setCode(2);
                    } else {
                        r.setCode(500);
                    }
                    r.setMsg("此终端" + statusCache + "中,请选择其他终端充电");
                    return r;
                }
            }
            if (cacheMap.get("vehicleGunStatus") == null) {
                r.setCode(500);
                r.setMsg("未知的枪状态");
                return r;
            } else {
                String vehicleGunStatus = cacheMap.get("vehicleGunStatus").toString();
                if (!"是".equals(vehicleGunStatus)) {
                    r.setCode(500);
                    r.setMsg("未插枪");
                    return r;
                }
            }
        }
        //启动充电
        //订单流水号 终端号+年月日时分秒+自增4位 共32位
        Date date = Calendar.getInstance().getTime();
        String format = DateUtil.format(date, "yyMMddHHmmss");
        String format1 = DateUtil.format(date, "yyyyMMddHHmmss");
        //自增
        String orderNo = serialNumber + format + StaticBeanUtil.seqDec("gun:" + serialNumber + ".seqdec");

        startChargingData.setOrderNo(orderNo);
        startChargingData.setPileNo(xhpcTerminal.getPileSerialNumber());
        startChargingData.setGunId(xhpcTerminal.getSerialNumber().substring(14));
        startChargingData.setVersion("0A");
        //桩、平台（最小的）
        int number =0;
        //平台
        String soc = redisService.getCacheObject("global:"+xhpcTerminal.getTenantId()+":SOC");
        if(!"".equals(soc) && soc!=null){
            if(number!=0){
                if(Integer.parseInt(soc)-number<0){
                    number=Integer.parseInt(soc);
                }
            }else{
                number=Integer.parseInt(soc);
            }
        }
        Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
        if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))){
            if(number!=0){
                if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                    number=Integer.parseInt(operatorMessage.get("soc").toString());
                }
            }else{
                number=Integer.parseInt(operatorMessage.get("soc").toString());
            }

        }
        startChargingData.setSoc(number);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<number>>>>>>>>>>>>>>>>>:" + number);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<Soc>>>>>>>>>>>>>>>>>:" + startChargingData.getSoc());
        String startTime = DateUtil.format(date, "yyyy-MM-dd HH: mm: ss");
        Map<String, Object> extraData1 = xhpcChargeOrderMapper.selectDate3rdNeedBy(serialNumber).get(0);
        Long terminalId = (Long) extraData1.get("terminalId");
        Double power = (Double) extraData1.get("power");
        Long chargingStationId = (Long) extraData1.get("chargingStationId");

        XhpcChargeOrder xhpcChargeOrder =new XhpcChargeOrder();
        xhpcChargeOrder.setChargingStationId(chargingStationId);
        xhpcChargeOrder.setInternetSerialNumber(operatorIdEvcs+format1 + StaticBeanUtil.seqDec("gun:" + serialNumber + ".seqdec"));
        xhpcChargeOrder.setSerialNumber(orderNo);
        xhpcChargeOrder.setDriverId(phone);
        xhpcChargeOrder.setChargingAmt(money.intValue());
        xhpcChargeOrder.setPlateNum(PlateNum);
        xhpcChargeOrder.setStatus(-1);
        Date date1 = new Date();
        xhpcChargeOrder.setCreateTime(date1);
        xhpcChargeOrder.setTerminalId(terminalId);
        xhpcChargeOrder.setPower(power == null ? "120" : power.toString());
        xhpcChargeOrder.setSource(1);
        xhpcChargeOrder.setUserId(userId);
        xhpcChargeOrder.setChargingMode("川逸充");

        Map<String, Object> chargingStationMap = xhpcChargeOrderMapper.getChargingStationById(chargingStationId);
        if(chargingStationMap==null){
            r.setCode(500);
            r.setMsg("无效场站");
            return r;
        }
        int res = xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);
        logger.info("<<<<<<<<<<<<<<<<川逸充<<<<<<<<第三方启动订单号>>>>>>>>>>>>>>>>>:" + xhpcChargeOrder.getInternetSerialNumber());

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                R r1 = powerPileService.startCharging(startChargingData);
                try {
                    Long rateModelId = Long.valueOf(r1.getData().toString());
                    xhpcChargeOrder.setRateModelId(rateModelId);
                    xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);

                    Map<String, Object> pushOrder = new HashMap<>();
                    pushOrder.put("startChargeSeqStat", 2);
                    pushOrder.put("internetSerialNumber", xhpcChargeOrder.getInternetSerialNumber());
                    pushOrder.put("connectorID", serialNumber);
                    pushOrder.put("startChargeNotificationStat", 0);
                    pushOrder.put("chargeOrderInfoNotificationStat", 0);
                    pushOrder.put("operatorId3rdpty", operatorIdEvcs);
                    pushOrder.put("startTime", DateUtil.format(date1,"yyyy-MM-dd HH:mm:ss"));
                    pushOrder.put("phone", phone);
                    pushOrder.put("operatorId3rdptyName", "CYC");

                    REDIS.setCacheMap("pushOrder:".concat(orderNo), pushOrder);

                    String gun ="gun:"+serialNumber;
                    Map<String, Object> cacheMap1 = REDIS.getCacheMap(gun);
                    //川逸充订单号，防止推送状态
                    cacheMap1.put("cycOrder",xhpcChargeOrder.getInternetSerialNumber());
                    REDIS.setCacheMap(gun, cacheMap1);

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("update order[{}] failed.", orderNo);
                }
            }
        });
        Map<String, Object> data = new HashMap<>();
        data.put("startTime", startTime);
        data.put("orderNo", orderNo);
        r.setData(data);
        if (res != 0) {
            r.setCode(200);
            r.setMsg("成功");
        } else {
            r.setCode(500);
            r.setMsg("内部服务调用错误");
        }
        return r;
    }

    @Override
    @Transactional
    public AjaxResult chargingCapacityStartUp(HttpServletRequest request, Long userId, String terminalSerialNumber, Integer type, Integer chargingCapacity) {
        try{
            //占位订单
            xhpcPlaceholderOrderService.getTimingPriceTime(terminalSerialNumber);
        }catch (Exception e){
            logger.info("<<<<<<<<<<<<<<<<<<<<<<<占位订单错误>>>>>>>>>>>>>>>>>"+e);
        }
        try{
            XhpcChargeOrder xhpcChargeOrder = new XhpcChargeOrder();
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser)) {
                String username = loginUser.getUsername();
                Integer userType = loginUser.getUserType();
                Long userid = loginUser.getUserid();
                if (chargingCapacity == null) {
                    return AjaxResult.error(1104, "请输入充电量");
                }else{
                    if(chargingCapacity>=65535){
                        return AjaxResult.error(1104, "输入充电量超出了限制");
                    }
                    if(chargingCapacity<=0){
                        return AjaxResult.error(1104, "输入充电量应该大于0");
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<登录用户id>>>>>>>>>>>>>>>>>"+userid);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<桩号>>>>>>>>>>>>>>>>>"+terminalSerialNumber);
                String openId = loginUser.getOpenId();
                String tenantId = loginUser.getTenantId();
                long l1 = System.currentTimeMillis();
                logger.info("<<<<<<<"+terminalSerialNumber+"开始启动充电获取用户时间>>>>>："+l1);
                R user = userTypeService.getUser(null, userid, userType, terminalSerialNumber,loginUser.getTenantId());
                long l2 = System.currentTimeMillis();
                logger.info("<<<<<<<"+terminalSerialNumber+"结束启动充电获取用户时间>>>>>："+l2);
                logger.info("<<<<<<<"+terminalSerialNumber+"启动充电时间差>>>>>："+(l2-l1));
                if (!userid.equals(userId) || user == null || user.getData() == null) {
                    return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "请重新登录");
                }
                Map<String, Object> userMessage = (Map<String, Object>)user.getData();
                if(UserTypeUtil.USER_TYPE !=userType){
                    if(Integer.valueOf(userMessage.get("number").toString())==0){
                        return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "此账号不能在该场站充电，请使用手机号登录");
                    }
                }
                xhpcChargeOrder.setDriverId(userMessage.get("phone").toString());
                String pattern = "^([0-9]{16})";
                Pattern compile = Pattern.compile(pattern);
                Matcher m = compile.matcher(terminalSerialNumber);
                if (terminalSerialNumber.length() != 16 || !m.matches()) {
                    return AjaxResult.error(1104, "无效的终端编号");
                }
                logger.info("<<<<<<<"+terminalSerialNumber+"启动充电时间差>>111>>>："+(l2-l1));
                //终端信息
                XhpcTerminal xhpcTerminal = xhpcChargeOrderMapper.getXhpcTerminalSerialNumber(terminalSerialNumber,tenantId);
                if (xhpcTerminal == null || xhpcTerminal.getTerminalId() == null || xhpcTerminal.getChargingPileId() == null || xhpcTerminal.getPileSerialNumber() == null) {
                    return AjaxResult.error(1104, "因限电该桩已停用,请选择其他桩进行充电");
                }else {
                    if(xhpcTerminal.getStatus()==1){
                        if(xhpcTerminal.getPrompt() !=null){
                            return AjaxResult.error(1104, xhpcTerminal.getPrompt());
                        }else{
                            return AjaxResult.error(1104, "桩已停用,请选择其他桩进行充电");
                        }
                    }
                }
                logger.info("<<<<<<<"+terminalSerialNumber+"启动充电时间差>>222>>>："+(l2-l1));
                //查看充电用户金额是否大于5元
                //Map<String, Object> userMessage = xhpcChargeOrderMapper.getUserMessage(userId);
                BigDecimal a = new BigDecimal(5);
                if (userMessage == null || userMessage.get("balance") == null || a.compareTo(new BigDecimal(userMessage.get("balance").toString())) == 1) {
                    return AjaxResult.error(1100, "金额小于5元,不能充电，请充值后再进行充电");
                }
                //充电用户是否存在异常的订单
                int j = xhpcChargeOrderMapper.countXhpcChargeOrder(userId,userType,tenantId);
                if (j > 0) {
                    return AjaxResult.error(1103, "你有异常订单未解决，请拨打客服电话进行解决");
                }
                //查看充电用户是否有申请退款的订单，还未处理
                if (Integer.parseInt(userMessage.get("isRefundApplication").toString()) != 0) {
                    return AjaxResult.error(1101, "你有申请退款订单在审核中,需要充电请取消申请退款");
                }
                //充电用户是否在充电中
                String i = xhpcChargeOrderMapper.countXhpcRealTimeOrder(userId,userType,tenantId);
                if (!"".equals(i) && i!=null) {
                    return AjaxResult.error(1102, "车辆正在充电,请查询车辆充电信息");
                }
                logger.info("<<<<<<<"+terminalSerialNumber+"启动充电时间差>>3333>>>："+(l2-l1));
                //终端状态是否空闲
                //是否插枪
                Map<String, Object> cacheMap = REDIS.getCacheMap("gun:" + terminalSerialNumber);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + terminalSerialNumber);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>" + cacheMap.toString());
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<cacheMap>>>>>>>>>>>>>>>>>");

                if(cacheMap==null){
                    return AjaxResult.error(1105, "未注册的终端,请选择其他终端充电");
                }else{
                    if(cacheMap.get("status") ==null){
                        return AjaxResult.error(1106, "未知的终端状态,请选择其他终端充电");
                    }else{
                        String status = cacheMap.get("status").toString();
                        //不同的状态
                        if("离线".equals(status)||"故障".equals(status) ||"充电".equals(status)){
                            return AjaxResult.error(1107, "此终端"+status+"中,请选择其他终端充电");
                        }
                    }
                    if(cacheMap.get("vehicleGunStatus") ==null){
                        return AjaxResult.error(1108, "未知的枪状态,请选择其他终端充电");
                    }else{
                        String vehicleGunStatus = cacheMap.get("vehicleGunStatus").toString();
                        if(!"是".equals(vehicleGunStatus)){
                            return AjaxResult.error(1109, "请插好充电枪");
                        }
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<终端编号>>>>"+terminalSerialNumber+">>>>>>>>>>>>>"+tenantId);

                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<终端编号>>>>>>>>>>>>>>>>");
                //余额
                String balance = new BigDecimal(userMessage.get("balance").toString()).multiply(new BigDecimal(100)).toString();
                //获取桩信息
                Map<String, Object> xhpcChargingPileById =xhpcChargeOrderMapper.getXhpcChargingPileById(xhpcTerminal.getChargingPileId(),tenantId);
                //启动充电
                StartChargingData startChargingData = new StartChargingData();
                //订单流水号 终端号+年月日时分秒+自增4位 共32位
                String orderNo = genOrder(terminalSerialNumber);

                startChargingData.setOrderNo(orderNo);
                if(userMessage.get("phone") !=null){
                    startChargingData.setTel(userMessage.get("phone").toString());
                    xhpcChargeOrder.setDriverId(userMessage.get("phone").toString());
                }
                startChargingData.setPileNo(xhpcTerminal.getPileSerialNumber());
                startChargingData.setGunId(xhpcTerminal.getSerialNumber().substring(14));
                startChargingData.setBalance(Double.valueOf(balance).intValue());
                if(xhpcChargingPileById.get("communicationProtocolVersion")!=null && !"".equals(xhpcChargingPileById.get("communicationProtocolVersion").toString())){
                    startChargingData.setVersion(xhpcChargingPileById.get("communicationProtocolVersion").toString());
                }else{
                    startChargingData.setVersion("0A");
                }
                //用户、桩、平台（最小的）
                int number =0;
                if(!"".equals(userMessage.get("socUser")) && userMessage.get("socUser") !=null && userMessage.get("socProtect") !=null && !"0".equals(userMessage.get("socProtect").toString())){
                    number =Integer.parseInt(userMessage.get("socUser").toString());
                    logger.info("=========用户、桩、平台（最小的）===number==="+number);
                }
                //平台
                String soc = redisService.getCacheObject("global:"+tenantId+":SOC");
                logger.info("=========用户、桩、平台（最小的）===soc==="+soc);
                if(!"".equals(soc) && soc!=null){
                    if(number!=0){
                        if(Integer.parseInt(soc)-number<0){
                            number=Integer.parseInt(soc);
                            logger.info("=========用户、桩、平台（最小的）1===number==="+number);
                        }
                    }else{
                        number=Integer.parseInt(soc);
                        logger.info("=========用户、桩、平台（最小的）2===number==="+number);
                    }
                }
                Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
                if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))){
                    if(number!=0){
                        if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                            number=Integer.parseInt(operatorMessage.get("soc").toString());
                            logger.info("=========用户、桩、平台（最小的）3===number==="+number);
                        }
                    }else{
                        number=Integer.parseInt(operatorMessage.get("soc").toString());
                        logger.info("=========用户、桩、平台（最小的）4===number==="+number);
                    }
                }
                if(number !=0){
                    startChargingData.setSoc(number);
                }
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<number>>>>>>>>>>>>>>>>>:"+number);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<Soc>>>>>>>>>>>>>>>>>:"+startChargingData.getSoc());
                //创建充电订单(充电启动soc初始值，结束是获取,并修改状态)

                xhpcChargeOrder.setChargingStationId(xhpcTerminal.getChargingStationId());
                xhpcChargeOrder.setUserId(userId);
                xhpcChargeOrder.setTerminalId(xhpcTerminal.getTerminalId());
                xhpcChargeOrder.setGunId(xhpcTerminal.getSerialNumber());
                xhpcChargeOrder.setSerialNumber(orderNo);
                xhpcChargeOrder.setSource(userType);
                xhpcChargeOrder.setStatus(-1);
                xhpcChargeOrder.setTenantId(tenantId);
                xhpcChargeOrder.setChargingCapacity(chargingCapacity);
                startChargingData.setChargingCapacity(chargingCapacity);
                if (xhpcChargingPileById != null && xhpcChargingPileById.get("power") != null) {
                    xhpcChargeOrder.setPower(xhpcChargingPileById.get("power").toString());
                }
                if (type == 1) {
                    xhpcChargeOrder.setChargingMode("微信");
                } else if (type == 2){
                    xhpcChargeOrder.setChargingMode("支付宝");
                }else{
                    xhpcChargeOrder.setChargingMode("App");
                }
                xhpcChargeOrder.setCreateTime(Calendar.getInstance().getTime());
                xhpcChargeOrder.setType("91");

                //获取车牌
                Map<String, Object> xhpcUserVehicleMessage = xhpcChargeOrderMapper.getXhpcUserVehicleMessage(xhpcChargeOrder.getUserId(), xhpcChargeOrder.getSource());
                if(xhpcUserVehicleMessage !=null && xhpcUserVehicleMessage.get("vehicleName") !=null){
                    xhpcChargeOrder.setPlateNum(xhpcUserVehicleMessage.get("vehicleName").toString());
                }
                xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);

                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        R r1 = powerPileService.startChargingCapacity(startChargingData);
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<充电返回>>>>>>>>>>>>>>>>>");
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getCode() + ">>>>>>>>>>>>>>>>>");
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getMsg() + ">>>>>>>>>>>>>>>>>");
                        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<" + r1.getData() + ">>>>>>>>>>>>>>>>>");
                        if(r1.getCode() == 200){
                            try{
                                xhpcChargeOrder.setRateModelId(Long.valueOf(r1.getData().toString()));
                                xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);
                                //插一帧实时数据
                                extracted(xhpcChargeOrder);
                            }catch (Exception e){
                                e.printStackTrace();
                                logger.error("update order[{}] failed.", orderNo);
                            }
                        }

                    }
                });
                logger.info("<<<<<<<<<1111<<<<<<<<<<<<<<<C端订单号>>>>>>>>>>>>>>>>>:" + orderNo+"用户id:"+userId);
                logger.info("<<<<<<<<<2222<<<<<<<<<<<<<<<C端订单号>>>>>>>>>>>>>>>>>:" + orderNo+"用户id:"+userId);
                return AjaxResult.success();
            }else{
                return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "请重新登录");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error(UserTypeUtil.LOGIN_TYPE, "请确认设备网络状况正常和枪正确插好后重新尝试");
    }

    @Override
    @Transactional
    public AjaxResult getUserOderMassage(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        Integer userType = loginUser.getUserType();
        Long userid = loginUser.getUserid();
        //查询是否有充电中的订单
        Map<String, Object> map = xhpcChargeOrderMapper.getUserOderMassage(userid, userType);
        if(map ==null || map.get("serialNumber")==null){
            return AjaxResult.error();
        }
        return AjaxResult.success(map);
    }
        @Override
    public String countXhpcRealTimeOrder(Long userId, Integer source, String tenantId) {
        return xhpcChargeOrderMapper.countXhpcRealTimeOrder(userId,source,tenantId);
    }

    @Override
    public int getBlacklistUser(String phone, String vin, String plateNnum, Long chargingStationId, String time) {

        return xhpcChargeOrderMapper.getBlacklistUser(phone, vin, plateNnum, chargingStationId, time);
    }

    @Override
    public List<Map<String,Object>> getXhpcTerminalList(Long chargingStationId, Long chargingPileId,Integer type,Long userId) {
        return xhpcChargeOrderMapper.getXhpcTerminalList(chargingStationId,chargingPileId,type,userId);
    }

    @Override
    public int getXhpcPlaceholderOrderNumber(Long userId, Integer source, String terminalId) {
        return xhpcChargeOrderMapper.getXhpcPlaceholderOrderNumber(userId, source, terminalId);
    }

    @Override
    public AjaxResult getUserOrderMessage(Long userId, Integer source) {
        Map<String, Object> userOrderMessage = xhpcChargeOrderMapper.getUserOrderMessage(userId, source);
        return AjaxResult.success(userOrderMessage);
    }

    @Override
    public void getAutomaticSettlement() {

        try{
            List<String> chargingStationIds = new ArrayList<>();
            chargingStationIds.add("18");
            chargingStationIds.add("19");
            List<Map<String, Object>> list = xhpcChargeOrderMapper.getAutomaticSettlement(chargingStationIds);
            for (int i = 0; i <list.size() ; i++) {
                Map<String, Object> map = list.get(i);
                Long chargeOrderId = Long.valueOf(map.get("chargeOrderId").toString());
                Long realTimeOrderId = Long.valueOf(map.get("realTimeOrderId").toString());

                Map<String, Object> examineMessage = xhpcRealTimeOrderService.getExamineMessage(realTimeOrderId, chargeOrderId);
                if(examineMessage !=null && examineMessage.get("powerPriceTotal")!=null && examineMessage.get("servicePriceTotal")!=null && examineMessage.get("chargingDegree")!=null){
                    BigDecimal powerPrice = new BigDecimal(examineMessage.get("powerPriceTotal").toString());
                    BigDecimal servicePrice = new BigDecimal(examineMessage.get("servicePriceTotal").toString());
                    BigDecimal chargingDegree = new BigDecimal(examineMessage.get("chargingDegree").toString());
                    String startTime=null;
                    String endTime=null;
                    if(examineMessage.get("startTime")!=null){
                        startTime = examineMessage.get("startTime").toString();
                    }else{
                        startTime = map.get("chargeCreateTime").toString();
                    }

                    if(examineMessage.get("endTime")!=null){
                        endTime = examineMessage.get("endTime").toString();
                    }else{
                        endTime = map.get("createTime").toString();
                    }

                    xhpcRealTimeOrderService.getExamine(chargeOrderId,powerPrice,servicePrice,chargingDegree,startTime,endTime);

                }else{
                    XhpcChargeOrder chargeOrder = new XhpcChargeOrder();
                    chargeOrder.setChargeOrderId(chargeOrderId);
                    chargeOrder.setStatus(2);
                    xhpcChargeOrderMapper.updateXhpcChargeOrder(chargeOrder);
                }


            }
        }catch (Exception e){

        }
    }


    //判断双枪启规则
    private AjaxResult startUpSuncha(Map<String, Object> userMessage,XhpcChargeOrder xhpcChargeOrder,XhpcTerminal xhpcTerminal,String tenantId,Integer source,String terminalSerialNumber,Integer type){

        logger.info("========================判断双枪启规则============================");
        logger.info("========================判断双枪启规则============================");
        //余额
        String balance = new BigDecimal(userMessage.get("balance").toString()).multiply(new BigDecimal(100)).toString();

        Long appUserId = Long.valueOf(userMessage.get("appUserId").toString());
        //获取桩信息
        Map<String, Object> xhpcChargingPileById =xhpcChargeOrderMapper.getXhpcChargingPileById(xhpcTerminal.getChargingPileId(),tenantId);

        String userType =UserTypeUtil.USER;
        if(UserTypeUtil.COMMUNIT_TYPE==source){
            userType =UserTypeUtil.COMMUNIT;
        }else if(UserTypeUtil.CUSTOMERS_TYPE==source){
            userType =UserTypeUtil.CUSTOMERS;
        }
        //判断是否有车充电
        Map<String, Object> cacheMap = redisService.getCacheMap("user:" + appUserId + userType + ".order");
        if(cacheMap!=null){
            boolean a =true;  //A账户未启动
            boolean b =true;  //b账户未启动
            //查看AB账户启动情况
            if(cacheMap.get("aBalanceStatus")!=null){
                Integer status = Integer.valueOf(cacheMap.get("aBalanceStatus").toString());
                if(status==0 || status==2){
                    a =false;
                }
            }
            if(cacheMap.get("bBalanceStatus")!=null){
                Integer status = Integer.valueOf(cacheMap.get("bBalanceStatus").toString());
                if(status==0 || status==2){
                    b =false;
                }
            }
            if(a && b){
                //账号金额平分，修改账号金额
                BigDecimal aBigDecimal = new BigDecimal(userMessage.get("balance").toString()).divide(new BigDecimal(2)).setScale(0, BigDecimal.ROUND_UP);

                BigDecimal bBigDecimal =new BigDecimal(userMessage.get("balance").toString()).subtract(aBigDecimal);

                if(UserTypeUtil.USER_TYPE==source){
                    xhpcChargeOrderMapper.updateXhpcAppUser(appUserId,aBigDecimal,bBigDecimal);
                }else if(UserTypeUtil.COMMUNIT_TYPE==source){
                    xhpcChargeOrderMapper.updateXhpcCommunityPersonnel(appUserId,aBigDecimal,bBigDecimal);
                }else if(UserTypeUtil.CUSTOMERS_TYPE==source){
                    xhpcChargeOrderMapper.updateXhpcCustomersPersonnel(appUserId,aBigDecimal,bBigDecimal);
                }
                String key = "user:" + appUserId + userType + ".order";
                redisService.deleteObject(key);

                return getAjaxResult(userMessage, xhpcChargeOrder, xhpcTerminal, tenantId, source, terminalSerialNumber, type, xhpcChargingPileById, appUserId, userType, aBigDecimal.multiply(new BigDecimal(100)).toString(),1);
            }else if(a){
                BigDecimal bigDecimal = new BigDecimal(userMessage.get("aBalance").toString());
                return getAjaxResult(userMessage, xhpcChargeOrder, xhpcTerminal, tenantId, source, terminalSerialNumber, type, xhpcChargingPileById, appUserId, userType, bigDecimal.multiply(new BigDecimal(100)).toString(),1);
            }else{
                BigDecimal bigDecimal = new BigDecimal(userMessage.get("bBalance").toString());
                return getAjaxResult(userMessage, xhpcChargeOrder, xhpcTerminal, tenantId, source, terminalSerialNumber, type, xhpcChargingPileById, appUserId, userType, bigDecimal.multiply(new BigDecimal(100)).toString(),2);
            }
        }else{
            //账号金额平分，修改账号金额
            BigDecimal aBigDecimal = new BigDecimal(balance).divide(new BigDecimal(2)).setScale(0, BigDecimal.ROUND_UP);

            BigDecimal bBigDecimal =new BigDecimal(balance).subtract(aBigDecimal);
            if(UserTypeUtil.USER_TYPE==source){
                xhpcChargeOrderMapper.updateXhpcAppUser(appUserId,aBigDecimal,bBigDecimal);
            }else if(UserTypeUtil.COMMUNIT_TYPE==source){
                xhpcChargeOrderMapper.updateXhpcCommunityPersonnel(appUserId,aBigDecimal,bBigDecimal);
            }else if(UserTypeUtil.CUSTOMERS_TYPE==source){
                xhpcChargeOrderMapper.updateXhpcCustomersPersonnel(appUserId,aBigDecimal,bBigDecimal);
            }
            return getAjaxResult(userMessage, xhpcChargeOrder, xhpcTerminal, tenantId, source, terminalSerialNumber, type, xhpcChargingPileById, appUserId, userType, aBigDecimal.toString(),1);
        }
    }

    private AjaxResult getAjaxResult(Map<String, Object> userMessage, XhpcChargeOrder xhpcChargeOrder, XhpcTerminal xhpcTerminal, String tenantId, Integer source, String terminalSerialNumber, Integer type, Map<String, Object> xhpcChargingPileById, Long appUserId, String userType, String bigDecimal,Integer sunchaStatus) {
        //启动充电
        StartChargingData startChargingData = new StartChargingData();
        //订单流水号 终端号+年月日时分秒+自增4位 共32位
        String orderNo = genOrder(terminalSerialNumber);

        startChargingData.setOrderNo(orderNo);
        if(userMessage.get("phone") !=null){
            startChargingData.setTel(userMessage.get("phone").toString());
            xhpcChargeOrder.setDriverId(userMessage.get("phone").toString());
        }
        startChargingData.setPileNo(xhpcTerminal.getPileSerialNumber());
        startChargingData.setGunId(xhpcTerminal.getSerialNumber().substring(14));
        startChargingData.setBalance(Double.valueOf(bigDecimal).intValue());
        if(xhpcChargingPileById.get("communicationProtocolVersion")!=null && !"".equals(xhpcChargingPileById.get("communicationProtocolVersion").toString())){
            startChargingData.setVersion(xhpcChargingPileById.get("communicationProtocolVersion").toString());
        }else{
            startChargingData.setVersion("0A");
        }
        //用户、桩、平台（最小的）
        int number =0;
        if(!"".equals(userMessage.get("socUser")) && userMessage.get("socUser") !=null && userMessage.get("socProtect") !=null && !"0".equals(userMessage.get("socProtect").toString())){
            number =Integer.parseInt(userMessage.get("socUser").toString());
            logger.info("=========用户、桩、平台（最小的）===number==="+number);
        }
        //平台
        String soc = redisService.getCacheObject("global:"+ tenantId +":SOC");
        logger.info("=========用户、桩、平台（最小的）===soc==="+soc);
        if(!"".equals(soc) && soc!=null){
            if(number!=0){
                if(Integer.parseInt(soc)-number<0){
                    number=Integer.parseInt(soc);
                    logger.info("=========用户、桩、平台（最小的）1===number==="+number);
                }
            }else{
                number=Integer.parseInt(soc);
                logger.info("=========用户、桩、平台（最小的）2===number==="+number);
            }
        }
        Map<String, Object> operatorMessage = xhpcChargeOrderMapper.getOperatorMessage(xhpcTerminal.getChargingStationId());
        if(operatorMessage !=null && operatorMessage.get("soc") !=null && !"".equals(operatorMessage.get("soc"))){
            if(number!=0){
                if(Integer.parseInt(operatorMessage.get("soc").toString())-number<0){
                    number=Integer.parseInt(operatorMessage.get("soc").toString());
                    logger.info("=========用户、桩、平台（最小的）3===number==="+number);
                }
            }else{
                number=Integer.parseInt(operatorMessage.get("soc").toString());
                logger.info("=========用户、桩、平台（最小的）4===number==="+number);
            }
        }
        if(number !=0){
            startChargingData.setSoc(number);
        }
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<number>>>>>>>>>>>>>>>>>:"+number);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<Soc>>>>>>>>>>>>>>>>>:"+startChargingData.getSoc());
        //创建充电订单(充电启动soc初始值，结束是获取,并修改状态)

        xhpcChargeOrder.setChargingStationId(xhpcTerminal.getChargingStationId());
        xhpcChargeOrder.setUserId(appUserId);
        xhpcChargeOrder.setTerminalId(xhpcTerminal.getTerminalId());
        xhpcChargeOrder.setGunId(xhpcTerminal.getSerialNumber());
        xhpcChargeOrder.setSerialNumber(orderNo);
        xhpcChargeOrder.setSource(source);
        xhpcChargeOrder.setStatus(-1);
        xhpcChargeOrder.setTenantId(tenantId);

        if (xhpcChargingPileById != null && xhpcChargingPileById.get("power") != null) {
            xhpcChargeOrder.setPower(xhpcChargingPileById.get("power").toString());
        }
        if (type == 1) {
            xhpcChargeOrder.setChargingMode("微信");
        } else if (type == 2){
            xhpcChargeOrder.setChargingMode("支付宝");
        }else if (type == 3){
            xhpcChargeOrder.setChargingMode("App");
        }else if (type == 4){
            xhpcChargeOrder.setChargingMode("刷卡");
        }else{
            xhpcChargeOrder.setChargingMode("vin码");
        }
        xhpcChargeOrder.setCreateTime(Calendar.getInstance().getTime());
        xhpcChargeOrder.setType("91");
        if(sunchaStatus==1){
            xhpcChargeOrder.setSunchaStatus(1);
        }else{
            xhpcChargeOrder.setSunchaStatus(2);
        }
        //获取车牌
        Map<String, Object> xhpcUserVehicleMessage = xhpcChargeOrderMapper.getXhpcUserVehicleMessage(xhpcChargeOrder.getUserId(), xhpcChargeOrder.getSource());
        if(xhpcUserVehicleMessage !=null && xhpcUserVehicleMessage.get("vehicleName") !=null){
            xhpcChargeOrder.setPlateNum(xhpcUserVehicleMessage.get("vehicleName").toString());
        }
        xhpcChargeOrderMapper.addXhpcChargeOrder(xhpcChargeOrder);

        String finalUserType = userType;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                R r1 = powerPileService.startCharging(startChargingData);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<双枪充电返回>>>>>>>>>>>>>>>>>");
                //添加缓存数据
                String key = "user:" + appUserId + finalUserType + ".order";
                Map<String, Object> map = new HashMap<>();
                if(sunchaStatus==1){
                    map.put("aBalance", bigDecimal);
                    map.put("aBalanceStatus",-1);
                }else{
                    map.put("bBalance", bigDecimal);
                    map.put("bBalanceStatus",-1);
                }

                redisService.setCacheMap(key,map);
                if(r1.getCode() == 200){
                    try{
                        xhpcChargeOrder.setRateModelId(Long.valueOf(r1.getData().toString()));
                        xhpcChargeOrderMapper.updateXhpcChargeOrder(xhpcChargeOrder);
                        //插一帧实时数据
                        extracted(xhpcChargeOrder);
                        //修改双枪缓存状态
                        if(sunchaStatus==1){
                            map.put("aBalanceStatus",0);
                        }else{
                            map.put("bBalanceStatus",0);
                        }
                        redisService.setCacheMap(key,map);
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.error("update order[{}] failed.", orderNo);
                    }
                }
            }
        });
        logger.info("<<<<<<<<<1111<<<<<<<<<<双枪启动<<<<<C端订单号>>>>>>>>>>>>>>>>>:" + orderNo+"用户id:"+ appUserId);
        return AjaxResult.success();
    }


    public static void main(String[] args) {
        try{
//            //String alipayPublicKey1 = getAlipayPublicKey("C:\\Users\\Administrator\\Downloads\\alipayCertPublicKey_RSA2.crt");
//            //System.out.println("alipayPublicKey1:"+alipayPublicKey1);
//            String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCGHX1s315EKjoIBkNiF3IxCAmvtVg+TdCDL/XmJZWdcZ23tEWmmIMsLRCLUKsaPfTEhnqD6EFJnmpJu4teDImo3aDbOoO31YFEXjMXUnTTS/dtDVEo1OecsRL+Re43KSohOkIL1TMyTuNfeIglQTuhCSZ3LOEOx4OHpYwcrLp8p1ORvAS7x35nsmjLp3oQTJo9RWfzfEaKbm6cxsWLKyr5/5eGDXrUHNC5hIDLjoJbe6iqNKyIiPJHtPZfJ36PcWa7PFvx4X+Ded32KZb2AA3p9w/HX7gn1MnRfT5NGH0k3ggxLNarDU8g6JjQYgNtmE/R8gbp99BudZNfDoSF1llNAgMBAAECggEAaTa9bSoXM/bErALt3ghyx1B8+OGVpts5F5IKoVEe/PNjPfkpIzdGwONhtUnF0cKFQaAWgWE1xuGGlO2Sumevn1Cvnw1axF+1F8Om5UcE67cPFvh5kUTlpyGrutt1tMSQjpy7r7jEf1UwP3e5pzBz7TPWf2wv635OC56uOtivPJZ+8vg7VYon/mNXQuL4AavoxfSDtvo0ad30X2fK1WKeeBtgiT4UzV6ZGZh5igKQHM4lVvmbo/jOeQD0KAod7pRe/h4FBFmCVIWwgW+I+Hnzp8A/nJezoowJ3jiTt0FodC9uBCT64ZCz5dVCryD62LDVjKBxB7cfIoQA+PxCiXr9QQKBgQD+2v38J/MlfK/XCYldclzumizwIw6T0Mv6XvYwXQHYgYDKYNF6k1LhMEUo7fP3EsPdV8h/nXmdU4qadOVm6QSJ/rGEl22yGlO7woUzTY/Ls9eknoqfMYuyI1+ICMnNxmesQbWyc0cOHh44cEF+icfJxEDAmrHGLmBVsKuLUJUuVQKBgQCGt663TF7mixghiUOcT11zC1fqG+dIcvAwHpCHfdxsniYRqnv+SLf6eC5PCkQ5aNAAl/ywOLQAWS0XgYti3LyZ4iuGIYcUE0IDDmhWl68V27iXcLIK+rBRqBGxSdk8xR+zSE8fpO4mXpxn8SH0Butex8PJ+oHTbmdXIUAXdn6HGQKBgQCvAB1rqtsRoL72ADxtCHy78u5srwXxhmyqrc6LgzIjQzn2vejaLJO6wfSbmFnwDNimAwNQbgf2ekkwqphjxBozz8qB66GNrPpWccoZYmcdT48CIUO68MCmQBf3R2GbhWPnKu/ja7kc/p1tz9eJVn70E2kLWK4+EdZgwQHqlhj6SQKBgF4AmbdpYOb5s9Li1vyhHJIEHkpLQi15lkPdb/g7SK26BNJa5b5fu5DYf2fDwCtXCZ0AcN/+EQwVLbOzPzGy2R9/g+NKTdkiPvOnAAM8QH2+HaX+ix3CI3o3DnFpGF6hJieRkzR/f3Ximryks451rZMrTWEIncKMzSstFm3Izy0xAoGBAJQaMqlzpM+QaJiytJNeqRpPWRsi0Dkf4XqJXPWLOrApSISsafZF5vk2ZOeIqRsVCBH3LdfVIJxEBAF4l/Sd2q7xC9JHawJDqa4ea7VwL68ANH2w3jcJ3j6DQqf7NIe/lSGxYF6Jt+74oRFHxN3GDSf+z91DYfZz8hQnyphKDNEJ" ;
//            //String alipayPublicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjHDksTgZTpf0wh7oeTVRp0h3SqzTM2smjEJnx9jF1+q3WSXLRB4OzSzq7VsJ/szcyK10ZGO5PxeQ4u9GAG/U+7xhs7ei1cJB/Er55Sg9SbjfkTpwlDv181UJCRJJ/IAcqyqezwTpB8e2trYmHKovUdt0KR9/tVkGa7hsNd5GfxTOUaAFc3zADqRVM+wGimtG0NYfOF2f8tkmBEAiMMLKq5pbAnHU723a1cm/nfVp7gvXfsnO0k2GvRuHzb8mxIhWLiAnwdK9gEu5za/jWxo/xIvf2sdJPYdWj+yfyzA2e1fJkx4uRUzX31CXxZvP2/tfEcnTdI0gxN+OH2eAMiPVswIDAQAB";
//            String alipayPublicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjHDksTgZTpf0wh7oeTVRp0h3SqzTM2smjEJnx9jF1+q3WSXLRB4OzSzq7VsJ/szcyK10ZGO5PxeQ4u9GAG/U+7xhs7ei1cJB/Er55Sg9SbjfkTpwlDv181UJCRJJ/IAcqyqezwTpB8e2trYmHKovUdt0KR9/tVkGa7hsNd5GfxTOUaAFc3zADqRVM+wGimtG0NYfOF2f8tkmBEAiMMLKq5pbAnHU723a1cm/nfVp7gvXfsnO0k2GvRuHzb8mxIhWLiAnwdK9gEu5za/jWxo/xIvf2sdJPYdWj+yfyzA2e1fJkx4uRUzX31CXxZvP2/tfEcnTdI0gxN+OH2eAMiPVswIDAQAB";
//            AlipayConfig alipayConfig = new AlipayConfig();
//            alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
//            alipayConfig.setAppId("2021002156615717");
//            alipayConfig.setPrivateKey(privateKey);
//            alipayConfig.setFormat("json");
//            alipayConfig.setCharset("GBK");
//            alipayConfig.setAlipayPublicKey(alipayPublicKey);
//            alipayConfig.setSignType("RSA2");
//            //构造client
//            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
//            AlipayOpenAppMiniTemplatemessageSendRequest request = new AlipayOpenAppMiniTemplatemessageSendRequest();
//            AlipayOpenAppMiniTemplatemessageSendModel model = new AlipayOpenAppMiniTemplatemessageSendModel();
//            //model.setFormId("2017010100000000580012345678");
//            model.setData("{\"keyword1\": {\"value\" : \"测试站点\"},\"keyword2\": {\"value\" : \"10.5kwh\"},\"keyword3\": {\"value\" : \"未检测到充电电流\"},\"keyword4\": {\"value\" : \"充电结束取出电池后关闭仓门\"}}");
//            model.setPage("page/component/index");
//            model.setUserTemplateId("3eaa5ea872894d018be2a900d9d6b12d");
//            model.setToUserId("2088102122458832");
//            request.setBizModel(model);
//            AlipayOpenAppMiniTemplatemessageSendResponse response = alipayClient.execute(request);
//            System.out.println(response.getBody());
//            if (response.isSuccess()) {
//                System.out.println("调用成功");
//            } else {
//                System.out.println("调用失败");
//            }
            String serialNumber="8083600012000301";
            System.out.println(serialNumber.substring(serialNumber.length()-2, serialNumber.length()));


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

}
