package com.xhpc.order.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhpc.common.api.*;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.HttpUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.data.redis.CacheBmsReqChargerOutputData;
import com.xhpc.common.data.redis.CacheOrderData;
import com.xhpc.common.data.redis.CacheRealtimeData;
import com.xhpc.common.domain.XhpcBarrierGateRecord;
import com.xhpc.common.domain.XhpcChargingPile;
import com.xhpc.common.domain.XhpcRate;
import com.xhpc.common.enums.StopReasonEnum;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.EvcsUtil;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.order.domain.*;
import com.xhpc.order.dto.*;
import com.xhpc.order.mapper.XhpcRealTimeOrderMapper;
import com.xhpc.order.service.IXhpcChargeOrderService;
import com.xhpc.order.service.IXhpcHistoryOrderService;
import com.xhpc.order.service.IXhpcPlaceholderOrderService;
import com.xhpc.order.service.IXhpcRealTimeOrderService;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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 java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMAT;
import static com.xhpc.common.data.redis.StaticBeanUtil.*;
import static org.bouncycastle.asn1.x500.style.RFC4519Style.serialNumber;

/**
 * @author yuyang
 * @date 2021/8/7 15:07
 */
@Service
public class XhpcRealTimeOrderServiceImpl extends BaseService implements IXhpcRealTimeOrderService {

    @Autowired
    private XhpcRealTimeOrderMapper xhpcRealTimeOrderMapper;

    @Autowired
    private IXhpcChargeOrderService xhpcChargeOrderService;

    @Autowired
    private IXhpcHistoryOrderService xhpcHistoryOrderService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RefundOrderService refundOrderService;

    @Autowired
    private UserTypeService userTypeService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ActivityInternetService activityInternetService;

    @Autowired
    private IXhpcPlaceholderOrderService placeholderOrderService;

    @Autowired
    private EvcsService evcsService;

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


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



    @Override
    public List<Map<String, Object>> list(String tenantId,Long chargingStationId,Long chargingPileId,Long terminalId,String phone, String transactionNumber, Integer source, String chargingStationName, String terminalName, Long operatorId, String startTime, String endTime,Integer status,Long userId,Integer type,String affiliationOrganization,String plateNum,Integer internetId,String internetSerialNumber) {

        //桩的统计、该时段金额
        List<Map<String, Object>> list =new ArrayList<>();

        //number 3 用户类型和电话都有 1 电话 2 用户类型
        //type   1 平台 2 运营商 3流量方
        Integer  number=0;
        if(!"".equals(phone) && phone!=null && !"".equals(source) && source !=null){
            number =3;
        }else if (!"".equals(phone) && phone!=null){
            number =1;
        }else{
            number =2;
        }
        if(type ==null || userId ==null){
            return new ArrayList<>();
        }
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        Long logUserId = loginUser.getUserid();
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())) {
            startPage();
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType()) && StatusConstants.OPERATION_POWER_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                list = xhpcRealTimeOrderMapper.list(chargingStationId,chargingPileId,terminalId,phone,transactionNumber,source,chargingStationName,terminalName,operatorId,startTime,endTime,number,status,logOperatorId,1,affiliationOrganization,plateNum,internetId,internetSerialNumber,tenantId);
            }else if(UserTypeUtil.SYS_USER_TYPE_TWO.equals(sysUser.getUserType()) && StatusConstants.INTERNET_POWER_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getInternetUserId();
                //流量方
                list = xhpcRealTimeOrderMapper.list(chargingStationId,chargingPileId,terminalId,phone,transactionNumber,source,chargingStationName,terminalName,operatorId,startTime,endTime,number,status,logOperatorId,3,affiliationOrganization,plateNum,internetId,internetSerialNumber,tenantId);
            }else if(UserTypeUtil.SYS_MOTORCADE_TYPE_FOUR.equals(sysUser.getUserType()) && StatusConstants.MOTORCADE_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getInternetUserId();
                //车队
                list = xhpcRealTimeOrderMapper.list(chargingStationId,chargingPileId,terminalId,phone,transactionNumber,source,chargingStationName,terminalName,operatorId,startTime,endTime,number,status,logOperatorId,4,affiliationOrganization,plateNum,internetId,internetSerialNumber,tenantId);
            }else{
                //查询赋值的场站
                list = xhpcRealTimeOrderMapper.list(chargingStationId,chargingPileId,terminalId,phone,transactionNumber,source,chargingStationName,terminalName,operatorId,startTime,endTime,number,status,logUserId,2,affiliationOrganization,plateNum,internetId,internetSerialNumber,tenantId);
            }
        }else{
            startPage();
            list = xhpcRealTimeOrderMapper.list(chargingStationId,chargingPileId,terminalId,phone,transactionNumber,source,chargingStationName,terminalName,operatorId,startTime,endTime,number,status,logUserId,0,affiliationOrganization,plateNum,internetId,internetSerialNumber,tenantId);
        }

        return list;
    }

    @Override
    public Map<String, Object> getMessage(Long realTimeOrderId,Long chargeOrderId) {
        if(realTimeOrderId ==null){
            return xhpcRealTimeOrderMapper.getMessageChargeOrderId(chargeOrderId);
        }
        return xhpcRealTimeOrderMapper.getMessage(realTimeOrderId);
    }

    @Override
    public List<Map<String, Object>> timeList(Long chargingOrderId) {
        return xhpcRealTimeOrderMapper.timeList(chargingOrderId);
    }

    @Override
    public List<Map<String, Object>> timeBmsList(Long chargingOrderId) {
        startPage();
        return xhpcRealTimeOrderMapper.timeBmsList(chargingOrderId);
    }

    @Override
    public AjaxResult timeChartListVoltage(Long chargingOrderId) {
        Map<String,Object> map =new HashMap();
        map.put("voltage",xhpcRealTimeOrderMapper.timeChartVoltageList(chargingOrderId));
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult timeChartListCurrent(Long chargingOrderId) {
        Map<String,Object> map =new HashMap();
        map.put("current",xhpcRealTimeOrderMapper.timeChartCurrentList(chargingOrderId));
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult timeChartListSoc(Long chargingOrderId) {
        Map<String,Object> map =new HashMap();
        map.put("soc",xhpcRealTimeOrderMapper.timeChartSOCList(chargingOrderId));
        return AjaxResult.success(map);
    }

    @Override
    public int addXhpcRealTimeOrder(XhpcRealTimeOrder xhpcRealTimeOrder) {
        return xhpcRealTimeOrderMapper.insertXhpcRealTimeOrder(xhpcRealTimeOrder);
    }

    /**
     * 添加一条实时订单的BMS
     *
     * @param orderNo
     */
    @Override
    public void addRealTimeOrderBms(String orderNo) {
        CacheBmsReqChargerOutputData cacheBmsReqChargerOutputData = redisService.getCacheObject("order:" + orderNo + ".bms");
        if(cacheBmsReqChargerOutputData !=null){
            XhpcRealTimeOrderBms xhpcRealTimeOrderBms = new XhpcRealTimeOrderBms();
            BeanUtils.copyProperties(cacheBmsReqChargerOutputData, xhpcRealTimeOrderBms);
            xhpcRealTimeOrderBms.setCreateTime(new Date());
            Integer bmsEstRemainingTime = cacheBmsReqChargerOutputData.getBmsEstRemainingTime();
            Integer chargingTimeSummary = cacheBmsReqChargerOutputData.getChargingTimeSummary();
            if (bmsEstRemainingTime > 60) {
                Integer hours = bmsEstRemainingTime / 60;
                Integer mins = bmsEstRemainingTime - (hours * 60);
                xhpcRealTimeOrderBms.setBmsEstRemainingTime(hours + "时" + mins + "分");
            } else {
                xhpcRealTimeOrderBms.setBmsEstRemainingTime(bmsEstRemainingTime + "分");
            }
            if (chargingTimeSummary > 60) {
                Integer hours = chargingTimeSummary / 60;
                Integer mins = chargingTimeSummary - (hours * 60);
                xhpcRealTimeOrderBms.setChargingTimeSummary(hours + "时" + mins + "分");
            } else {
                xhpcRealTimeOrderBms.setChargingTimeSummary(chargingTimeSummary + "分");
            }
            XhpcChargeOrder xhpcChargeOrder = xhpcChargeOrderService.getSerialNumberMessage(orderNo);
            xhpcRealTimeOrderBms.setChargingOrderId(xhpcChargeOrder.getChargeOrderId());
            xhpcRealTimeOrderBms.setCreateTime(new Date());

            String key ="orderOutpu:"+orderNo;

            XhpcRealTimeOrderBms bms = redisService.getCacheObject(key);
            if(bms==null){
                redisService.setCacheObject(key,xhpcRealTimeOrderBms);
            }else{
                BigDecimal bigDecimal1 = new BigDecimal(bms.getPileVoltageOutput()).multiply(BigDecimal.valueOf(bms.getPileCurrentOutput())).setScale(2, BigDecimal.ROUND_CEILING);
                BigDecimal bigDecimal2 = new BigDecimal(xhpcRealTimeOrderBms.getPileVoltageOutput()).multiply(BigDecimal.valueOf(xhpcRealTimeOrderBms.getPileCurrentOutput())).setScale(2, BigDecimal.ROUND_CEILING);
                if(bigDecimal1.compareTo(bigDecimal2)<0){
                    redisService.setCacheObject(key,xhpcRealTimeOrderBms);
                }
            }
            xhpcRealTimeOrderMapper.insertRealTimeOrderBms(xhpcRealTimeOrderBms);
        }

    }

    @Override
    public int addSOC(XhpcChargeOrderSoc xhpcChargeOrderSoc) {
        return xhpcRealTimeOrderMapper.insertSOC(xhpcChargeOrderSoc);
    }

    @Override
    public int addCurrent(XhpcChargeOrderCurrent xhpcChargeOrderCurrent) {
        return xhpcRealTimeOrderMapper.insertCurrent(xhpcChargeOrderCurrent);
    }

    @Override
    public int addVoltage(XhpcChargeOrderVoltage xhpcChargeOrderVoltage) {
        return xhpcRealTimeOrderMapper.insertVoltage(xhpcChargeOrderVoltage);
    }

    @Transactional
    @Override
    public Map<String, Object> getExamineMessage(Long realTimeOrderId,Long chargeOrderId) {
        if(realTimeOrderId==null){
            Map<String, Object> message = xhpcRealTimeOrderMapper.getMessageChargeOrderId(chargeOrderId);

            if(message.get("createTime") !=null && message.get("startTime")==null && message.get("endTime")==null){
                message.put("startTime",message.get("createTime").toString());
                DateTime parse = DateUtil.parse(message.get("createTime").toString(), "yyyy-MM-dd HH:mm:ss");
                DateTime dateTime = DateUtil.offset(parse, DateField.MILLISECOND,10000);
                message.put("endTime",DateUtil.format(dateTime, "yyyy-MM-dd HH:mm:ss"));
            }
            message.put("powerPriceTotal",0);
            message.put("servicePriceTotal",0);
            message.put("chargingDegree",0);
            return message;
        }
        //基本信息
        Map<String, Object> message = xhpcRealTimeOrderMapper.getMessage(realTimeOrderId);
        try{
            XhpcChargeOrder chargeOrder = xhpcChargeOrderService.getChargingOrderId(Long.parseLong(message.get("chargeOrderId").toString()));
            Map<String, Object> cacheMap = redisService.getCacheMap("order:" + chargeOrder.getSerialNumber());
            if (cacheMap !=null && cacheMap.get("startTime")!=null && cacheMap.get("lastOrderTime")!=null) {
                String startTime = cacheMap.get("startTime").toString();
                String lastOrderTime = cacheMap.get("lastOrderTime").toString();
                chargeOrder.setStartTime(DateUtil.parse(startTime));
                chargeOrder.setEndTime(DateUtil.parse(lastOrderTime));
                message.put("startTime",startTime);
                message.put("endTime",lastOrderTime);

                if(cacheMap.get("endSoc")==null){
                    message.put("endSoc",message.get("soc").toString());
                }
                if(cacheMap.get("startSoc")!=null){
                    message.put("startSoc",cacheMap.get("startSoc").toString());
                }

                if (cacheMap.get("totalPower")!=null && cacheMap.get("totalMoney")!=null) {
                    String totalPower = cacheMap.get("totalPower").toString();
                    //String totalPowerSub = totalPower.substring(0, totalPower.length() - 1);
                    String totalMoney = cacheMap.get("totalMoney").toString();
                    //String totalMoneySub = totalMoney.substring(0, totalMoney.length() - 1);
                    chargeOrder.setChargingDegree(new BigDecimal(totalPower));
                    chargeOrder.setAmountCharged(new BigDecimal(totalMoney));
                    message.put("chargingDegree",new BigDecimal(totalPower));
                }
            }
            if(message.get("chargeOrderId") == null){
                message.put("powerPriceTotal",0);
                message.put("servicePriceTotal",0);
                return message;
            }
            //获取开始充电时间、结束时间、计费模型、充电度数、已充金额
            if(chargeOrder.getRateModelId()==null || "".equals(chargeOrder.getRateModelId().toString())){
                Map<String, Object> xhpcChargingStationMap = xhpcRealTimeOrderMapper.getXhpcChargingStationById(chargeOrder.getChargingStationId());
                chargeOrder.setRateModelId(Long.valueOf(xhpcChargingStationMap.get("rateModelId").toString()));
            }
            //获取该订单最后一条实时数据
            Boolean judgment =true;
            if(cacheMap !=null && cacheMap.get("orderData") !=null){
                CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
                if(cacheOrderData.getT1PowerQuantity()==null || cacheOrderData.getT2PowerQuantity()==null|| cacheOrderData.getT3PowerQuantity()==null|| cacheOrderData.getT4PowerQuantity()==null){
                    judgment =false;
                }
            }
            Long rateModelId = chargeOrder.getRateModelId();
            if(cacheMap !=null && cacheMap.get("orderData") !=null && judgment){
                CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
                BigDecimal bigDecimal = new BigDecimal(10000);
                BigDecimal money = new BigDecimal(cacheOrderData.getCost()).divide(bigDecimal,2,BigDecimal.ROUND_HALF_UP);
                //00: 尖费率 01: 峰费率 02: 平费率 03: 谷费率
                BigDecimal t1powerFee =new BigDecimal(0);
                BigDecimal t2powerFee =new BigDecimal(0);
                BigDecimal t3powerFee =new BigDecimal(0);
                BigDecimal t4powerFee =new BigDecimal(0);
                BigDecimal t1serviceFee =new BigDecimal(0);
                BigDecimal t2serviceFee =new BigDecimal(0);
                BigDecimal t3serviceFee =new BigDecimal(0);
                BigDecimal t4serviceFee =new BigDecimal(0);
                //费率计费模型
                List<XhpcRate> rateModelList = xhpcChargeOrderService.getRateModelId(rateModelId);
                for (XhpcRate xhpcRate:rateModelList) {
                    if("00".equals(xhpcRate.getRateValue())){
                        t1powerFee = xhpcRate.getPowerFee();
                        t1serviceFee =xhpcRate.getServiceFee();
                    }
                    if("01".equals(xhpcRate.getRateValue())){
                        t2powerFee = xhpcRate.getPowerFee();
                        t2serviceFee =xhpcRate.getServiceFee();
                    }
                    if("02".equals(xhpcRate.getRateValue())){
                        t3powerFee = xhpcRate.getPowerFee();
                        t3serviceFee = xhpcRate.getServiceFee();
                    }
                    if("03".equals(xhpcRate.getRateValue())){
                        t4powerFee = xhpcRate.getPowerFee();
                        t4serviceFee =xhpcRate.getServiceFee();
                    }
                }
                BigDecimal powerPrice =new BigDecimal(0);
                BigDecimal servicePrice =new BigDecimal(0);
                //因桩有误差，电费和服务费重新计算
                if(!"0".equals(cacheOrderData.getT1PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(t1powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(t1serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                if(!"0".equals(cacheOrderData.getT2PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(t2powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(t2serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                if(!"0".equals(cacheOrderData.getT3PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(t3powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(t3serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                if(!"0".equals(cacheOrderData.getT4PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(t4powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(t4serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                powerPrice =powerPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
                //总服务费
                servicePrice =servicePrice.setScale(2,BigDecimal.ROUND_HALF_UP);
                message.put("powerPriceTotal",powerPrice);
                message.put("servicePriceTotal",servicePrice);
                chargeOrder.setStartTime(DateUtil.parse(cacheOrderData.getStartTime()));
                chargeOrder.setEndTime(DateUtil.parse(cacheOrderData.getEndTime()));
                if(cacheOrderData.getStartSoc() !=null){
                    chargeOrder.setStartSoc(cacheOrderData.getStartSoc()+"");
                }
                if(cacheOrderData.getEndTime() !=null){
                    chargeOrder.setEndSoc(cacheOrderData.getEndSoc()+"");
                }
                if(cacheOrderData.getTotalPowerQuantity() !=null){
                    BigDecimal chargingDegree1 = new BigDecimal(cacheOrderData.getTotalPowerQuantity()).divide(bigDecimal,2,BigDecimal.ROUND_HALF_UP);
                    chargeOrder.setChargingDegree(chargingDegree1);
                }
                chargeOrder.setAmountCharged(money);
            }else{
                if (cacheMap.get("startTime")!=null && cacheMap.get("lastOrderTime")!=null) {
                    chargeOrder.setStartTime(DateUtil.parse(cacheMap.get("startTime").toString()));
                    chargeOrder.setEndTime(DateUtil.parse(cacheMap.get("lastOrderTime").toString()));
                    if (cacheMap.get("totalPower")!=null && cacheMap.get("totalMoney")!=null) {
                        String totalPower = cacheMap.get("totalPower").toString();
                        //String totalPowerSub = totalPower.substring(0, totalPower.length() - 1);
                        String totalMoney = cacheMap.get("totalMoney").toString();
                        chargeOrder.setChargingDegree(new BigDecimal(totalPower));
                        chargeOrder.setAmountCharged(new BigDecimal(totalMoney));
                    }
                }else{
                    //没有获取到时间 1.获取缓存数据 2.缓存没有获取数据库数据
                    List<CacheRealtimeData> list = (List<CacheRealtimeData>) cacheMap.get("realtimeDataList");

                    CacheRealtimeData startData =new CacheRealtimeData();
                    CacheRealtimeData endData =new CacheRealtimeData();

                    if (list != null && list.size() > 0) {
                        endData =list.get(list.size()-1);
                        for (int i = 0; i <list.size() ; i++) {
                            startData =list.get(i);
                            if(startData.getAmountCharged()>0){
                                break;
                            }
                        }
                    }
                    if(endData !=null && endData.getAmountCharged() !=null && startData.getChargingTime()>0){
                        //最后一祯时间
                        Date endTime = DateUtil.parse(endData.getCreateTime());
                        Date startTime =DateUtil.parse(startData.getCreateTime());
                        //充电时长
                        BigDecimal chargingDegree = new BigDecimal(endData.getChargingDegree()).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                        chargeOrder.setStartTime(startTime);
                        chargeOrder.setEndTime(endTime);
                        chargeOrder.setStartSoc(startData.getSoc().toString());
                        chargeOrder.setEndSoc(endData.getSoc().toString());
                        chargeOrder.setChargingDegree(chargingDegree);
                        chargeOrder.setAmountCharged(new BigDecimal(endData.getAmountCharged()).divide(new BigDecimal(10000),2,BigDecimal.ROUND_HALF_UP));
                    }else{
                        //当没有缓存数据时，查询数据库
                        XhpcRealTimeOrder startRealTimeOrder = xhpcRealTimeOrderMapper.getChargingOrderId(chargeOrder.getChargeOrderId(), 1);
                        if(startRealTimeOrder ==null){
                            message.put("powerPriceTotal",0);
                            message.put("servicePriceTotal",0);
                            return message;
                        }
                        XhpcRealTimeOrder endRealTimeOrder = xhpcRealTimeOrderMapper.getChargingOrderId(chargeOrder.getChargeOrderId(), 2);
                        //最后一祯时间
                        Date endTime = endRealTimeOrder.getCreateTime();
                        Date startTime = startRealTimeOrder.getCreateTime();
                        BigDecimal chargingDegree = endRealTimeOrder.getChargingDegree();
                        chargeOrder.setChargingTime(endRealTimeOrder.getChargingTime());
                        if(startRealTimeOrder.getRealTimeOrderId().equals(startRealTimeOrder.getRealTimeOrderId())){
                            message.put("powerPriceTotal",0);
                            message.put("servicePriceTotal",0);
                            return message;
                        }
                        chargeOrder.setStartTime(startTime);
                        chargeOrder.setEndTime(endTime);
                        chargeOrder.setStartSoc(startRealTimeOrder.getSoc());
                        chargeOrder.setEndSoc(endRealTimeOrder.getSoc());
                        Integer chargingTimeNumber = endRealTimeOrder.getChargingTimeNumber();
                        if(chargingTimeNumber>0){
                            chargeOrder.setChargingTimeNumber(Long.valueOf(chargingTimeNumber*60));
                        }else{
                            chargeOrder.setChargingTimeNumber(0L);
                        }
                        chargeOrder.setChargingDegree(chargingDegree);

                        chargeOrder.setAmountCharged(endRealTimeOrder.getAmountCharged());
                    }
                }
                Date startTime2 = chargeOrder.getStartTime();
                Date updateTime2 = chargeOrder.getEndTime();
                BigDecimal amountCharged = chargeOrder.getAmountCharged();
                //充电度数
                BigDecimal chargingDegree = chargeOrder.getChargingDegree();
                BigDecimal powerPriceTotal =new BigDecimal(0);
                //1时间没有跨天
                DateTime parse = DateUtil.parse(DateUtil.format(startTime2, "yyyy-MM-dd"), "yyyy-MM-dd");
                DateTime parse1 = DateUtil.parse(DateUtil.format(updateTime2, "yyyy-MM-dd"), "yyyy-MM-dd");
                //每分钟多少度电
                BigDecimal decimal = new BigDecimal((updateTime2.getTime() - startTime2.getTime())).divide(new BigDecimal(60000),4,BigDecimal.ROUND_HALF_UP);
                BigDecimal divide = chargingDegree.divide(decimal,4,BigDecimal.ROUND_HALF_UP);
                long betweenDay = DateUtil.between(parse,parse1, DateUnit.DAY);
                if(betweenDay==0){
                    powerPriceTotal = getBigDecimal(rateModelId,DateUtil.formatTime(startTime2), DateUtil.formatTime(updateTime2), powerPriceTotal, divide);
                }else{
                    //跨天
                    powerPriceTotal = getBigDecimal(rateModelId, DateUtil.formatTime(startTime2), "23:59:59", powerPriceTotal, divide);
                    System.out.println(">>>>>>跨天前>>>>>>>"+powerPriceTotal);
                    //明天
                    DateTime tomorrow = DateUtil.offsetDay(startTime2,1);
                    Date startTime3 = DateUtil.beginOfDay(tomorrow);
                    powerPriceTotal = getBigDecimal(rateModelId,  DateUtil.formatTime(startTime3), DateUtil.formatTime(updateTime2), powerPriceTotal, divide);
                    System.out.println(">>>>>>跨天后>>>>>>>"+powerPriceTotal);
                }
                //算服务费和电费
                if(amountCharged.compareTo(powerPriceTotal)>-1){
                    BigDecimal servicePriceTotal =amountCharged.subtract(powerPriceTotal);
                    message.put("powerPriceTotal",powerPriceTotal.setScale(2,BigDecimal.ROUND_HALF_UP));
                    message.put("servicePriceTotal",servicePriceTotal.setScale(2,BigDecimal.ROUND_HALF_UP));
                }else{
                    message.put("powerPriceTotal",amountCharged);
                    message.put("servicePriceTotal",0);
                }
            }

            message.put("chargingDegree",chargeOrder.getChargingDegree());
            Long tiem = (chargeOrder.getEndTime().getTime() - chargeOrder.getStartTime().getTime()) / 1000;
            if (tiem > 3600) {
                long hours = tiem / 3600;
                double mins = (double) ((tiem - (hours * 3600)) / 60);
                message.put("chargingTime",hours + "时" + new BigDecimal(mins).setScale(0) + "分");
                chargeOrder.setChargingTime(hours + "时" + new BigDecimal(mins).setScale(0) + "分");
            } else {
                double mins = (double) (tiem / 60);
                message.put("chargingTime",new BigDecimal(mins).setScale(0) + "分");
                chargeOrder.setChargingTime(new BigDecimal(mins).setScale(0) + "分");
            }
            message.put("startSoc",chargeOrder.getStartSoc());
            message.put("endSoc",chargeOrder.getEndSoc());

            if(cacheMap.get("stopReasonHex") !=null && "".equals(cacheMap.get("stopReasonHex").toString())){
                chargeOrder.setType(cacheMap.get("stopReasonHex").toString());
            }else{
                chargeOrder.setType("90");
            }
            message.put("startTime",chargeOrder.getStartTime());
            message.put("endTime",chargeOrder.getEndTime());
            //修改充电订单
            xhpcChargeOrderService.updateXhpcChargeOrder(chargeOrder);

        }catch (Exception e){
            e.printStackTrace();
            logger.info("======================异常订单审核异常=======================");
            message.put("powerPriceTotal",0);
            message.put("servicePriceTotal",0);
        }
        return message;

    }


    @Transactional
    @Override
    public AjaxResult getExamineMessageYu(Long realTimeOrderId,Long chargeOrderId) {
        if(realTimeOrderId==null){
            Map<String, Object> message = xhpcRealTimeOrderMapper.getMessageChargeOrderId(chargeOrderId);

            if(message.get("createTime") !=null && message.get("startTime")==null && message.get("endTime")==null){
                message.put("startTime",message.get("createTime").toString());
                DateTime parse = DateUtil.parse(message.get("createTime").toString(), "yyyy-MM-dd HH:mm:ss");
                DateTime dateTime = DateUtil.offset(parse, DateField.MILLISECOND,10000);
                message.put("endTime",DateUtil.format(dateTime, "yyyy-MM-dd HH:mm:ss"));
            }
            message.put("powerPriceTotal",0);
            message.put("servicePriceTotal",0);
            message.put("chargingDegree",0);
            return AjaxResult.success(message);
        }
        //基本信息
        Map<String, Object> message = xhpcRealTimeOrderMapper.getMessage(realTimeOrderId);
        try{
            XhpcChargeOrder chargeOrder = xhpcChargeOrderService.getChargingOrderId(Long.parseLong(message.get("chargeOrderId").toString()));
            Map<String, Object> cacheMap = redisService.getCacheMap("order:" + chargeOrder.getSerialNumber());
            if (cacheMap !=null && cacheMap.get("startTime")!=null && cacheMap.get("lastOrderTime")!=null) {
                String startTime = cacheMap.get("startTime").toString();
                String lastOrderTime = cacheMap.get("lastOrderTime").toString();
                chargeOrder.setStartTime(DateUtil.parse(startTime));
                chargeOrder.setEndTime(DateUtil.parse(lastOrderTime));
                message.put("startTime",startTime);
                message.put("endTime",lastOrderTime);

                if(cacheMap.get("endSoc")==null){
                    message.put("endSoc",message.get("soc").toString());
                }
                if(cacheMap.get("startSoc")!=null){
                    message.put("startSoc",cacheMap.get("startSoc").toString());
                }

                if (cacheMap.get("totalPower")!=null && cacheMap.get("totalMoney")!=null) {
                    String totalPower = cacheMap.get("totalPower").toString();
                    //String totalPowerSub = totalPower.substring(0, totalPower.length() - 1);
                    String totalMoney = cacheMap.get("totalMoney").toString();
                    //String totalMoneySub = totalMoney.substring(0, totalMoney.length() - 1);
                    chargeOrder.setChargingDegree(new BigDecimal(totalPower));
                    chargeOrder.setAmountCharged(new BigDecimal(totalMoney));
                    message.put("chargingDegree",new BigDecimal(totalPower));
                }
            }
            if(message.get("chargeOrderId") == null){
                message.put("powerPriceTotal",0);
                message.put("servicePriceTotal",0);
                return AjaxResult.success(message);
            }
            //获取开始充电时间、结束时间、计费模型、充电度数、已充金额
            if(chargeOrder.getRateModelId()==null || "".equals(chargeOrder.getRateModelId().toString())){
                Map<String, Object> xhpcChargingStationMap = xhpcRealTimeOrderMapper.getXhpcChargingStationById(chargeOrder.getChargingStationId());
                chargeOrder.setRateModelId(Long.valueOf(xhpcChargingStationMap.get("rateModelId").toString()));
            }
            //获取该订单最后一条实时数据
            Boolean judgment =true;
            if(cacheMap !=null && cacheMap.get("orderData") !=null){
                CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
                if(cacheOrderData.getT1PowerQuantity()==null || cacheOrderData.getT2PowerQuantity()==null|| cacheOrderData.getT3PowerQuantity()==null|| cacheOrderData.getT4PowerQuantity()==null){
                    judgment =false;
                }
            }
            Long rateModelId = chargeOrder.getRateModelId();
            if(cacheMap !=null && cacheMap.get("orderData") !=null && judgment){
                CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
                BigDecimal bigDecimal = new BigDecimal(10000);
                BigDecimal money = new BigDecimal(cacheOrderData.getCost()).divide(bigDecimal,2,BigDecimal.ROUND_HALF_UP);
                //00: 尖费率 01: 峰费率 02: 平费率 03: 谷费率
                BigDecimal t1powerFee =new BigDecimal(0);
                BigDecimal t2powerFee =new BigDecimal(0);
                BigDecimal t3powerFee =new BigDecimal(0);
                BigDecimal t4powerFee =new BigDecimal(0);
                BigDecimal t1serviceFee =new BigDecimal(0);
                BigDecimal t2serviceFee =new BigDecimal(0);
                BigDecimal t3serviceFee =new BigDecimal(0);
                BigDecimal t4serviceFee =new BigDecimal(0);
                //费率计费模型
                List<XhpcRate> rateModelList = xhpcChargeOrderService.getRateModelId(rateModelId);
                for (XhpcRate xhpcRate:rateModelList) {

                    if(UserTypeUtil.MOTORCADE_TYPE==chargeOrder.getSource() ||UserTypeUtil.MOTORCADE_USER_TYPE==chargeOrder.getSource()){
                        if(chargeOrder.getMark()==null){
                            chargeOrder.setStatus(2);
                            chargeOrder.setUpdateTime(new Date());
                            chargeOrder.setErroRemark("车队结算时，车队标识不存在");
                            xhpcChargeOrderService.updateXhpcChargeOrder(chargeOrder);
                            return AjaxResult.error("无效订单");
                        }

                        R motorcadeMap = userTypeService.getOrderMotorcade(chargeOrder.getMark());
                        if(motorcadeMap !=null && motorcadeMap.getData() !=null ){
                            Map<String, Object> motorcadeMessage = (Map<String, Object>)motorcadeMap.getData();
                            if (motorcadeMessage == null) {
                                return AjaxResult.error("查询车队用户信息失败");
                            }

                            if("00".equals(xhpcRate.getRateValue())){
                                t1powerFee = new BigDecimal(String.valueOf(motorcadeMessage.get("peakSharpElectricity")));
                                t1serviceFee =new BigDecimal(String.valueOf(motorcadeMessage.get("peakSharpService")));
                            }
                            if("01".equals(xhpcRate.getRateValue())){
                                t2powerFee = new BigDecimal(String.valueOf(motorcadeMessage.get("peakElectricity")));
                                t2serviceFee =new BigDecimal(String.valueOf(motorcadeMessage.get("peakService")));
                            }
                            if("02".equals(xhpcRate.getRateValue())){
                                t3powerFee = new BigDecimal(String.valueOf(motorcadeMessage.get("flatElectricity")));
                                t3serviceFee = new BigDecimal(String.valueOf(motorcadeMessage.get("flatService")));
                            }
                            if("03".equals(xhpcRate.getRateValue())){
                                t4powerFee =new BigDecimal(String.valueOf(motorcadeMessage.get("valleyElectricity")));
                                t4serviceFee =new BigDecimal(String.valueOf(motorcadeMessage.get("valleyService")));
                            }
                        }else{
                            return AjaxResult.error("查询车队用户信息失败");
                        }

                    }else{
                        if("00".equals(xhpcRate.getRateValue())){
                            t1powerFee = xhpcRate.getPowerFee();
                            t1serviceFee =xhpcRate.getServiceFee();
                        }
                        if("01".equals(xhpcRate.getRateValue())){
                            t2powerFee = xhpcRate.getPowerFee();
                            t2serviceFee =xhpcRate.getServiceFee();
                        }
                        if("02".equals(xhpcRate.getRateValue())){
                            t3powerFee = xhpcRate.getPowerFee();
                            t3serviceFee = xhpcRate.getServiceFee();
                        }
                        if("03".equals(xhpcRate.getRateValue())){
                            t4powerFee = xhpcRate.getPowerFee();
                            t4serviceFee =xhpcRate.getServiceFee();
                        }
                    }
                }
                BigDecimal powerPrice =new BigDecimal(0);
                BigDecimal servicePrice =new BigDecimal(0);
                //因桩有误差，电费和服务费重新计算
                if(!"0".equals(cacheOrderData.getT1PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(t1powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(t1serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                if(!"0".equals(cacheOrderData.getT2PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(t2powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(t2serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                if(!"0".equals(cacheOrderData.getT3PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(t3powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(t3serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                if(!"0".equals(cacheOrderData.getT4PowerQuantity().toString())){
                    BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(t4powerFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(t4serviceFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                    powerPrice=powerPrice.add(multiply1);
                    servicePrice=servicePrice.add(multiply2);
                }
                powerPrice =powerPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
                //总服务费
                servicePrice =servicePrice.setScale(2,BigDecimal.ROUND_HALF_UP);
                message.put("powerPriceTotal",powerPrice);
                message.put("servicePriceTotal",servicePrice);
                chargeOrder.setStartTime(DateUtil.parse(cacheOrderData.getStartTime()));
                chargeOrder.setEndTime(DateUtil.parse(cacheOrderData.getEndTime()));
                if(cacheOrderData.getStartSoc() !=null){
                    chargeOrder.setStartSoc(cacheOrderData.getStartSoc()+"");
                }
                if(cacheOrderData.getEndTime() !=null){
                    chargeOrder.setEndSoc(cacheOrderData.getEndSoc()+"");
                }
                if(cacheOrderData.getTotalPowerQuantity() !=null){
                    BigDecimal chargingDegree1 = new BigDecimal(cacheOrderData.getTotalPowerQuantity()).divide(bigDecimal,2,BigDecimal.ROUND_HALF_UP);
                    chargeOrder.setChargingDegree(chargingDegree1);
                }
                chargeOrder.setAmountCharged(money);
            }else{
                if (cacheMap.get("startTime")!=null && cacheMap.get("lastOrderTime")!=null) {
                    chargeOrder.setStartTime(DateUtil.parse(cacheMap.get("startTime").toString()));
                    chargeOrder.setEndTime(DateUtil.parse(cacheMap.get("lastOrderTime").toString()));
                    if (cacheMap.get("totalPower")!=null && cacheMap.get("totalMoney")!=null) {
                        String totalPower = cacheMap.get("totalPower").toString();
                        //String totalPowerSub = totalPower.substring(0, totalPower.length() - 1);
                        String totalMoney = cacheMap.get("totalMoney").toString();
                        chargeOrder.setChargingDegree(new BigDecimal(totalPower));
                        chargeOrder.setAmountCharged(new BigDecimal(totalMoney));
                    }
                }else{
                    //没有获取到时间 1.获取缓存数据 2.缓存没有获取数据库数据
                    List<CacheRealtimeData> list = (List<CacheRealtimeData>) cacheMap.get("realtimeDataList");

                    CacheRealtimeData startData =new CacheRealtimeData();
                    CacheRealtimeData endData =new CacheRealtimeData();

                    if (list != null && list.size() > 0) {
                        endData =list.get(list.size()-1);
                        for (int i = 0; i <list.size() ; i++) {
                            startData =list.get(i);
                            if(startData.getAmountCharged()>0){
                                break;
                            }
                        }
                    }
                    if(endData !=null && endData.getAmountCharged() !=null && startData.getChargingTime()>0){
                        //最后一祯时间
                        Date endTime = DateUtil.parse(endData.getCreateTime());
                        Date startTime =DateUtil.parse(startData.getCreateTime());
                        //充电时长
                        BigDecimal chargingDegree = new BigDecimal(endData.getChargingDegree()).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                        chargeOrder.setStartTime(startTime);
                        chargeOrder.setEndTime(endTime);
                        chargeOrder.setStartSoc(startData.getSoc().toString());
                        chargeOrder.setEndSoc(endData.getSoc().toString());
                        chargeOrder.setChargingDegree(chargingDegree);
                        chargeOrder.setAmountCharged(new BigDecimal(endData.getAmountCharged()).divide(new BigDecimal(10000),2,BigDecimal.ROUND_HALF_UP));
                    }else{
                        //当没有缓存数据时，查询数据库
                        XhpcRealTimeOrder startRealTimeOrder = xhpcRealTimeOrderMapper.getChargingOrderId(chargeOrder.getChargeOrderId(), 1);
                        if(startRealTimeOrder ==null){
                            message.put("powerPriceTotal",0);
                            message.put("servicePriceTotal",0);
                            return AjaxResult.success(message);
                        }
                        XhpcRealTimeOrder endRealTimeOrder = xhpcRealTimeOrderMapper.getChargingOrderId(chargeOrder.getChargeOrderId(), 2);
                        //最后一祯时间
                        Date endTime = endRealTimeOrder.getCreateTime();
                        Date startTime = startRealTimeOrder.getCreateTime();
                        BigDecimal chargingDegree = endRealTimeOrder.getChargingDegree();
                        chargeOrder.setChargingTime(endRealTimeOrder.getChargingTime());
                        if(startRealTimeOrder.getRealTimeOrderId().equals(startRealTimeOrder.getRealTimeOrderId())){
                            message.put("powerPriceTotal",0);
                            message.put("servicePriceTotal",0);
                            return AjaxResult.success(message);
                        }
                        chargeOrder.setStartTime(startTime);
                        chargeOrder.setEndTime(endTime);
                        chargeOrder.setStartSoc(startRealTimeOrder.getSoc());
                        chargeOrder.setEndSoc(endRealTimeOrder.getSoc());
                        Integer chargingTimeNumber = endRealTimeOrder.getChargingTimeNumber();
                        if(chargingTimeNumber>0){
                            chargeOrder.setChargingTimeNumber(Long.valueOf(chargingTimeNumber*60));
                        }else{
                            chargeOrder.setChargingTimeNumber(0L);
                        }
                        chargeOrder.setChargingDegree(chargingDegree);

                        chargeOrder.setAmountCharged(endRealTimeOrder.getAmountCharged());
                    }
                }
                Date startTime2 = chargeOrder.getStartTime();
                Date updateTime2 = chargeOrder.getEndTime();
                BigDecimal amountCharged = chargeOrder.getAmountCharged();
                //充电度数
                BigDecimal chargingDegree = chargeOrder.getChargingDegree();
                BigDecimal powerPriceTotal =new BigDecimal(0);
                //1时间没有跨天
                DateTime parse = DateUtil.parse(DateUtil.format(startTime2, "yyyy-MM-dd"), "yyyy-MM-dd");
                DateTime parse1 = DateUtil.parse(DateUtil.format(updateTime2, "yyyy-MM-dd"), "yyyy-MM-dd");
                //每分钟多少度电
                BigDecimal decimal = new BigDecimal((updateTime2.getTime() - startTime2.getTime())).divide(new BigDecimal(60000),4,BigDecimal.ROUND_HALF_UP);
                BigDecimal divide = chargingDegree.divide(decimal,4,BigDecimal.ROUND_HALF_UP);
                long betweenDay = DateUtil.between(parse,parse1, DateUnit.DAY);
                if(betweenDay==0){
                    powerPriceTotal = getBigDecimal(rateModelId,DateUtil.formatTime(startTime2), DateUtil.formatTime(updateTime2), powerPriceTotal, divide);
                }else{
                    //跨天
                    powerPriceTotal = getBigDecimal(rateModelId, DateUtil.formatTime(startTime2), "23:59:59", powerPriceTotal, divide);
                    System.out.println(">>>>>>跨天前>>>>>>>"+powerPriceTotal);
                    //明天
                    DateTime tomorrow = DateUtil.offsetDay(startTime2,1);
                    Date startTime3 = DateUtil.beginOfDay(tomorrow);
                    powerPriceTotal = getBigDecimal(rateModelId,  DateUtil.formatTime(startTime3), DateUtil.formatTime(updateTime2), powerPriceTotal, divide);
                    System.out.println(">>>>>>跨天后>>>>>>>"+powerPriceTotal);
                }
                //算服务费和电费
                if(amountCharged.compareTo(powerPriceTotal)>-1){
                    BigDecimal servicePriceTotal =amountCharged.subtract(powerPriceTotal);
                    message.put("powerPriceTotal",powerPriceTotal.setScale(2,BigDecimal.ROUND_HALF_UP));
                    message.put("servicePriceTotal",servicePriceTotal.setScale(2,BigDecimal.ROUND_HALF_UP));
                }else{
                    message.put("powerPriceTotal",amountCharged);
                    message.put("servicePriceTotal",0);
                }
            }

            message.put("chargingDegree",chargeOrder.getChargingDegree());
            Long tiem = (chargeOrder.getEndTime().getTime() - chargeOrder.getStartTime().getTime()) / 1000;
            if (tiem > 3600) {
                long hours = tiem / 3600;
                double mins = (double) ((tiem - (hours * 3600)) / 60);
                message.put("chargingTime",hours + "时" + new BigDecimal(mins).setScale(0) + "分");
                chargeOrder.setChargingTime(hours + "时" + new BigDecimal(mins).setScale(0) + "分");
            } else {
                double mins = (double) (tiem / 60);
                message.put("chargingTime",new BigDecimal(mins).setScale(0) + "分");
                chargeOrder.setChargingTime(new BigDecimal(mins).setScale(0) + "分");
            }
            message.put("startSoc",chargeOrder.getStartSoc());
            message.put("endSoc",chargeOrder.getEndSoc());

            if(cacheMap.get("stopReasonHex") !=null && "".equals(cacheMap.get("stopReasonHex").toString())){
                chargeOrder.setType(cacheMap.get("stopReasonHex").toString());
            }else{
                chargeOrder.setType("90");
            }
            message.put("startTime",chargeOrder.getStartTime());
            message.put("endTime",chargeOrder.getEndTime());
            //修改充电订单
            xhpcChargeOrderService.updateXhpcChargeOrder(chargeOrder);

        }catch (Exception e){
            e.printStackTrace();
            logger.info("======================异常订单审核异常=======================");
            message.put("powerPriceTotal",0);
            message.put("servicePriceTotal",0);
        }
        return AjaxResult.success(message);

    }
    @Override
    @Transactional
    public AjaxResult getExamine(Long chargingOrderId, BigDecimal powerPrice, BigDecimal servicePrice,BigDecimal chargingDegree,String startTime,String endTime) {
        XhpcChargeOrder xhpcChargeOrder = xhpcChargeOrderService.getChargingOrderId(chargingOrderId);
        //查询是否已存在结算信息
        XhpcHistoryOrder historyOrderById = xhpcHistoryOrderService.getHistoryOrderById(null, xhpcChargeOrder.getSerialNumber());
        if(historyOrderById !=null){
            xhpcChargeOrder.setStatus(3);
            xhpcChargeOrderService.updateXhpcChargeOrder(xhpcChargeOrder);
            return AjaxResult.success();
        }
        if(xhpcChargeOrder.getRateModelId()==null || "".equals(xhpcChargeOrder.getRateModelId())){
            Map<String, Object> xhpcChargingStationMap = xhpcRealTimeOrderMapper.getXhpcChargingStationById(xhpcChargeOrder.getChargingStationId());
            xhpcChargeOrder.setRateModelId(Long.valueOf(xhpcChargingStationMap.get("rateModelId").toString()));
        }
        //总金额
        BigDecimal money = powerPrice.add(servicePrice);
        //总服务费 servicePrice
        //总电费 powerPrice
        //剩余的电费
        BigDecimal surplusPowerPrice = powerPrice;
        //剩余的服务费
        BigDecimal surplusServicePrice = servicePrice;

        if(xhpcChargeOrder.getStatus()==1 || xhpcChargeOrder.getStatus()==3){
            return AjaxResult.error("订单已结算，请联系技术人员解决");
        }
        xhpcChargeOrder.setStatus(3);
        xhpcChargeOrder.setAmountCharged(money);

        try{
            Map<String, Object> cacheMap = redisService.getCacheMap("order:"+xhpcChargeOrder.getSerialNumber());
            if(cacheMap.get("stopReasonHex") !=null && !"".equals(cacheMap.get("stopReasonHex").toString())){
                xhpcChargeOrder.setType(cacheMap.get("stopReasonHex").toString());
            }else{
                xhpcChargeOrder.setType("91");
                xhpcChargeOrder.setStopReasonEvcs(45);
            }
        }catch (Exception e){}
        Long userId = xhpcChargeOrder.getUserId();
        Integer source = xhpcChargeOrder.getSource();
        String tenantId = xhpcChargeOrder.getTenantId();
        Map<String, Object> userMessage =new HashMap<>();
        if(startTime !=null && endTime!=null && null!=chargingDegree){
            xhpcChargeOrder.setStartTime(DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss"));
            xhpcChargeOrder.setEndTime(DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"));
            xhpcChargeOrder.setChargingDegree(chargingDegree);
        }

        XhpcHistoryOrder xhpcHistoryOrder = new XhpcHistoryOrder();

        if(xhpcChargeOrder.getStartTime() ==null || xhpcChargeOrder.getEndTime()==null || xhpcChargeOrder.getChargingDegree()==null){
            //获取实时数据
            Map<String, Object> cacheMap = redisService.getCacheMap("order:"+xhpcChargeOrder.getSerialNumber());
            if(cacheMap !=null){
                CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
                if(cacheOrderData !=null){
                    //获取
                    xhpcChargeOrder.setStartSoc(cacheOrderData.getStartSoc()+"");
                    xhpcChargeOrder.setEndSoc(cacheOrderData.getEndSoc()+"");
                    if(startTime==null || endTime==null || null==chargingDegree){
                        DateTime startTime1 = DateUtil.parse(cacheOrderData.getStartTime());
                        DateTime endTime1 = DateUtil.parse(cacheOrderData.getEndTime());
                        xhpcChargeOrder.setStartTime(startTime1);
                        xhpcChargeOrder.setEndTime(endTime1);
                        BigDecimal bigDecimal = new BigDecimal(10000);
                        BigDecimal divide = new BigDecimal(cacheOrderData.getTotalPowerQuantity()).divide(bigDecimal,2, BigDecimal.ROUND_HALF_UP);
                        xhpcChargeOrder.setChargingDegree(divide);
                    }
                    if(cacheOrderData.getStopReason() !=null && !"".equals(cacheOrderData.getStopReason())){
                        xhpcChargeOrder.setType(cacheOrderData.getStopReason());
                    }
                }else{
                    if(startTime==null || endTime==null || null==chargingDegree){
                        if(cacheMap.get("realtimeDataList") !=null){
                            List<CacheRealtimeData> list = (List<CacheRealtimeData>) cacheMap.get("realtimeDataList");
                            if(list !=null && list.size()>0){
                                xhpcChargeOrder.setEndTime(DateUtil.parse(list.get(list.size()-1).getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                                xhpcChargeOrder.setStartTime(DateUtil.parse(list.get(0).getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                                BigDecimal bigDecimal = new BigDecimal(10000);
                                BigDecimal divide = new BigDecimal(list.get(list.size()-1).getChargingDegree()).divide(bigDecimal,2, BigDecimal.ROUND_HALF_UP);
                                xhpcChargeOrder.setChargingDegree(divide);
                            }
                        }else{
                            if(cacheMap.get("startTime") !=null) {
                                xhpcChargeOrder.setEndTime(DateUtil.parse(cacheMap.get("startTime").toString(), "yyyy-MM-dd HH:mm:ss"));
                            }
                        }
                    }
                }
            }
        }



        if(UserTypeUtil.MOTORCADE_TYPE.equals(source) || UserTypeUtil.MOTORCADE_USER_TYPE.equals(source)){
            R user = userTypeService.getUser(null, userId, source, null, tenantId);
            boolean judge = false;
            if(user !=null && user.getData() !=null){
                userMessage = (Map<String, Object>)user.getData();

                if(0==Integer.valueOf(userMessage.get("type").toString())){
                    if (userMessage == null || userMessage.get("remainingAmount") == null) {
                        judge =true;
                    }
                }else{
                    if (userMessage == null || userMessage.get("balance") == null) {
                        judge =true;
                    }
                }
            }else{
                judge =true;
            }
            if(judge){
                //订单异常
                xhpcChargeOrder.setStatus(2);
                //异常原因
                xhpcChargeOrder.setErroRemark("".equals(xhpcChargeOrder.getErroRemark())?"用户id:" + userId + "为空":xhpcChargeOrder.getErroRemark()+"用户id:" + userId + "为空");
                xhpcChargeOrderService.updateXhpcChargeOrder(xhpcChargeOrder);
                return AjaxResult.error("用户id:" + userId + "为空");
            }
        }else if(!UserTypeUtil.INTERNET_TYPE.equals(source)){
            R user = userTypeService.getUser(null, userId, source, null, tenantId);
            boolean judge = false;
            if(user !=null && user.getData() !=null){
                userMessage = (Map<String, Object>)user.getData();
                if (userMessage == null || userMessage.get("balance") == null) {
                    judge =true;
                }
            }else{
                judge =true;
            }
            if(judge){
                //订单异常
                xhpcChargeOrder.setStatus(2);
                //异常原因
                xhpcChargeOrder.setErroRemark("".equals(xhpcChargeOrder.getErroRemark())?"用户id:" + userId + "为空":xhpcChargeOrder.getErroRemark()+"用户id:" + userId + "为空");
                xhpcChargeOrderService.updateXhpcChargeOrder(xhpcChargeOrder);
                return AjaxResult.error("用户id:" + userId + "为空");
            }
        }else{
            xhpcHistoryOrder.setInternetSerialNumber(xhpcChargeOrder.getInternetSerialNumber());
            Map<String, Object> pushOrder = redisService.getCacheMap("pushOrder:"+xhpcChargeOrder.getSerialNumber());
            if(pushOrder.get("operatorId3rdpty") !=null){
                xhpcHistoryOrder.setOperatorId3rdptyEvcs((String) pushOrder.get("operatorId3rdpty"));
            }
        }
        //生成一条历史订单
        if("微信".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("微信");
        }
        if("支付宝".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("支付宝");
        }
        if("刷卡".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("刷卡");
        }
        if("VIN码".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("VIN码");
        }
        if("川逸充".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("川逸充");
        }
        if("快电".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("1");
        }
        if("恒大".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("2");
        }
        if("新电途".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("3");
        }
        if("小桔".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("4");
        }
        if("车为家".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("7");
        }
        if("云快充".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("8");
        }
        xhpcHistoryOrder.setStartTime(xhpcChargeOrder.getStartTime());
        if(xhpcChargeOrder.getEndTime()==null ){
            xhpcHistoryOrder.setEndTime(xhpcChargeOrder.getStartTime());
        }else{
            xhpcHistoryOrder.setStartTime(xhpcChargeOrder.getStartTime());
            xhpcHistoryOrder.setEndTime(xhpcChargeOrder.getEndTime());
        }
        xhpcHistoryOrder.setStartSoc(xhpcChargeOrder.getStartSoc());
        xhpcHistoryOrder.setEndSoc(xhpcChargeOrder.getEndSoc());

        if(xhpcChargeOrder.getChargingDegree() !=null){
            xhpcHistoryOrder.setTotalPower(xhpcChargeOrder.getChargingDegree().doubleValue());
        }else{
            xhpcChargeOrder.setChargingDegree(new BigDecimal(0));
            xhpcHistoryOrder.setTotalPower(0.00);
        }
        xhpcHistoryOrder.setType(2);
        xhpcHistoryOrder.setStatus(0);
        xhpcHistoryOrder.setDelFlag(0);
        addSettlement(powerPrice, servicePrice, money, surplusPowerPrice, surplusServicePrice, xhpcChargeOrder, userId, userMessage,0,null,xhpcHistoryOrder);
        logger.info("======================异常订单结算===================="+xhpcChargeOrder.getSerialNumber());
        return AjaxResult.success();
    }


    @Override
    @Transactional
    public AjaxResult getExamineYu() {
        List<XhpcHistoryOrder> list = xhpcRealTimeOrderMapper.getOrderMassageOrRateTime();

        for (int i = 0; i <list.size() ; i++) {
            XhpcHistoryOrder xhpcHistoryOrder = list.get(i);

            //占位订单生成
            XhpcPlaceholderOrder placeholderOrder = new XhpcPlaceholderOrder();

            if(xhpcHistoryOrder.getSource() !=UserTypeUtil.INTERNET_TYPE){
                if(0 == xhpcHistoryOrder.getSource()){
                    placeholderOrder.setChargingMode("C端用户");
                }else if(2 == xhpcHistoryOrder.getSource()){
                    placeholderOrder.setChargingMode("社区用户");
                }else if(3 == xhpcHistoryOrder.getSource()){
                    placeholderOrder.setChargingMode("B端用户");
                }else{
                    placeholderOrder.setChargingMode("车队");
                }
            }else{
                placeholderOrder.setChargingMode(xhpcHistoryOrder.getChargingMode());
            }
            placeholderOrder.setDriverId(xhpcHistoryOrder.getPhone());
            placeholderOrder.setHistoryOrderId(xhpcHistoryOrder.getHistoryOrderId());
            placeholderOrder.setChargingStationId(xhpcHistoryOrder.getChargingStationId());
            placeholderOrder.setChargeOrderId(xhpcHistoryOrder.getChargeOrderId());
            placeholderOrder.setTerminalId(xhpcHistoryOrder.getTerminalId());
            placeholderOrder.setUserId(xhpcHistoryOrder.getUserId());
            placeholderOrder.setSerialNumber(xhpcHistoryOrder.getSerialNumber());
            placeholderOrder.setInternetSerialNumber(xhpcHistoryOrder.getInternetSerialNumber());
            if(xhpcHistoryOrder.getSource()==UserTypeUtil.INTERNET_TYPE){
                placeholderOrder.setInternetIdEvcs(xhpcHistoryOrder.getInternetSerialNumber().substring(0,9));
            }
            placeholderOrder.setConfirmResult(-2);
            placeholderOrder.setSource(xhpcHistoryOrder.getSource());
            //placeholderOrder.setPlaceholderId(Long.valueOf(xhpcPlaceholderMap.get("placeholderId").toString()));
            placeholderOrder.setFreeTime(30);
            placeholderOrder.setMaxFee(50);
            placeholderOrder.setOperatorId("MA6DFCTD5");
            //订单流水号 终端号+年月日时分秒+自增4位 共32位
            String substring = xhpcHistoryOrder.getSerialNumber().substring(0, 16);
            String orderNo = genOrder(substring);
            placeholderOrder.setPlaceholderOrderNumber(orderNo);
            placeholderOrder.setStatus(1);
            placeholderOrder.setTerminalNumber(substring);
            placeholderOrder.setBillEquipment(1);
            placeholderOrder.setStartTime(xhpcHistoryOrder.getEndTime());
            placeholderOrder.setCreateTime(new Date());
            placeholderOrder.setTenantId(xhpcHistoryOrder.getTenantId());
            //placeholderOrder.setPlateNum(xhpcChargeOrder.getPlateNum());
            placeholderOrderService.insertXhpcPlaceholderOrder(placeholderOrder);


        }



        return null;
    }

    /**
     * 结算订单
     * @param powerPrice
     * @param servicePrice
     * @param money
     * @param surplusPowerPrice
     * @param surplusServicePrice
     * @param xhpcChargeOrder
     * @param userId
     * @param userMessage
     * @param type              0 不发短信  1发短信
     */
    @Override
    public R addSettlement(BigDecimal powerPrice, BigDecimal servicePrice, BigDecimal money, BigDecimal surplusPowerPrice, BigDecimal surplusServicePrice, XhpcChargeOrder xhpcChargeOrder, Long userId, Map<String, Object> userMessage, Integer type, String vinNormal, XhpcHistoryOrder xhpcHistoryOrder) {
        logger.info("<<<<<<<<<<<<<<<进入结算>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
        try{
            if("微信".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("微信");
            }
            if("支付宝".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("支付宝");
            }
            if("刷卡".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("刷卡");
            }
            if("VIN码".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("VIN码");
            }
            if("川逸充".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("川逸充");
            }
            if("快电".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("1");
            }
            if("恒大".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("2");
            }
            if("新电途".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("3");
            }
            if("小桔".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("4");
            }
            if("车为家".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("7");
            }
            if("云快充".equals(xhpcChargeOrder.getChargingMode())){
                xhpcHistoryOrder.setChargingMode("8");
            }
            xhpcHistoryOrder.setPowerPriceTotal(powerPrice);
            xhpcHistoryOrder.setServicePriceTotal(servicePrice);
            xhpcHistoryOrder.setTotalPrice(money.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setVinNormal(vinNormal);
            //电站活动抵扣--抵扣的总金额
            BigDecimal promotionDiscount = new BigDecimal(0);
            //实际价格-用户支付的钱
            BigDecimal actPrice =money;

            //活动的订单总价
            BigDecimal activityTotalPriceTotal=new BigDecimal(0);
            //活动的订单总服务费
            BigDecimal activityServicePriceTotal=new BigDecimal(0);
            //活动的订单总电费
            BigDecimal activityPowerPriceTotal=new BigDecimal(0);
            //活动的订单服务费（抽成后）
            BigDecimal activityServicePrice=new BigDecimal(0);
            //活动的订单电费（抽成后）
            BigDecimal activityPowerPrice=new BigDecimal(0);

            //流量方总金额抽成（折扣后）
            BigDecimal internetCommission =new BigDecimal(0);
            //流量方服务费抽成（折扣后）
            BigDecimal internetSvcCommission =new BigDecimal(0);
            //流量方电量抽成（折扣后）
            BigDecimal internetDegreeCommission =new BigDecimal(0);
            //平台总金额抽成（折扣后）
            BigDecimal platformCommission =new BigDecimal(0);
            //平台服务费抽成（折扣后）
            BigDecimal platformSvcCommission =new BigDecimal(0);
            //运维总抽成（折扣后）
            BigDecimal operationCommission =new BigDecimal(0);
            //运维服务费抽成（折扣后）
            BigDecimal operationSvcCommission =new BigDecimal(0);
            //判断是C端用户还是流量端用户
            //先计算第三方优惠力度
            //判断第三方是否有活动
            Long internetUserId = xhpcChargeOrder.getUserId();
            Long chargeOrderId = xhpcChargeOrder.getChargeOrderId();
            //最后一条实时数据
            Date startTime = xhpcChargeOrder.getStartTime();
            Date endTime = xhpcChargeOrder.getEndTime();
            Integer source = xhpcChargeOrder.getSource();
            String internetSerialNumber = xhpcChargeOrder.getInternetSerialNumber();
            Long chargingStationId = xhpcChargeOrder.getChargingStationId();
            String tenantId = xhpcChargeOrder.getTenantId();
            int computeType =0;
            //判断是否有活动
            logger.info("<<<<<<<<<<<<<<<判断是否有活动>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
            boolean judge =false;
            if(source==UserTypeUtil.INTERNET_TYPE &&  internetSerialNumber!=null && xhpcChargeOrder.getStartTime()!=null && xhpcChargeOrder.getEndTime()!=null && money.compareTo(new BigDecimal(0))>=1){
                xhpcHistoryOrder.setInternetSerialNumber(xhpcChargeOrder.getInternetSerialNumber());
                Double totalPower = xhpcHistoryOrder.getTotalPower();
                boolean activityInternet =false;
                //yyyy-mm-dd(当前时间)
                String parse2 = DateUtil.formatDate(startTime);
                long time1 = startTime.getTime();
                long time2 = endTime.getTime();

                if(time2>time1){
                    List<XhpcActivityInternetDomainDto> activityStationTime = xhpcRealTimeOrderMapper.getActivityStationTime(internetUserId, DateUtil.formatDateTime(startTime), DateUtil.formatDateTime(endTime), chargingStationId, tenantId);
                    //1时间没有跨天
                    DateTime parse = DateUtil.parse(DateUtil.format(startTime, "yyyy-MM-dd"), "yyyy-MM-dd");
                    DateTime parse1 = DateUtil.parse(DateUtil.format(endTime, "yyyy-MM-dd"), "yyyy-MM-dd");
                    long betweenDay = DateUtil.between(parse,parse1, DateUnit.DAY);
                    if(activityStationTime !=null && activityStationTime.size()==1){
                        logger.info("<<<<<<<<<<<<<<<有流量方活动>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
                        judge =true;

                        String start = DateUtil.formatTime(startTime);
                        String end = DateUtil.formatTime(endTime);
                        String activityId ="";
                        BigDecimal chargingDegree = new BigDecimal(0);
                        Map<String, Double> params =new HashMap<>();
                        List<XhpcActivityFormulaDomainDto> activityFormulaTime1 =new ArrayList<>();
                        List<XhpcActivityFormulaDomainDto> activityFormulaTime2 =new ArrayList<>();
                        List<Map<String,Object>> reatTimeList1 =new ArrayList<>();
                        List<Map<String,Object>> reatTimeList2 =new ArrayList<>();
                        XhpcActivityInternetDomainDto activityInternet1 =new XhpcActivityInternetDomainDto();
                        if(betweenDay>0){
                            activityInternet1 = activityStationTime.get(0);
                            activityFormulaTime1 = xhpcRealTimeOrderMapper.getActivityFormulaTime(activityInternet1.getActivityId(), start, "24:00:00");
                            activityFormulaTime2 = xhpcRealTimeOrderMapper.getActivityFormulaTime(activityInternet1.getActivityId(), "00:00:00", end);
                            reatTimeList1 = xhpcHistoryOrderService.getReatTimeList(start,"23:59:59",xhpcChargeOrder.getRateModelId());
                            reatTimeList2 = xhpcHistoryOrderService.getReatTimeList("00:00:00", end,xhpcChargeOrder.getRateModelId());
                            activityId =activityInternet1.getActivityId()+"";
                        }else{
                            activityInternet1 = activityStationTime.get(0);
                            activityFormulaTime1 = xhpcRealTimeOrderMapper.getActivityFormulaTime(activityInternet1.getActivityId(), start, end);
                            reatTimeList1 = xhpcHistoryOrderService.getReatTimeList(start,end,xhpcChargeOrder.getRateModelId());
                            activityId =activityInternet1.getActivityId()+"";
                        }
                        for (int j = 0; j < activityFormulaTime1.size(); j++) {
                            XhpcActivityFormulaDomainDto activityFormula = activityFormulaTime1.get(j);
                            //计费类型
                            computeType = activityInternet1.getComputeType();
                            BigDecimal activityServicePriceFormula = activityFormula.getServicePrice();
                            //BigDecimal activityPowerPriceFormula = activityFormula.getPowerPrice();
                            BigDecimal activityPowerPriceFormula = new BigDecimal(reatTimeList1.get(j).get("powerFee").toString());
                            //计算公式
                            String computeFormula = activityFormula.getComputeFormula();
                            BigDecimal degree =new BigDecimal(0);
                            if (activityFormulaTime2.size()==0 && activityFormulaTime1.size()-1==j) {
                                degree = new BigDecimal(totalPower).subtract(chargingDegree).setScale(2, BigDecimal.ROUND_HALF_UP);
                            }else{
                                degree =getRealOrderTime(chargeOrderId, parse2+" "+activityFormula.getStartTime(), parse2+" "+activityFormula.getEndTime()).setScale(2,BigDecimal.ROUND_HALF_UP);;
                            }
                            //挡前服务费
                            BigDecimal activityServicePrice1 = activityServicePriceFormula.multiply(degree).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //活动总服务费
                            activityServicePriceTotal = activityServicePriceTotal.add(activityServicePrice1).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //挡前电费
                            BigDecimal activityPowerPrice1 = activityPowerPriceFormula.multiply(degree).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //活动总电费
                            activityPowerPriceTotal = activityPowerPriceTotal.add(activityPowerPrice1).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //活动总金额
                            activityTotalPriceTotal = activityTotalPriceTotal.add(activityServicePrice1.add(activityPowerPrice1));
                            params.put("T",activityPowerPrice1.add(activityServicePrice1).doubleValue());
                            params.put("P",activityPowerPrice1.doubleValue());
                            params.put("S",activityServicePrice1.doubleValue());
                            params.put("E",degree.doubleValue());
                            //支付给流量方的钱
                            BigDecimal eval = new BigDecimal(Calc.eval(computeFormula, params)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            if(computeType==1){
                                BigDecimal decimal1 = eval.multiply(new BigDecimal(0.5)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                internetCommission = internetCommission.add(eval);
                                activityPowerPrice =activityPowerPrice.add(activityPowerPrice1.subtract(decimal1));
                                activityServicePrice =activityServicePrice.add(activityServicePrice1.subtract(decimal1));
                            }else if(computeType==2){
                                internetSvcCommission = internetSvcCommission.add(eval);
                                activityServicePrice =activityServicePrice.add(activityServicePrice1.subtract(eval));
                                activityPowerPrice =activityPowerPrice.add(activityPowerPrice1);
                            }else{
                                //电量抽成
                                internetDegreeCommission = internetDegreeCommission.add(eval);
                                //减服务费
                                activityServicePrice =activityServicePrice.add(activityServicePrice1.subtract(eval));
                                activityPowerPrice =activityPowerPrice.add(activityPowerPrice1);
                            }
                            chargingDegree = chargingDegree.add(degree);
                        }
                        if(activityFormulaTime2.size()>0){
                            for (int j = 0; j < activityFormulaTime2.size(); j++) {
                                //计费类型
                                computeType = activityInternet1.getComputeType();
                                XhpcActivityFormulaDomainDto activityFormula = activityFormulaTime2.get(j);
                                BigDecimal activityServicePriceFormula = activityFormula.getServicePrice();
                                //BigDecimal activityPowerPriceFormula = activityFormula.getPowerPrice();
                                BigDecimal activityPowerPriceFormula = new BigDecimal(reatTimeList2.get(j).get("powerFee").toString());
                                //计算公式
                                String computeFormula = activityFormula.getComputeFormula();
                                BigDecimal degree =new BigDecimal(0);
                                if (activityFormulaTime2.size()-1==j) {
                                    degree = new BigDecimal(totalPower).subtract(chargingDegree).setScale(2, BigDecimal.ROUND_HALF_UP);
                                }else{
                                    degree =getRealOrderTime(chargeOrderId, parse2+" "+activityFormula.getStartTime(), parse2+" "+activityFormula.getEndTime()).setScale(2,BigDecimal.ROUND_HALF_UP);;
                                }
                                //挡前服务费
                                BigDecimal activityServicePrice1 = activityServicePriceFormula.multiply(degree).setScale(2, BigDecimal.ROUND_HALF_UP);
                                //活动总服务费
                                activityServicePriceTotal = activityServicePriceTotal.add(activityServicePrice1).setScale(2, BigDecimal.ROUND_HALF_UP);
                                //挡前电费
                                BigDecimal activityPowerPrice1 = activityPowerPriceFormula.multiply(degree).setScale(2, BigDecimal.ROUND_HALF_UP);
                                //活动总电费
                                activityPowerPriceTotal = activityPowerPriceTotal.add(activityPowerPrice1).setScale(2, BigDecimal.ROUND_HALF_UP);
                                //活动总金额
                                activityTotalPriceTotal = activityTotalPriceTotal.add(activityServicePrice1.add(activityPowerPrice1));
                                params.put("T",activityPowerPrice1.add(activityServicePrice1).doubleValue());
                                params.put("P",activityPowerPrice1.doubleValue());
                                params.put("S",activityServicePrice1.doubleValue());
                                params.put("E",degree.doubleValue());
                                //支付给流量方的钱
                                BigDecimal eval = new BigDecimal(Calc.eval(computeFormula, params)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                if(computeType==1){
                                    BigDecimal decimal1 = eval.multiply(new BigDecimal(0.5)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    internetCommission = internetCommission.add(eval);
                                    activityPowerPrice =activityPowerPrice.add(activityPowerPrice1.subtract(decimal1));
                                    activityServicePrice =activityServicePrice.add(activityServicePrice1.subtract(decimal1));
                                }else if(computeType==2){
                                    internetSvcCommission = internetSvcCommission.add(eval);
                                    activityServicePrice =activityServicePrice.add(activityServicePrice1.subtract(eval));
                                    activityPowerPrice =activityPowerPrice.add(activityPowerPrice1);
                                }else{
                                    //电量抽成
                                    internetDegreeCommission = internetDegreeCommission.add(eval);
                                    //减服务费
                                    activityServicePrice =activityServicePrice.add(activityServicePrice1.subtract(eval));
                                    activityPowerPrice =activityPowerPrice.add(activityPowerPrice1);
                                }
                                chargingDegree = chargingDegree.add(degree);
                            }
                        }
                        promotionDiscount = money.subtract(activityTotalPriceTotal);
                        xhpcHistoryOrder.setActivityId(activityId);
                    }else{
                        //按照以前流量方折扣计算
                        if(activityStationTime.size()>1){
                            xhpcHistoryOrder.setActivityId("同一时间活动有2个");
                        }else{
                            xhpcHistoryOrder.setActivityId("无活动");
                        }
                        activityInternet =true;
                    }
                }else{
                    activityInternet =true;
                    xhpcHistoryOrder.setActivityId("充电开始结束时间相等不做活动");
                }
                if(activityInternet){
                    logger.info("无活动，流量方按照以前抽成");
                    String substring = internetSerialNumber.substring(0, 9);
                    xhpcHistoryOrder.setInternetSerialNumber(xhpcChargeOrder.getInternetSerialNumber());
                    Map<String, Object> operatorIdEvcs = xhpcRealTimeOrderMapper.getOperatorIdEvcs(substring);
                    if(operatorIdEvcs !=null){
                        if(operatorIdEvcs.get("operatorIdEvcs")!=null && operatorIdEvcs.get("commissionType")!=null && operatorIdEvcs.get("commissionRate")!=null){
                            BigDecimal commissionRate = new BigDecimal(operatorIdEvcs.get("commissionRate").toString()).divide(new BigDecimal(100));
                            String commissionType = operatorIdEvcs.get("commissionType").toString();
                            //0总金额提成 1服务费提成
                            if(new BigDecimal(0).compareTo(commissionRate)==-1){
                                if("0".equals(commissionType) || "1".equals(commissionType)|| "2".equals(commissionType)){
                                    //流量方的钱
                                    if("0".equals(commissionType)){
                                        BigDecimal decimal1 = surplusPowerPrice.multiply(commissionRate).setScale(2, BigDecimal.ROUND_DOWN);
                                        BigDecimal decimal2 = surplusServicePrice.multiply(commissionRate).setScale(2, BigDecimal.ROUND_DOWN);
                                        internetCommission = decimal1.add(decimal2);
                                        surplusPowerPrice =surplusPowerPrice.subtract(decimal1);
                                        surplusServicePrice =surplusServicePrice.subtract(decimal2);
                                    }else if("1".equals(commissionType)){
                                        BigDecimal decimal2 = surplusServicePrice.multiply(commissionRate).setScale(2, BigDecimal.ROUND_DOWN);
                                        internetSvcCommission = decimal2;
                                        surplusServicePrice = surplusServicePrice.subtract(decimal2);
                                    }else{
                                        //电量抽成
                                        BigDecimal chargingDegree = xhpcChargeOrder.getChargingDegree();
                                        internetDegreeCommission = chargingDegree.multiply(new BigDecimal(operatorIdEvcs.get("commissionRate").toString())).setScale(2, BigDecimal.ROUND_DOWN);
                                        //减服务费
                                        surplusServicePrice = surplusServicePrice.subtract(internetDegreeCommission);
                                    }
                                }
                            }
                        }
                    }
                }

//                }
            }
            //
            if ( !UserTypeUtil.INTERNET_TYPE.equals(source) && xhpcChargeOrder.getStartTime()!=null && xhpcChargeOrder.getEndTime()!=null && money.compareTo(new BigDecimal(0))>=1) {
                //查询是否有活动
                List<XhpcActivityDiscountDto> activityDiscountTime = xhpcRealTimeOrderMapper.getActivityDiscountTime(userId, DateUtil.formatDateTime(startTime), source, xhpcChargeOrder.getChargingStationId(), xhpcChargeOrder.getTenantId());
                if(activityDiscountTime !=null && activityDiscountTime.size()>0){
                    logger.info("<<<<<<<<<<<<<<<有活动>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
                    judge =true;
                    int size = activityDiscountTime.size();
                    activityServicePriceTotal  = surplusServicePrice;
                    activityPowerPriceTotal  = surplusPowerPrice;
                    String parse2 = DateUtil.formatDate(startTime);
                    //折扣电费、服务费
                    BigDecimal promotionDiscount1 =new BigDecimal(0);
                    BigDecimal activityServicePrice1 = new BigDecimal(0);
                    BigDecimal activityPowerPrice1 = new BigDecimal(0);
                    String activityId ="";
                    String start = DateUtil.formatTime(startTime);
                    for (int i = 0; i < size; i++) {
                        XhpcActivityDiscountDto activity = activityDiscountTime.get(i);
                        BigDecimal discountRate = activity.getDiscountRate().divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal  decimal1= activityPowerPriceTotal.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                        BigDecimal  decimal2= activityServicePriceTotal.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                        Integer discountType = activity.getDiscountType();
                        //说明活动时间大于用户充电结束时间
                        if(discountType.equals(1)){
                            if(promotionDiscount1.compareTo(decimal1.add(decimal2))<0){
                                promotionDiscount1 =decimal1.add(decimal2);
                                activityPowerPrice1 = decimal1;
                                activityServicePrice1 = decimal2;
                                activityId =activity.getActivityId()+"";
                            }
                        }else if(discountType.equals(2)){
                            //服务费
                            if(activityServicePriceTotal.compareTo(decimal2)<0){
                                if(promotionDiscount1.compareTo(activityServicePriceTotal)<0){
                                    promotionDiscount1 =activityServicePriceTotal;
                                    activityServicePrice1 = activityServicePriceTotal;
                                    activityId =activity.getActivityId()+"";
                                }
                            }else{
                                if(promotionDiscount1.compareTo(decimal2)<0){
                                    promotionDiscount1 =decimal2;
                                    activityServicePrice1 = decimal2;
                                    activityId =activity.getActivityId()+"";
                                }
                            }
                        }else{
                            //电量抽成
                            BigDecimal chargingDegree = xhpcChargeOrder.getChargingDegree();
                            //电量的钱
                            BigDecimal bigDecimal = chargingDegree.multiply(discountRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //当电量的折扣大于服务费时，电量==服务费
                            if(activityServicePriceTotal.compareTo(bigDecimal)<0){
                                if(promotionDiscount1.compareTo(activityServicePriceTotal)<0){
                                    promotionDiscount1 =activityServicePriceTotal;
                                    activityServicePrice1 = activityServicePriceTotal;
                                    activityId =activity.getActivityId()+"";
                                }
                            }else{
                                if(promotionDiscount1.compareTo(bigDecimal)<0){
                                    promotionDiscount1 =bigDecimal;
                                    activityServicePrice1 = bigDecimal;
                                    activityId =activity.getActivityId()+"";
                                }
                            }
                        }

                    }
                    //得到最大的折扣进行计算
                    promotionDiscount = promotionDiscount1;
                    activityServicePriceTotal = activityServicePriceTotal.subtract(activityServicePrice1);
                    activityPowerPriceTotal = activityPowerPriceTotal.subtract(activityPowerPrice1);
                    activityTotalPriceTotal = money.subtract(promotionDiscount);
                    actPrice = activityTotalPriceTotal;
                    activityServicePrice = activityServicePriceTotal;
                    activityPowerPrice = activityPowerPriceTotal;
                    activityTotalPriceTotal = activityServicePriceTotal.add(activityPowerPriceTotal);
                    xhpcHistoryOrder.setActivityId(activityId);
                }else{
                    if(UserTypeUtil.COMMUNIT_TYPE.equals(source) || UserTypeUtil.CUSTOMERS_TYPE.equals(source) || UserTypeUtil.MOTORCADE_TYPE.equals(source) || UserTypeUtil.MOTORCADE_USER_TYPE.equals(source)){
                        //折扣（机构用户），没有活动时计算
                        if(xhpcChargeOrder.getChargingStationId()!=null){
                            R mechanismDiscount = userTypeService.getMechanismDiscount(userId, source, xhpcChargeOrder.getTenantId(),xhpcChargeOrder.getChargingStationId());

                            if(mechanismDiscount !=null && mechanismDiscount.getData() !=null) {
                                Map<String, Object> userDiscount = (Map<String, Object>) mechanismDiscount.getData();
                                if (userDiscount != null && userDiscount.get("commissionType") != null && userDiscount.get("servicePreferential") != null) {
                                    String commissionType = userDiscount.get("commissionType").toString();
                                    BigDecimal servicePreferential =new BigDecimal(userDiscount.get("servicePreferential").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);

                                    if(servicePreferential.compareTo(new BigDecimal(0))==1){
                                        if("0".equals(commissionType) || "1".equals(commissionType) || "2".equals(commissionType)){
                                            BigDecimal decimal1 = surplusPowerPrice.multiply(servicePreferential).setScale(2, BigDecimal.ROUND_HALF_UP);
                                            BigDecimal decimal2 = surplusServicePrice.multiply(servicePreferential).setScale(2, BigDecimal.ROUND_HALF_UP);
                                            if("0".equals(commissionType)){
                                                //总金额
                                                actPrice =actPrice.subtract(decimal1.add(decimal2));
                                                //折扣的钱
                                                promotionDiscount = decimal1.add(decimal2);
                                                surplusPowerPrice = surplusPowerPrice.subtract(decimal1);
                                                surplusServicePrice= surplusServicePrice.subtract(decimal2);
                                            }else if("1".equals(commissionType)){
                                                //服务费
                                                if(surplusServicePrice.compareTo(decimal2) > -1){
                                                    surplusServicePrice =surplusServicePrice.subtract(decimal2);
                                                    actPrice =actPrice.subtract(decimal2);
                                                    promotionDiscount = decimal2;
                                                }else{
                                                    promotionDiscount = surplusServicePrice;
                                                    actPrice =actPrice.subtract(surplusServicePrice);
                                                    surplusServicePrice =new BigDecimal(0);
                                                }
                                            }else{
                                                //电量抽成
                                                BigDecimal chargingDegree = xhpcChargeOrder.getChargingDegree();
                                                //电量的钱
                                                promotionDiscount = chargingDegree.multiply(new BigDecimal(userDiscount.get("servicePreferential").toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                                //当电量的折扣大于服务费时，电量==服务费
                                                if(surplusServicePrice.compareTo(promotionDiscount)>-1){
                                                    surplusServicePrice= surplusServicePrice.subtract(promotionDiscount);
                                                    actPrice =actPrice.subtract(promotionDiscount);
                                                }else{
                                                    promotionDiscount = surplusServicePrice;
                                                    actPrice =actPrice.subtract(surplusServicePrice);
                                                    surplusServicePrice =new BigDecimal(0);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            logger.info("<<<<<<<<<<<<<<<获取运营商>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
            //获取运营商
            Map<String, Object> operatorMessage = xhpcChargeOrderService.getOperatorMessage(xhpcChargeOrder.getChargingStationId());
            if(operatorMessage !=null){
                if(operatorMessage.get("operatorIdEvcs")!=null){
                    if(operatorMessage.get("operatorIdEvcs") !=null && !"".equals(operatorMessage.get("operatorIdEvcs").toString())){
                        String stw = operatorMessage.get("operatorIdEvcs").toString();
                        if(stw.length()==9){
                            //  xhpcHistoryOrder.setOperatorIdEvcs(stw);
                        }
                    }
                }

                if(operatorMessage.get("maintenanceCommissionRate") !=null && operatorMessage.get("commissionType") !=null && operatorMessage.get("platformCommissionRate") !=null){
                    Integer commissionType = (Integer) operatorMessage.get("commissionType");
                    //运维提成
                    BigDecimal maintenanceCommissionRate = new BigDecimal(operatorMessage.get("maintenanceCommissionRate").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
                    //平台提成
                    BigDecimal platformCommissionRate = new BigDecimal(operatorMessage.get("platformCommissionRate").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
                    if(judge){
                        //提成类型（0总金额提成 1服务费提成）
                        if(commissionType==0){
                            //平台总抽成
                            BigDecimal multiply1 = activityPowerPrice.multiply(platformCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = activityServicePrice.multiply(platformCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            //运维总抽成
                            BigDecimal multiply3 = activityPowerPrice.multiply(maintenanceCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply4 = activityServicePrice.multiply(maintenanceCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);

                            //平台总金额抽成
                            platformCommission = multiply1.add(multiply2);
                            //剩下的钱电费和服务
                            activityPowerPrice = activityPowerPrice.subtract(multiply1);
                            activityServicePrice = activityServicePrice.subtract(multiply2);

                            //运维总金额抽成
                            operationCommission = multiply3.add(multiply4);
                            //剩下的钱电费和服务
                            activityPowerPrice = activityPowerPrice.subtract(multiply3);
                            activityServicePrice = activityServicePrice.subtract(multiply4);

                        }else if(commissionType==1){
                            BigDecimal multiply1 = activityServicePrice.multiply(platformCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = activityServicePrice.multiply(maintenanceCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            //平台服务费抽成金额
                            platformSvcCommission=multiply1;
                            //剩下的服务费钱
                            activityServicePrice = activityServicePrice.subtract(multiply1);

                            //运维服务费抽成金额
                            operationCommission = multiply2;
                            //剩下的钱
                            activityServicePrice = activityServicePrice.subtract(multiply2);
                        }
                    }else{
                        //提成类型（0总金额提成 1服务费提成）
                        if(commissionType==0){
                            //平台总抽成
                            BigDecimal multiply1 = surplusPowerPrice.multiply(platformCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = surplusServicePrice.multiply(platformCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            //运维总抽成
                            BigDecimal multiply3 = surplusPowerPrice.multiply(maintenanceCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply4 = surplusServicePrice.multiply(maintenanceCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);

                            //平台总金额抽成
                            platformCommission = multiply1.add(multiply2);
                            //剩下的钱电费和服务
                            surplusPowerPrice = surplusPowerPrice.subtract(multiply1);
                            surplusServicePrice = surplusServicePrice.subtract(multiply2);

                            //运维总金额抽成
                            operationCommission = multiply3.add(multiply4);
                            //剩下的钱电费和服务
                            surplusPowerPrice = surplusPowerPrice.subtract(multiply3);
                            surplusServicePrice = surplusServicePrice.subtract(multiply4);

                        }else if(commissionType==1){
                            BigDecimal multiply1 = surplusServicePrice.multiply(platformCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = surplusServicePrice.multiply(maintenanceCommissionRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                            //平台服务费抽成金额
                            platformSvcCommission=multiply1;
                            //剩下的服务费钱
                            surplusServicePrice = surplusServicePrice.subtract(multiply1);

                            //运维服务费抽成金额
                            operationCommission = multiply2;
                            //剩下的钱
                            surplusServicePrice = surplusServicePrice.subtract(multiply2);
                        }
                    }
                }else{
                    //订单异常
                    xhpcChargeOrder.setStatus(2);
                    //异常原因
                    xhpcChargeOrder.setErroRemark("运营商数据为空");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.fail();
                }
            }
            logger.info("<<<<<<<<<<<<<<<<22222>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
            logger.info("<<<<<<<<<<<<<<<<22222>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());

            xhpcHistoryOrder.setStopReasonEvcs(xhpcChargeOrder.getType());
            xhpcHistoryOrder.setChargeOrderId(chargeOrderId);
            xhpcHistoryOrder.setChargingStationId(xhpcChargeOrder.getChargingStationId());
            xhpcHistoryOrder.setUserId(userId);
            xhpcHistoryOrder.setTerminalId(xhpcChargeOrder.getTerminalId());
            xhpcHistoryOrder.setStartTime(xhpcChargeOrder.getStartTime());
            //todo 从头开始设置所有evcs字段
            if(UserTypeUtil.COMMUNIT_TYPE.equals(source) || UserTypeUtil.CUSTOMERS_TYPE.equals(source)){
                xhpcHistoryOrder.setChargeModelEvcs(2);
            }else{
                xhpcHistoryOrder.setChargeModelEvcs(xhpcChargeOrder.getChargeModelEvcs());
            }
            xhpcHistoryOrder.setSerialNumber(xhpcChargeOrder.getSerialNumber());
            xhpcHistoryOrder.setRateModelId(xhpcChargeOrder.getRateModelId());
            xhpcHistoryOrder.setStartSoc(xhpcChargeOrder.getStartSoc());
            xhpcHistoryOrder.setReconciliationStatus(0);
            xhpcHistoryOrder.setSortingStatus(0);
            if(judge){
                if(UserTypeUtil.INTERNET_TYPE.equals(source)){
                    //computeType
                    BigDecimal totalMoney = actPrice.add(promotionDiscount).add(internetCommission).add(internetSvcCommission).add(internetDegreeCommission).add(platformCommission).add(platformSvcCommission).add(operationCommission).add(operationSvcCommission).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if(money.compareTo(totalMoney)==1){
                        BigDecimal remainMoney = money.subtract(totalMoney);
                        if(computeType==1){
                            internetCommission = internetCommission.add(remainMoney);
                        }else if(computeType==2){
                            internetSvcCommission = internetSvcCommission.add(remainMoney);
                        }else{
                            internetDegreeCommission = internetDegreeCommission.add(remainMoney);
                        }
                    }
                }
                if(computeType==2){
                    xhpcHistoryOrder.setActivityPowerPriceTotal(powerPrice);
                    xhpcHistoryOrder.setActivityServicePriceTotal(activityServicePriceTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActivityTotalPrice(powerPrice.add(activityServicePriceTotal.setScale(2, BigDecimal.ROUND_HALF_UP)));
                    xhpcHistoryOrder.setActPowerPrice(powerPrice);
                    xhpcHistoryOrder.setActServicePrice(activityServicePrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActPrice(powerPrice.add(activityServicePrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setPromotionDiscount(money.subtract(xhpcHistoryOrder.getActivityTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                }else{
                    xhpcHistoryOrder.setActivityTotalPrice(activityTotalPriceTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActivityPowerPriceTotal(activityPowerPriceTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActivityServicePriceTotal(activityServicePriceTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActPrice(activityPowerPrice.add(activityServicePrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActPowerPrice(activityPowerPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setActServicePrice(activityServicePrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                    xhpcHistoryOrder.setPromotionDiscount(promotionDiscount.setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }else{
                xhpcHistoryOrder.setActPrice(actPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                xhpcHistoryOrder.setActPowerPrice(surplusPowerPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                xhpcHistoryOrder.setActServicePrice(surplusServicePrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                xhpcHistoryOrder.setPromotionDiscount(promotionDiscount.setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            xhpcHistoryOrder.setInternetCommission(internetCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setInternetSvcCommission(internetSvcCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setInternetDegreeCommission(internetDegreeCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setPlatformCommission(platformCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setPlatformSvcCommisssion(platformSvcCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setOperationCommission(operationCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setOperationSvcCommission(operationSvcCommission.setScale(2, BigDecimal.ROUND_HALF_UP));
            xhpcHistoryOrder.setStartSoc(xhpcChargeOrder.getStartSoc());
            xhpcHistoryOrder.setEndSoc(xhpcChargeOrder.getEndSoc());
            xhpcHistoryOrder.setReconciliationStatus(0);
            xhpcHistoryOrder.setSource(xhpcChargeOrder.getSource());
            Date date = new Date();
            xhpcHistoryOrder.setCreateTime(date);
            xhpcHistoryOrder.setChargeModelEvcs(3);
            if(xhpcChargeOrder.getPower()!=null){
                xhpcHistoryOrder.setConnectorPowerEvcs(Double.parseDouble(xhpcChargeOrder.getPower()));
            }

            logger.info("<<<<<<<<<<<<<<<<33333>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
            Map<String, Object> map =new HashMap<>();
            map.put("source",xhpcChargeOrder.getSource());
            map.put("tenantId",xhpcChargeOrder.getTenantId());
            BigDecimal subtract =new BigDecimal(0);
            String openid ="";
            String refundType ="";

            if(UserTypeUtil.MOTORCADE_TYPE.equals(source) || UserTypeUtil.MOTORCADE_USER_TYPE.equals(source)){
                xhpcHistoryOrder.setMotorcadeId(xhpcChargeOrder.getMotorcadeId());
                //增加流水订单号
                if(operatorMessage!=null && operatorMessage.get("operatorId")!=null){
                    String evcs = EvcsUtil.transferInternetOrderNo(xhpcChargeOrder.getSerialNumber(), operatorMessage.get("operatorId").toString());
                    xhpcHistoryOrder.setEvcsOrderNo(evcs);
                }

                if(xhpcChargeOrder.getSource()==UserTypeUtil.MOTORCADE_TYPE){
                    //扣除用户实际消费金额，添加消费记录 剩余的钱
                    BigDecimal balance1 =new BigDecimal(userMessage.get("balance").toString());
                    subtract = balance1.subtract(actPrice);
                    //消费金额
                    BigDecimal consumptionAmount =new BigDecimal(userMessage.get("consumptionAmount").toString()).add(actPrice);

                    int i = xhpcChargeOrderService.updateeMotorcadeAmount(xhpcChargeOrder.getMotorcadeId(), subtract,consumptionAmount,UserTypeUtil.MOTORCADE_TYPE,xhpcChargeOrder.getTenantId());
                    if(i==0){
                        //扣钱失败
                        logger.info("<<<<<<<<<<<<<<<<扣钱失败>>>>>>>>>>>>>>>>>");
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.fail();
                    }else{
                        logger.info("<<<<<<<<<<<<<<<<扣钱成功>>>>>>>>>>用户金额>>>>>>>"+balance1 +">>>>>>>>>>扣款金额>>>>>>>>>>"+actPrice+">>>>>>>>>>>>>剩余金额>>>>>>>>>>>>>>>>"+subtract+">>>>订单号>>>>>>>"+xhpcHistoryOrder.getSerialNumber());
                        //添加流水
                        xhpcChargeOrderService.addUserAccountStatement(xhpcChargeOrder.getMotorcadeId(), actPrice.negate(), subtract, xhpcChargeOrder.getChargeOrderId(), 3, date,xhpcChargeOrder.getSource());
                        map.put("userId",userId);
                        map.put("amount",subtract);
                    }
                }else if(0==Integer.valueOf(userMessage.get("type").toString())){
                    //扣除用户实际消费金额，添加消费记录 剩余的钱
                    BigDecimal balance1 =new BigDecimal(userMessage.get("remainingAmount").toString());
                    subtract = balance1.subtract(actPrice);
                    //消费金额
                    BigDecimal consumptionAmount =new BigDecimal(userMessage.get("consumptionAmount").toString()).add(actPrice);

                    int i = xhpcChargeOrderService.updateeMotorcadeAmount(xhpcChargeOrder.getMotorcadeId(), subtract,consumptionAmount,UserTypeUtil.MOTORCADE_TYPE,xhpcChargeOrder.getTenantId());
                    if(i==0){
                        //扣钱失败
                        logger.info("<<<<<<<<<<<<<<<<扣钱失败>>>>>>>>>>>>>>>>>");
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.fail();
                    }else{
                        logger.info("<<<<<<<<<<<<<<<<扣钱成功>>>>>>>>>>用户金额>>>>>>>"+balance1 +">>>>>>>>>>扣款金额>>>>>>>>>>"+actPrice+">>>>>>>>>>>>>剩余金额>>>>>>>>>>>>>>>>"+subtract+">>>>订单号>>>>>>>"+xhpcHistoryOrder.getSerialNumber());
                        //添加流水
                        xhpcChargeOrderService.addUserAccountStatement(xhpcChargeOrder.getMotorcadeId(), actPrice.negate(), subtract, xhpcChargeOrder.getChargeOrderId(), 3, date,xhpcChargeOrder.getSource());
                        map.put("userId",userId);
                        map.put("amount",subtract);
                    }
                }else{
                    //扣除用户实际消费金额，添加消费记录 剩余的钱
                    BigDecimal balance1 =new BigDecimal(userMessage.get("balance").toString());
                    subtract = balance1.subtract(actPrice);
                    logger.info("<<<<<<<<<<<<<<<<原本金额>>>>>>>>balance1>>>>>>>>>"+balance1.toString());
                    logger.info("<<<<<<<<<<<<<<<<剩余金额>>>>>>>>subtract>>>>>>>>>"+subtract.toString());
                    //消费金额
                    BigDecimal consumeMoney =new BigDecimal(userMessage.get("consumeMoney").toString()).add(actPrice);

                    int i = xhpcChargeOrderService.updateeMotorcadeAmount(userId, subtract,consumeMoney,5,xhpcChargeOrder.getTenantId());
                    if(i==0){
                        //扣钱失败
                        logger.info("<<<<<<<<<<<<<<<<扣钱失败>>>>>>>>>>>>>>>>>");
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.fail();
                    }else{
                        logger.info("<<<<<<<<<<<<<<<<扣钱成功>>>>>>>>>>用户金额>>>>>>>"+balance1 +">>>>>>>>>>扣款金额>>>>>>>>>>"+actPrice+">>>>>>>>>>>>>剩余金额>>>>>>>>>>>>>>>>"+subtract+">>>>订单号>>>>>>>"+xhpcHistoryOrder.getSerialNumber());
                        //添加流水
                        xhpcChargeOrderService.addUserAccountStatement(userId, actPrice.negate(), subtract, xhpcChargeOrder.getChargeOrderId(), 3, date,5);
                        map.put("userId",userId);
                        map.put("amount",subtract);
//                        xhpcChargeOrder.setSource(5);
//                        xhpcHistoryOrder.setSource(5);
                    }
                }
            }else if(!UserTypeUtil.INTERNET_TYPE.equals(source)){
                //增加流水订单号
                if(operatorMessage!=null && operatorMessage.get("operatorId")!=null){
                    String evcs = EvcsUtil.transferInternetOrderNo(xhpcChargeOrder.getSerialNumber(), operatorMessage.get("operatorId").toString());
                    xhpcHistoryOrder.setEvcsOrderNo(evcs);
                }
                //扣除用户实际消费金额，添加消费记录 剩余的钱
                BigDecimal balance1 =new BigDecimal(userMessage.get("balance").toString());
                subtract = balance1.subtract(actPrice);

                logger.info("<<<<<<<<<<<<<<<<原本金额>>>>>>>>balance1>>>>>>>>>"+balance1.toString());
                logger.info("<<<<<<<<<<<<<<<<剩余金额>>>>>>>>subtract>>>>>>>>>"+subtract.toString());
                int i = xhpcChargeOrderService.updateUserBalance(userId, subtract,xhpcChargeOrder.getSource(),xhpcChargeOrder.getTenantId());
                if(i==0){
                    //扣钱失败
                    logger.info("<<<<<<<<<<<<<<<<扣钱失败>>>>>>>>>>>>>>>>>");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.fail();
                }else{
                    if(UserTypeUtil.USER_TYPE.equals(source)){
                        Map<String, Object> userMessage1 = xhpcChargeOrderService.getUserMessage(userId);
                        logger.info("<<<<<<<<<<<<<<<<扣钱成功>>>>>>userMessage1>>>>>"+userMessage1.toString());
                    }
                    logger.info("<<<<<<<<<<<<<<<<扣钱成功>>>>>>>>>>用户金额>>>>>>>"+balance1 +">>>>>>>>>>扣款金额>>>>>>>>>>"+actPrice+">>>>>>>>>>>>>剩余金额>>>>>>>>>>>>>>>>"+subtract+">>>>订单号>>>>>>>"+xhpcHistoryOrder.getSerialNumber());
                    //添加流水
                    xhpcChargeOrderService.addUserAccountStatement(userId, actPrice.negate(), subtract, xhpcChargeOrder.getChargeOrderId(), 3, date,xhpcChargeOrder.getSource());
                    map.put("userId",userId);
                    map.put("amount",subtract);
                    if(UserTypeUtil.CHARGING_MODE_WX.equals(xhpcChargeOrder.getChargingMode())){
                        openid=userMessage.get("weixinOpenId").toString();
                        refundType="1";
                    }else if(UserTypeUtil.CHARGING_MODE_ZFB.equals(xhpcChargeOrder.getChargingMode())){
                        openid=userMessage.get("alipayOpenId").toString();
                        refundType="2";
                    }
                    map.put("remark","充电结算自动申请退款");
                }
            }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && xhpcChargeOrder.getUserId()>10000){
                //增加流水订单号
                if(operatorMessage!=null && operatorMessage.get("operatorId")!=null){
                    String evcs = EvcsUtil.transferInternetOrderNo(xhpcChargeOrder.getSerialNumber(), operatorMessage.get("operatorId").toString());
                    xhpcHistoryOrder.setEvcsOrderNo(evcs);
                }
                //扣除用户实际消费金额，添加消费记录 剩余的钱
                BigDecimal balance1 =new BigDecimal(userMessage.get("balance").toString());
                subtract = balance1.subtract(actPrice);
                int i = xhpcChargeOrderService.updateUserBalance(userId, subtract,xhpcChargeOrder.getSource(),xhpcChargeOrder.getTenantId());
                if(i==0){
                    //扣钱失败
                    logger.info("<<<<<<<<<<<<<<<<扣钱失败>>>>>>>>>>>>>>>>>");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.fail();
                }else{
                    logger.info("<<<<<<<<<<<<<<<<扣钱成功>>>>>>>>>>用户金额>>>>>>>"+balance1 +">>>>>>>>>>扣款金额>>>>>>>>>>"+actPrice+">>>>>>>>>>>>>剩余金额>>>>>>>>>>>>>>>>"+subtract+">>>>订单号>>>>>>>"+xhpcHistoryOrder.getSerialNumber());
                    //添加流水
                    xhpcChargeOrderService.addUserAccountStatement(userId, actPrice.negate(), subtract, xhpcChargeOrder.getChargeOrderId(), 3, date,xhpcChargeOrder.getSource());
                    map.put("userId",userId);
                    map.put("amount",subtract);
                    //openid=userMessage.get("weixinOpenId").toString();
                    refundType="0";
                    map.put("remark","充电结算自动申请退款");
                }
            }

            logger.info("<<<<<<<<<<<<<<<<订单结束异步之前>>>>>getUserNameEvcs>>>>>>>>>>>>"+xhpcHistoryOrder.getUserNameEvcs());
            logger.info("<<<<<<<<<<<<<<<<订单结束异步之前>>>>>getPhone>>>>>>>>>>>>"+xhpcHistoryOrder.getPhone());

            int number = xhpcHistoryOrderService.updateXhpcHistoryOrderSerialNumber(xhpcHistoryOrder);
            if(number==0){
                if(xhpcHistoryOrder.getChargingStationId()==15){
                    if(xhpcHistoryOrder.getVinNormal()!=null){
                        xhpcHistoryOrder.setVinNormal(new StringBuffer(xhpcHistoryOrder.getVinNormal()).reverse().toString());
                    }
                }
                xhpcHistoryOrder.setMark(xhpcChargeOrder.getMark());


                BigDecimal bigDecimal = xhpcHistoryOrder.getActPowerPrice().add(xhpcHistoryOrder.getActServicePrice());
                xhpcHistoryOrder.setActTotalPrice(bigDecimal);
                //该订单是否参与清分0
                if(xhpcChargeOrder.getClearingType().equals(UserTypeUtil.CLEARING_NO)){
                    xhpcHistoryOrder.setClearingType(xhpcChargeOrder.getClearingType());
                    xhpcHistoryOrder.setClearingPrice(bigDecimal);
//                    xhpcHistoryOrder.setActServicePrice(new BigDecimal(0));
//                    xhpcHistoryOrder.setActPowerPrice(new BigDecimal(0));
                }else{
                    xhpcHistoryOrder.setClearingPrice(new BigDecimal(0));
                }
                xhpcHistoryOrderService.insert(xhpcHistoryOrder);
            }
            xhpcChargeOrderService.updateXhpcChargeOrder(xhpcChargeOrder);
            logger.info("<<<<<<<<<<<<<<<<订单结束异步之前>>>>>>>>>>>>>>>>>"+xhpcHistoryOrder.getSerialNumber());
            final BigDecimal balance = actPrice;
            final String balance2 = subtract.toString();
            final String openids =openid;
            final String refundTypes =refundType;
            Map<String, Object> xhpcChargingPile = xhpcChargeOrderService.getXhpcChargingPile(xhpcChargeOrder.getTerminalId());
            // 另起线程处理业务上传redis数据
            BigDecimal finalActPrice = actPrice;
            String keyUser =xhpcChargeOrder.getSerialNumber();
            redisService.deleteObject("YE"+xhpcChargeOrder.getSerialNumber());
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try{
                        logger.info("<<<<<<<<<<<<<<<<进行入短信发送>>>>>>>>>>>>>>>>>");

                        if(!UserTypeUtil.INTERNET_TYPE.equals(source) && !UserTypeUtil.MOTORCADE_TYPE.equals(source)&& !UserTypeUtil.MOTORCADE_USER_TYPE.equals(source)){
                            if(userMessage !=null && userMessage.get("phone") != null){
                                if("1".equals(xhpcChargingPile.get("type").toString())){
                                    if(UserTypeUtil.USER_TYPE.equals(source)){
                                        if(xhpcHistoryOrder.getChargingMode().equals("微信")){
                                            String phoneObject = redisService.getCacheObject("WXToken:wxd0a48e00319ef8a7");
                                            String serialNumber = xhpcHistoryOrder.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";
                                            }
                                            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+"枪",xhpcHistoryOrder.getEndSoc(),xhpcHistoryOrder.getActPrice().toString(),xhpcChargeOrder.getChargingTime());
                                        }else if(xhpcHistoryOrder.getChargingMode().equals("支付宝")){
                                            String phone =userMessage.get("phone").toString();
                                            String phoneObject = redisService.getCacheObject(phone+":"+balance.toString());
                                            if (phoneObject == null || "".equals(phoneObject)) {
                                                HashMap<String, String> paramMap = new HashMap<>();
                                                paramMap.put("elec", xhpcChargeOrder.getEndSoc());
                                                paramMap.put("sumMoney", balance.toString());
                                                paramMap.put("phone", phone);
                                                paramMap.put("content", "【翔桦充电】尊敬的用户，你的爱车已停止充电，电量为：" + xhpcChargeOrder.getEndSoc() + "%，总费用为：" + balance + "元，充电费用明细，请查询翔桦充电小程序，谢谢。");
                                                smsService.sendNotice(paramMap);
                                                redisService.setCacheObject(phone+":"+balance.toString(), balance.toString(), 300L, TimeUnit.SECONDS);
                                            }
                                        }
                                    }else{
                                        String phone =userMessage.get("phone").toString();
                                        String phoneObject = redisService.getCacheObject(phone+":"+balance.toString());
                                        if (phoneObject == null || "".equals(phoneObject)) {
                                            HashMap<String, String> paramMap = new HashMap<>();
                                            paramMap.put("elec", xhpcChargeOrder.getEndSoc());
                                            paramMap.put("sumMoney", balance.toString());
                                            paramMap.put("phone", phone);
                                            paramMap.put("content", "【翔桦充电】尊敬的用户，你的爱车已停止充电，电量为：" + xhpcChargeOrder.getEndSoc() + "%，总费用为：" + balance + "元，充电费用明细，请查询翔桦充电小程序，谢谢。");
                                            smsService.sendNotice(paramMap);
                                            redisService.setCacheObject(phone+":"+balance.toString(), balance.toString(), 300L, TimeUnit.SECONDS);
                                        }
                                    }
                                }else {
                                    HashMap<String, String> paramMap = new HashMap<>();
                                    paramMap.put("sumMoney", balance.toString());
                                    paramMap.put("phone", userMessage.get("phone").toString());
                                    paramMap.put("content", "【翔桦充电】尊敬的用户，你的爱车已停止充电，总费用为：" + balance.toString() + "元，充电费用明细，请查询翔桦充电小程序，谢谢。");
                                    smsService.sendNotice(paramMap);
                                }
                            }
                        }
                    }catch (Exception e){
                        logger.info("<<<<<<<<<<<<<<<<发送短信失败>>>>>>>>>>>>>>>>>");
                    }
                    addPileEndOrder(xhpcHistoryOrder, xhpcChargeOrder, xhpcChargeOrder.getSerialNumber(),1);
                    if(!UserTypeUtil.INTERNET_TYPE.equals(source) && !UserTypeUtil.MOTORCADE_TYPE.equals(source) && !UserTypeUtil.MOTORCADE_USER_TYPE.equals(source)){
                        try{
                            //双枪修改逻辑，查询是否是双枪
                            if(xhpcChargeOrder.getSunchaStatus()!=0){
                                String userType =UserTypeUtil.USER;
                                if(UserTypeUtil.COMMUNIT_TYPE==xhpcChargeOrder.getSource()){
                                    userType =UserTypeUtil.COMMUNIT;
                                }else if(UserTypeUtil.CUSTOMERS_TYPE==xhpcChargeOrder.getSource()){
                                    userType =UserTypeUtil.CUSTOMERS;
                                }
                                Map<String, Object> map = new HashMap<>();
                                String key = "user:" + xhpcChargeOrder.getUserId() + userType + ".order";
                                Map<String, Object> cacheMap = redisService.getCacheMap(key);

                                if(xhpcChargeOrder.getSunchaStatus()==1){
                                    map.put("aBalanceStatus",1);
                                    BigDecimal aBalance = new BigDecimal(cacheMap.get("aBalance").toString()).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_CEILING);
                                    BigDecimal subtract = aBalance.subtract(finalActPrice);
                                    map.put("aBalance",subtract.multiply(new BigDecimal(100)).toString());
                                    xhpcChargeOrderService.updateUserSunchaBalance(userId, subtract,xhpcChargeOrder.getSource(),xhpcChargeOrder.getTenantId(),1);
                                }else{
                                    map.put("bBalanceStatus",1);
                                    BigDecimal bBalance = new BigDecimal(cacheMap.get("bBalance").toString()).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_CEILING);
                                    BigDecimal subtract = bBalance.subtract(finalActPrice);
                                    map.put("bBalance",subtract.multiply(new BigDecimal(100)).toString());
                                    xhpcChargeOrderService.updateUserSunchaBalance(userId, subtract,xhpcChargeOrder.getSource(),xhpcChargeOrder.getTenantId(),2);
                                }
                                redisService.setCacheMap(key,map);
                                boolean a =true;  //A账户未有充电中、异常订单
                                boolean b =true;  //b账户未有充电中、异常订单
                                //查询所有状态
                                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){
                                    String i = xhpcChargeOrderService.countXhpcRealTimeOrder(xhpcChargeOrder.getUserId(),xhpcChargeOrder.getSource(),xhpcChargeOrder.getTenantId());
                                    if (!"".equals(i) && i!=null) {
                                        //"车辆正在充电,请查询车辆充电信息"
                                    }else{
                                        //退款，判断A+B账号金额 = 总金额
                                        R user = userTypeService.getUser(null, userId, source, null, tenantId);
                                        if(user !=null && user.getData() !=null ){
                                            Map<String, Object> userMap = (Map<String, Object>)user.getData();
                                            if (userMap == null || userMap.get("balance") == null) {
                                                //获取用户信息失败
                                            }else{
                                                BigDecimal balance = new BigDecimal(userMap.get("balance").toString());
                                                BigDecimal aBalance = new BigDecimal(userMap.get("aBalance").toString());
                                                BigDecimal bBbalance = new BigDecimal(userMap.get("bBbalance").toString());
                                                if(balance.compareTo(aBalance.add(bBbalance))==0){
                                                    //退款
                                                    if(userMessage !=null && "1".equals(userMessage.get("isRefund").toString()) && map !=null){
                                                        if(UserTypeUtil.CHARGING_MODE_WX.equals(xhpcChargeOrder.getChargingMode()) ||UserTypeUtil.CHARGING_MODE_ZFB.equals(xhpcChargeOrder.getChargingMode()) ){
                                                            if(UserTypeUtil.USER_TYPE.equals(source) || UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                                                                refundOrderService.sendNotice(balance2,openids,xhpcChargeOrder.getSource(),refundTypes,xhpcChargeOrder.getUserId().toString(),xhpcChargeOrder.getTenantId(),"充电结算自动申请退款");
                                                                redisService.deleteObject(key);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                //充电结算后自动申请退款
                                if(userMessage !=null && "1".equals(userMessage.get("isRefund").toString()) && map !=null){
                                    if(UserTypeUtil.CHARGING_MODE_WX.equals(xhpcChargeOrder.getChargingMode()) ||UserTypeUtil.CHARGING_MODE_ZFB.equals(xhpcChargeOrder.getChargingMode()) ){
                                        if(UserTypeUtil.USER_TYPE.equals(source) || UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                                            refundOrderService.sendNotice(balance2,openids,xhpcChargeOrder.getSource(),refundTypes,xhpcChargeOrder.getUserId().toString(),xhpcChargeOrder.getTenantId(),"充电结算自动申请退款");
                                        }
                                    }
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            logger.info("<<<<<<<<<<<<<<<<自动退款失败>>>>>>>>>>>>>>>>>");
                        }
                    }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
                        //自动退款
                        refundOrderService.cycOrderCheckOut(balance2,xhpcChargeOrder.getSource(),xhpcChargeOrder.getUserId()+"",xhpcChargeOrder.getTenantId());
                    }

                    //川逸充，调用订单结束推送
                    if(UserTypeUtil.INTERNET_TYPE.equals(source) && xhpcChargeOrder.getUserId()>10000){
                        logger.info("<<<<<<<<<11<<<<<<<川逸充，调用订单结束推送>>>>>>>>>>>>>>>>>");
                        Map<String, Object> orderMap =new HashMap<>();
                        orderMap.put("orderNo",xhpcHistoryOrder.getSerialNumber());
                        orderMap.put("OperatorID","MA6CC2LK7");
                        orderMap.put("elecMoney",xhpcHistoryOrder.getPowerPriceTotal());
                        orderMap.put("seviceMoney",xhpcHistoryOrder.getServicePriceTotal());
                        orderMap.put("totalMoney",xhpcHistoryOrder.getTotalPower());

                        evcsService.getCYCNotificationConnectorChargeStatus(orderMap);
                        logger.info("<<<<<<<<<22<<<<<<<川逸充，调用订单结束推送>>>>>>>>>>>>>orderMap>>>>"+orderMap.toString());
                    }


                }
            });
            //小华充电二台子社区充电站 道闸
            try{
                if(xhpcChargeOrder.getPlateNum() !=null && !"".equals(xhpcChargeOrder.getPlateNum())){
                    Map<String, Object> xhpcBarrierGate = xhpcChargeOrderService.getXhpcBarrierGate(xhpcChargeOrder.getChargingStationId());
                    if(xhpcBarrierGate !=null && xhpcBarrierGate.get("url") !=null && xhpcBarrierGate.get("chargingStationNumber") !=null){
                        Map<String, Object> barrierGateMap = new HashMap<>();
                        barrierGateMap.put("plateNo", xhpcChargeOrder.getPlateNum());
                        barrierGateMap.put("chargingStationNumber", xhpcBarrierGate.get("chargingStationNumber").toString());
                        barrierGateMap.put("chargingStationName", xhpcBarrierGate.get("name").toString());
                        barrierGateMap.put("address", xhpcBarrierGate.get("address").toString());
                        barrierGateMap.put("longitude", xhpcBarrierGate.get("longitude").toString());
                        barrierGateMap.put("latitude", xhpcBarrierGate.get("latitude").toString());
                        barrierGateMap.put("startTime", xhpcHistoryOrder.getStartTime());
                        barrierGateMap.put("endTime", xhpcHistoryOrder.getEndTime());
                        JSONObject json = new JSONObject(barrierGateMap);
                        String result = HttpUtils.post(xhpcBarrierGate.get("url").toString(), json);
                        JSONObject jsonObject = JSON.parseObject(result);
                        String code = jsonObject.getString("ret");
                        XhpcBarrierGateRecord xhpcBarrierGateRecord = new XhpcBarrierGateRecord();
                        if("200".equals(code)){
                            xhpcBarrierGateRecord.setStatus(0);
                        }else{
                            xhpcBarrierGateRecord.setStatus(1);
                        }
                        xhpcBarrierGateRecord.setBarrierGateId(Long.parseLong(xhpcBarrierGate.get("barrierGateId").toString()));
                        xhpcBarrierGateRecord.setUserId(userId);
                        xhpcBarrierGateRecord.setSource(source);
                        xhpcBarrierGateRecord.setChargingStationId(xhpcChargeOrder.getChargingStationId());
                        xhpcBarrierGateRecord.setSendingTime(new Date());
                        xhpcBarrierGateRecord.setDelFlag(0);
                        xhpcBarrierGateRecord.setRemark(result);
                        xhpcBarrierGateRecord.setSerialNumber(xhpcChargeOrder.getSerialNumber());
                        xhpcBarrierGateRecord.setInternetSerialNumber(xhpcChargeOrder.getInternetSerialNumber());
                        xhpcBarrierGateRecord.setPlateNum(xhpcChargeOrder.getPlateNum());
                        xhpcBarrierGateRecord.setPhone(xhpcHistoryOrder.getPhone());
                        xhpcBarrierGateRecord.setHistoryOrderId(xhpcHistoryOrder.getHistoryOrderId());
                        xhpcRealTimeOrderMapper.insertXhpcBarrierGateRecord(xhpcBarrierGateRecord);
                        xhpcHistoryOrder.setParkingVoucher(2);
                        xhpcHistoryOrderService.updateXhpcHistoryOrderParkingVoucher(xhpcHistoryOrder);
                    }

                }
            }catch (Exception e){
                e.printStackTrace();
            }
            //查询该场站是否有占位费
            Map<String, Object> xhpcPlaceholderMap;
            if(xhpcHistoryOrder.getSource() != UserTypeUtil.INTERNET_TYPE){
                xhpcPlaceholderMap = xhpcRealTimeOrderMapper.getXhpcPlaceholder(xhpcHistoryOrder.getChargingStationId(),null,xhpcHistoryOrder.getSource()+"");
            }else{
                xhpcPlaceholderMap = xhpcRealTimeOrderMapper.getXhpcPlaceholder(xhpcHistoryOrder.getChargingStationId(),xhpcHistoryOrder.getUserId()+"",null);
            }
            System.out.println("===============生成占位费订单=============================");
            if(xhpcPlaceholderMap !=null){
                //占位订单生成
                XhpcPlaceholderOrder placeholderOrder = new XhpcPlaceholderOrder();

                if(xhpcHistoryOrder.getSource() !=UserTypeUtil.INTERNET_TYPE){
                    if(0 == xhpcHistoryOrder.getSource()){
                        placeholderOrder.setChargingMode("C端用户");
                    }else if(2 == xhpcHistoryOrder.getSource()){
                        placeholderOrder.setChargingMode("社区用户");
                    }else if(3 == xhpcHistoryOrder.getSource()){
                        placeholderOrder.setChargingMode("B端用户");
                    }else{
                        placeholderOrder.setChargingMode("车队");
                    }
                }else{
                    placeholderOrder.setChargingMode(xhpcHistoryOrder.getChargingMode());
                }
                placeholderOrder.setDriverId(xhpcChargeOrder.getDriverId());
                placeholderOrder.setHistoryOrderId(xhpcHistoryOrder.getHistoryOrderId());
                placeholderOrder.setChargingStationId(xhpcHistoryOrder.getChargingStationId());
                placeholderOrder.setChargeOrderId(xhpcHistoryOrder.getChargeOrderId());
                placeholderOrder.setTerminalId(xhpcHistoryOrder.getTerminalId());
                placeholderOrder.setUserId(xhpcHistoryOrder.getUserId());
                placeholderOrder.setSerialNumber(xhpcHistoryOrder.getSerialNumber());
                placeholderOrder.setInternetSerialNumber(xhpcHistoryOrder.getInternetSerialNumber());
                if(xhpcChargeOrder.getSource()==UserTypeUtil.INTERNET_TYPE){
                    placeholderOrder.setInternetIdEvcs(xhpcHistoryOrder.getInternetSerialNumber().substring(0,9));
                }
                placeholderOrder.setConfirmResult(-2);
                placeholderOrder.setSource(xhpcHistoryOrder.getSource());
                placeholderOrder.setPlaceholderId(Long.valueOf(xhpcPlaceholderMap.get("placeholderId").toString()));
                placeholderOrder.setFreeTime(Integer.valueOf(xhpcPlaceholderMap.get("freeTime").toString()));
                placeholderOrder.setMaxFee(new BigDecimal(xhpcPlaceholderMap.get("maxFee").toString()).intValue());
                placeholderOrder.setOperatorId("MA6DFCTD5");
                //订单流水号 终端号+年月日时分秒+自增4位 共32位
                String substring = xhpcHistoryOrder.getSerialNumber().substring(0, 16);
                String orderNo = genOrder(substring);
                placeholderOrder.setPlaceholderOrderNumber(orderNo);
                placeholderOrder.setStatus(1);
                placeholderOrder.setTerminalNumber(substring);
                placeholderOrder.setBillEquipment(1);
                placeholderOrder.setStartTime(xhpcHistoryOrder.getEndTime());
                placeholderOrder.setCreateTime(new Date());
                placeholderOrder.setTenantId(xhpcHistoryOrder.getTenantId());
                placeholderOrder.setPlateNum(xhpcChargeOrder.getPlateNum());
                placeholderOrderService.insertXhpcPlaceholderOrder(placeholderOrder);
                logger.info("<<<<<<<<<<<<<<getPlaceholderOrderId>>>>>>>>>>>>>>>>"+placeholderOrder.getPlaceholderOrderId());

                String gunkey ="gun:"+xhpcHistoryOrder.getSerialNumber().substring(0,16);
                Map<String, Object> cacheGun =new HashMap<>();
                cacheGun.put("previousOrder",xhpcHistoryOrder.getSerialNumber());
                REDIS.setCacheMap(gunkey, cacheGun);
            }
            if(xhpcHistoryOrder.getTotalPrice().compareTo(new BigDecimal(0))>0){
                //生成历史订单收费明细
                installXhpcHistoryOrderChargeDetails(xhpcHistoryOrder);
            }
            String orderKey = xhpcChargeOrder.getMark()+":"+xhpcChargeOrder.getMotorcadeId()+":"+xhpcChargeOrder.getSerialNumber();
            redisService.deleteObject(orderKey);
        }catch (Exception e){
            e.printStackTrace();
            logger.info("<<<<<<<<<<<<<<<<运行异常，结算失败，数据回滚>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
            logger.info("<<<<<<<<<<<<<<<<运行异常，结算失败，数据回滚>>>>>>>>>>>>>>>>>");
            e.printStackTrace();
            logger.info("<<<<<<<<<<<<<<<<运行异常，结算失败，数据回滚>>>>>>>>>>>>>>>>>"+xhpcChargeOrder.getSerialNumber());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail();
        }
        return R.ok();
    }

    @Override
    public void deleteRealTimeOrder(Long chargingOrderId) {
        xhpcRealTimeOrderMapper.deleteRealTimeOrder(chargingOrderId);
        xhpcRealTimeOrderMapper.deleteChargeOrderCurrent(chargingOrderId);
        xhpcRealTimeOrderMapper.deleteChargeOrderSoc(chargingOrderId);
        xhpcRealTimeOrderMapper.deleteChargeVoltage(chargingOrderId);
    }

    @Override
    public void addPileEndOrder(XhpcHistoryOrder xhpcHistoryOrder, XhpcChargeOrder xhpcChargeOrder, String orderNo,Integer type) {
        Map<String, Object> cacheMap = redisService.getCacheMap("order:" + orderNo);
        Date date = new Date();
        Long chargeOrderId = xhpcChargeOrder.getChargeOrderId();
        //删除实时数据，获取最新的实时数据
        //deleteRealTimeOrder(xhpcChargeOrder.getChargeOrderId());
        //添加新的实时数据
//        List<CacheRealtimeData> list = (List<CacheRealtimeData>) cacheMap.get("realtimeDataList");
//        if (list != null && list.size() > 0) {
//            for (CacheRealtimeData cacheRealtimeData : list) {
//                addOrderTime(cacheRealtimeData, xhpcChargeOrder, orderNo, type);
//            }
//        }
        //添加redis到数据库
        XhpcOrderRedisRecord xhpcOrderRedisRecord =new XhpcOrderRedisRecord();
        xhpcOrderRedisRecord.setChargeOrderId(chargeOrderId);
        xhpcOrderRedisRecord.setSerialNumber(xhpcHistoryOrder.getSerialNumber());
        xhpcOrderRedisRecord.setHistoryOrderOd(xhpcHistoryOrder.getHistoryOrderId());
        if(cacheMap.get("endSoc") !=null){
            xhpcOrderRedisRecord.setEndSoc(cacheMap.get("endSoc").toString());
        }
        if(cacheMap.get("status") !=null){
            xhpcOrderRedisRecord.setStatus(cacheMap.get("status").toString());
        }
        if(cacheMap.get("balance") !=null){
            xhpcOrderRedisRecord.setBalance(cacheMap.get("balance").toString());
        }
        if(cacheMap.get("tel") !=null){
            xhpcOrderRedisRecord.setTel(cacheMap.get("tel").toString());
        }
        if(cacheMap.get("startSoc") !=null){
            xhpcOrderRedisRecord.setStartSoc(cacheMap.get("startSoc").toString());
        }
        if(cacheMap.get("startResult") !=null){
            xhpcOrderRedisRecord.setStartResult(cacheMap.get("startResult").toString());
        }
        if(cacheMap.get("realtimeDataList") !=null){
            xhpcOrderRedisRecord.setRealtimeDataList(cacheMap.get("realtimeDataList").toString());
        }
        if(cacheMap.get("remainingTime") !=null){
            xhpcOrderRedisRecord.setRemainingTime(cacheMap.get("remainingTime").toString());
        }
        if(cacheMap.get("rateModelId") !=null){
            xhpcOrderRedisRecord.setRateModelId(cacheMap.get("rateModelId").toString());
        }
        if(cacheMap.get("lt5alerted") !=null){
            xhpcOrderRedisRecord.setLt5alerted(cacheMap.get("lt5alerted").toString());
        }
        if(cacheMap.get("orderData") !=null){
            CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
            xhpcOrderRedisRecord.setOrderData(cacheOrderData.toString());
        }
        xhpcOrderRedisRecord.setCreateTime(date);
        xhpcChargeOrderService.addXhpcOrderRedisRecord(xhpcOrderRedisRecord);
        //删除redis
        //redisService.deleteObject("order:"+orderNo);
        //redisService.deleteObject("order:"+orderNo+".lord");
        logger.info("<<<<<<<<<<<<<<<<订单结束回调成功>>>>>>>>>订单号：>>>"+orderNo+">>>>>");
        logger.info("<<<<<<<<<<<<<<<<订单结束回调成功>>>>>>>>>订单号：>>>"+orderNo+">>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<订单结束回调成功>>>>>>>>>订单号：>>>"+orderNo+">>>>>>>>");
        try {
            int startSoc = Integer.parseInt(xhpcHistoryOrder.getStartSoc());
            int endSoc = Integer.parseInt(xhpcHistoryOrder.getEndSoc());
            String stopReason = xhpcHistoryOrder.getStopReasonEvcs();
            if(("40".equals(stopReason) || "41".equals(stopReason)||"6E".equals(stopReason)||"42".equals(stopReason)||"43".equals(stopReason)||"44".equals(stopReason)||"45".equals(stopReason)||"4E".equals(stopReason))){

            }else{
                XhpcWorkHistoryOrderDto xhpcWorkHistoryOrderDto =new XhpcWorkHistoryOrderDto();
                BeanUtils.copyProperties(xhpcHistoryOrder,xhpcWorkHistoryOrderDto);
                String nameByCode = StopReasonEnum.getNameByCode(xhpcHistoryOrder.getStopReasonEvcs());
                xhpcWorkHistoryOrderDto.setStopReasonEvcsName(nameByCode);
                xhpcHistoryOrderService.insertXhpcWorkHistoryOrderDto(xhpcWorkHistoryOrderDto);
                logger.info("<<<<<<<<<<<<<<<<入库成功>>>>>>>>>订单号：>>>");
            }

            //存储订单最大功率数据
            String key ="orderOutpu:"+orderNo;
            XhpcRealTimeOrderBms bms = redisService.getCacheObject(key);
            if(bms!=null){
                XhpcOrderOutputMax max=new XhpcOrderOutputMax();
                BeanUtils.copyProperties(bms,max);
                max.setCountPileOutput(new BigDecimal(max.getPileVoltageOutput()).multiply(new BigDecimal(max.getPileCurrentOutput())).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_CEILING).doubleValue());
                max.setCountBmsRequest(new BigDecimal(max.getBmsVoltageRequest()).multiply(new BigDecimal(max.getBmsCurrentRequest())).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_CEILING).doubleValue());
                max.setChargeOrderId(xhpcChargeOrder.getChargeOrderId());
                max.setChargingStationId(xhpcChargeOrder.getChargingStationId());
                max.setTerminalId(xhpcChargeOrder.getTerminalId());
                max.setBmsChargingVolt(bms.getBmsChargingVolt());
                max.setBmsChargingCurrent(bms.getBmsChargingCurrent());
                xhpcRealTimeOrderMapper.insertOrderOutputMax(max);
            }
        }catch (Exception e){

        }

    }



    /**
     * 添加实时数据
     *
     * @param cacheRealtimeData
     * @param xhpcChargeOrder
     * @param orderNo           订单号
     * @param type              1.实时数据回调  2.结算回调
     * @return
     */
    @Override
    public Map<String, Object> addOrderTime(CacheRealtimeData cacheRealtimeData, XhpcChargeOrder xhpcChargeOrder,
                                            String orderNo, Integer type) {

        Map<String, Object> map = new HashMap<>();
        Date date = new Date();
        Long chargeOrderId = xhpcChargeOrder.getChargeOrderId();
        XhpcRealTimeOrder xhpcRealTimeOrder = new XhpcRealTimeOrder();
        xhpcRealTimeOrder.setSource(xhpcChargeOrder.getSource());
        xhpcRealTimeOrder.setChargingOrderId(xhpcChargeOrder.getChargeOrderId());
        xhpcRealTimeOrder.setTransactionNumber(orderNo);
        xhpcRealTimeOrder.setPileNumber(cacheRealtimeData.getPileNo());
        String gunId = cacheRealtimeData.getGunId();
        xhpcRealTimeOrder.setGunNumber(gunId);
        if("00".equals(cacheRealtimeData.getPileGunStatus())){
            xhpcRealTimeOrder.setPileGunStatus(0);
        }else if("01".equals(cacheRealtimeData.getPileGunStatus())){
            xhpcRealTimeOrder.setPileGunStatus(1);
        }else{
            xhpcRealTimeOrder.setPileGunStatus(2);
        }
        if("00".equals(cacheRealtimeData.getVehicleGunStatus())){
            xhpcRealTimeOrder.setVehicleGunStatus(0);
        }else{
            xhpcRealTimeOrder.setVehicleGunStatus(1);
        }
        BigDecimal v = new BigDecimal(cacheRealtimeData.getWorkingVoltage()).divide(new BigDecimal(10));
        BigDecimal c = new BigDecimal(cacheRealtimeData.getWorkingCurrent()).divide(new BigDecimal(10));
        BigDecimal decimal1 = v.multiply(c).setScale(2, BigDecimal.ROUND_HALF_UP);
        xhpcRealTimeOrder.setVoltage(v);
        xhpcRealTimeOrder.setElectricCurrent(c);
        xhpcRealTimeOrder.setGunLineTemperature(cacheRealtimeData.getGunLineTemperature());
        xhpcRealTimeOrder.setGunLineNumber(cacheRealtimeData.getGunLineNumber());
        Integer soc = cacheRealtimeData.getSoc();
        xhpcRealTimeOrder.setSoc(soc.toString());
        xhpcRealTimeOrder.setMaxTemperature(cacheRealtimeData.getMaxTemperature());
        Integer chargingTime = cacheRealtimeData.getChargingTime();
        if(chargingTime>60){
            int hours = chargingTime / 60;
            int mins = (chargingTime-(hours*60)) % 60;
            xhpcRealTimeOrder.setChargingTime(hours+"时"+mins+"分");
        }else{
            xhpcRealTimeOrder.setChargingTime(chargingTime+"分");
        }
        Integer remainingTime = cacheRealtimeData.getRemainingTime();
        if(remainingTime>60){
            int hours = remainingTime / 60;
            double mins = (remainingTime-(hours*60))/60;
            xhpcRealTimeOrder.setRemainingTime(hours+"时"+new BigDecimal(mins).setScale(0)+"分");
        }else{
            double mins = remainingTime / 60;
            xhpcRealTimeOrder.setRemainingTime(new BigDecimal(mins).setScale(0)+"分");
        }
        BigDecimal decimal = new BigDecimal(10000);
        BigDecimal divide = new BigDecimal(cacheRealtimeData.getLossChargingDegree()).divide(decimal);
        BigDecimal chargingDegree = new BigDecimal(cacheRealtimeData.getChargingDegree()).divide(decimal);
        xhpcRealTimeOrder.setChargingDegree(chargingDegree);
        xhpcRealTimeOrder.setLossChargingDegree(divide);
        BigDecimal amountCharged = new BigDecimal(cacheRealtimeData.getAmountCharged()).divide(decimal);
        xhpcRealTimeOrder.setAmountCharged(amountCharged);
        xhpcRealTimeOrder.setHardwareFault(cacheRealtimeData.getHardwareFault());
        if ("00".equals(cacheRealtimeData.getStatus())) {
            xhpcRealTimeOrder.setStatus(0);
        } else if ("01".equals(cacheRealtimeData.getStatus())) {
            xhpcRealTimeOrder.setStatus(1);
        } else if ("02".equals(cacheRealtimeData.getStatus())) {
            xhpcRealTimeOrder.setStatus(2);
        } else {
            xhpcRealTimeOrder.setStatus(3);
        }
        xhpcRealTimeOrder.setCreateTime(date);
        xhpcRealTimeOrder.setUserId(xhpcChargeOrder.getUserId());
        Long chargingStationId = xhpcChargeOrder.getChargingStationId();
        xhpcRealTimeOrder.setChargingStationId(chargingStationId);
        xhpcRealTimeOrder.setChargingTimeNumber(cacheRealtimeData.getChargingTime());

        XhpcChargingPile xhpcChargingPiles = xhpcRealTimeOrderMapper.getSerialNumber(xhpcChargeOrder.getSerialNumber().substring(0, 14));

        xhpcRealTimeOrder.setChargingPileId(xhpcChargingPiles.getChargingPileId());
        xhpcRealTimeOrder.setTerminalId(xhpcChargeOrder.getTerminalId());
        addXhpcRealTimeOrder(xhpcRealTimeOrder);
        //实时数据存入MYsql、soc、电流、电压

        XhpcChargeOrderSoc xhpcChargeOrderSoc = new XhpcChargeOrderSoc();
        xhpcChargeOrderSoc.setChargeOrderId(chargeOrderId);
        xhpcChargeOrderSoc.setSoc(soc.toString());
        xhpcChargeOrderSoc.setCreateTime(date);
        addSOC(xhpcChargeOrderSoc);

        XhpcChargeOrderCurrent xhpcChargeOrderCurrent =new XhpcChargeOrderCurrent();
        xhpcChargeOrderCurrent.setChargeOrderId(chargeOrderId);
        xhpcChargeOrderCurrent.setCurrent(c.toString());
        xhpcChargeOrderCurrent.setCreateTime(date);
        addCurrent(xhpcChargeOrderCurrent);

        XhpcChargeOrderVoltage xhpcChargeOrderVoltage =new XhpcChargeOrderVoltage();
        xhpcChargeOrderVoltage.setChargeOrderId(chargeOrderId);
        xhpcChargeOrderVoltage.setVoltage(v.toString());
        xhpcChargeOrderVoltage.setCreateTime(date);
        addVoltage(xhpcChargeOrderVoltage);
        if(type==1){
            map.put("code", 200);
            map.put("message", "实时数据");
            map.put("userId", xhpcChargeOrder.getUserId());
            Map<String, Object> data = new HashMap<>();
            data.put("amountCharged",amountCharged);
            data.put("gunNumber",gunId);
            data.put("chargingOrderId",chargeOrderId);
            data.put("chargingTimeNumber",cacheRealtimeData.getChargingTime());
            data.put("soc",soc);
            data.put("chargingTime",xhpcRealTimeOrder.getChargingTime());
            data.put("electricCurrent",c);
            data.put("voltage", v);
            data.put("power", decimal1.divide(new BigDecimal(1000),2,BigDecimal.ROUND_HALF_UP));
            data.put("chargingDegree", chargingDegree);
            data.put("remainingTime",xhpcRealTimeOrder.getRemainingTime());
            data.put("serialNumber",orderNo.substring(0,16));
            data.put("parkingInstructions","充电完成请尽快离场,超时车位占用费10元/小时");
            //获取桩直流还是交流
            Map<String, Object> xhpcChargingPile = xhpcChargeOrderService.getXhpcChargingPile(xhpcChargeOrder.getTerminalId());
            if(xhpcChargingPile !=null){
                data.put("type", xhpcChargingPile.get("type").toString());
            }else{
                data.put("type", 1);
            }
            map.put("data", data);
        }
        return map;
    }

    @Override
    public XhpcRealTimeOrder getChargingOrderId(Long chargingOrderId, Integer type) {
        return xhpcRealTimeOrderMapper.getChargingOrderId(chargingOrderId, type);
    }

    /**
     * 添加一条金额为0的数据
     *
     * @param xhpcChargeOrder
     */
    @Override
    public void addZeroHistoryOrder(XhpcChargeOrder xhpcChargeOrder) {

        XhpcHistoryOrder xhpcHistoryOrder = new XhpcHistoryOrder();
        xhpcHistoryOrder.setChargeOrderId(xhpcChargeOrder.getChargeOrderId());
        xhpcHistoryOrder.setChargingStationId(xhpcChargeOrder.getChargingStationId());
        xhpcHistoryOrder.setUserId(xhpcChargeOrder.getUserId());
        xhpcHistoryOrder.setTerminalId(xhpcChargeOrder.getTerminalId());
        xhpcHistoryOrder.setSerialNumber(xhpcChargeOrder.getSerialNumber());
        xhpcHistoryOrder.setInternetSerialNumber(xhpcChargeOrder.getInternetSerialNumber());
        xhpcHistoryOrder.setType(2);
        xhpcHistoryOrder.setStatus(0);
        xhpcHistoryOrder.setStartSoc(xhpcChargeOrder.getStartSoc());
        xhpcHistoryOrder.setEndSoc(xhpcChargeOrder.getEndSoc());
        Date date = new Date();
        xhpcHistoryOrder.setCreateTime(date);

        if("微信".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("微信");
        }
        if("支付宝".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("支付宝");
        }
        if("刷卡".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("刷卡");
        }
        if("VIN码".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("VIN码");
        }
        if("川逸充".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("川逸充");
        }
        if("快电".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("1");
        }
        if("恒大".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("2");
        }
        if("新电途".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("3");
        }
        if("小桔".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("4");
        }
        if("车为家".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("7");
        }
        if("运快充".equals(xhpcChargeOrder.getChargingMode())){
            xhpcHistoryOrder.setChargingMode("7");
        }
        Map<String, Object> pushOrder = redisService.getCacheMap("pushOrder:"+xhpcChargeOrder.getSerialNumber());
        if(pushOrder !=null){
            if(pushOrder.get("operatorId3rdpty") !=null){
                xhpcHistoryOrder.setOperatorId3rdptyEvcs((String) pushOrder.get("operatorId3rdpty"));
            }
        }
        //获取运营商
        Map<String, Object> operatorMessage = xhpcChargeOrderService.getOperatorMessage(xhpcChargeOrder.getChargingStationId());
        if(operatorMessage !=null){
            if(operatorMessage.get("operatorIdEvcs")!=null){
                if(operatorMessage.get("operatorIdEvcs") !=null && !"".equals(operatorMessage.get("operatorIdEvcs").toString())){
                    String stw = operatorMessage.get("operatorIdEvcs").toString();
                    if(stw.length()==9){
                        // xhpcHistoryOrder.setOperatorIdEvcs(stw);
                    }
                }
            }
        }
        if(xhpcChargeOrder.getStartTime()==null){
            xhpcHistoryOrder.setStartTime(xhpcChargeOrder.getCreateTime());
            xhpcHistoryOrder.setEndTime(xhpcChargeOrder.getCreateTime());
        }else{
            xhpcHistoryOrder.setStartTime(xhpcChargeOrder.getStartTime());
            xhpcHistoryOrder.setEndTime(xhpcChargeOrder.getStartTime());
        }
        xhpcHistoryOrder.setStopReasonEvcs(xhpcChargeOrder.getType());

        if(UserTypeUtil.COMMUNIT_TYPE.equals(xhpcChargeOrder.getSource()) || UserTypeUtil.CUSTOMERS_TYPE.equals(xhpcChargeOrder.getSource())){
            xhpcHistoryOrder.setChargeModelEvcs(2);
        }else{
            xhpcHistoryOrder.setChargeModelEvcs(xhpcChargeOrder.getChargeModelEvcs());
        }
        xhpcHistoryOrder.setTenantId(xhpcChargeOrder.getTenantId());
        xhpcHistoryOrder.setSource(xhpcChargeOrder.getSource());
        xhpcHistoryOrder.setRateModelId(xhpcChargeOrder.getRateModelId());
        xhpcHistoryOrder.setDelFlag(0);
        xhpcHistoryOrderService.insert(xhpcHistoryOrder);
    }


    @Override
    public void orderCurrent() {
        String time = monthTime();
        xhpcRealTimeOrderMapper.deleteOrderCurrent(time);
    }

    @Override
    public void orderVoltage() {
        String time = monthTime();
        xhpcRealTimeOrderMapper.deleteOrderVoltage(time);
    }

    @Override
    public void orderSoc() {
        String time = monthTime();
        xhpcRealTimeOrderMapper.deleteOrderSoc(time);
    }

    @Override
    public void realTimeOrder() {
        String time = monthTime();
        xhpcRealTimeOrderMapper.deleteRealTimeOrderTime(time);
    }
    @Override
    public void orderRedisRecord() {
        String time = monthTime();
        xhpcRealTimeOrderMapper.deleteOorderRedisRecord(time);
    }
    @Override
    public void realTimeOrderBms() {
        String time = monthTime();
        xhpcRealTimeOrderMapper.deleteRealTimeOrderBms(time);
    }


    @Override
    public void deleteOrderCacheDate() {
        String time = monthTime();

        Collection<String> keys = redisService.keys("Yu80836000*");
        String st1 = DateUtil.format(DateUtil.offsetDay(new Date(),-15), "yyMMdd");
        int order1 =Integer.parseInt(st1);
        for (String order : keys) {
            String st2 = order.substring(18, 24);
            int order2 =Integer.parseInt(st2);
            if(order1>order2){
                redisService.deleteObject(order);
            }
        }
    }


    //获今天之后一个月半后时间
    private String monthTime(){
        Date date = new Date();
        Date beginOfDay = DateUtil.beginOfDay(date);
        return DateUtil.formatDateTime(DateUtil.offsetDay(beginOfDay, -35));
    }

    private BigDecimal getBigDecimal(Long rateModelId, String startTime, String updateTime, BigDecimal powerPriceTotal, BigDecimal divide) {
        if("00:00:00".equals(updateTime)){
            updateTime="23:59:59";
        }
        List<Map<String, Object>> reatTimeList = xhpcHistoryOrderService.getReatTimeList(startTime,updateTime, rateModelId);
        for (int i = 0; i <reatTimeList.size() ; i++) {
            int size = reatTimeList.size();
            Map<String, Object> map = reatTimeList.get(i);
            String startTime1 = map.get("startTime").toString();
            String endTime1 = map.get("endTime").toString();
            BigDecimal powerFee =new BigDecimal(map.get("powerFee").toString());
            if("00:00:00".equals(endTime1)){
                endTime1="23:59:59";
            }
            //获取费率
            if(size==1){
                powerPriceTotal = powerPriceTotal.add(getRateTimeList(startTime,updateTime,divide,powerFee));
            }else{
                if(i==0){
                    powerPriceTotal = powerPriceTotal.add(getRateTimeList(startTime,endTime1,divide,powerFee));
                } else if(i<size-1){
                    powerPriceTotal = powerPriceTotal.add(getRateTimeList(startTime1,endTime1,divide,powerFee));
                }else{
                    powerPriceTotal = powerPriceTotal.add(getRateTimeList(startTime1,updateTime,divide,powerFee));
                }
            }
        }
        return powerPriceTotal;
    }

    private  BigDecimal getRateTimeList(String startTime, String endTime, BigDecimal degree, BigDecimal powerPrice) {
        long time = DateUtil.parse(endTime).getTime();
        long time1= DateUtil.parse(startTime).getTime();
        BigDecimal multiply = new BigDecimal(time-time1).divide(new BigDecimal(60000),4, BigDecimal.ROUND_HALF_UP).multiply(degree).setScale(4,BigDecimal.ROUND_HALF_UP);
        BigDecimal bigDecimal = multiply.multiply(powerPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
        return  bigDecimal;
    }

    private BigDecimal getRealOrderTime(Long chargingOrderId,String startTime,String endTime){
        //结束时间差时间
        int differenceEndTime =0;
        try {
            differenceEndTime = xhpcRealTimeOrderMapper.getDifferenceTime(chargingOrderId, endTime);
        }catch (Exception e){
            //无实时数据
        }
        double endTimeChargingDegree =0.0;
        if(differenceEndTime>0){
            //时间差度数
            double chargingDegreeTime = xhpcRealTimeOrderMapper.getChargingDegreeTime(chargingOrderId, endTime);
            endTimeChargingDegree = differenceEndTime*chargingDegreeTime/15;
        }
        int differenceStartTime=0;
        try {
            differenceStartTime = xhpcRealTimeOrderMapper.getDifferenceTime(chargingOrderId, startTime);
        }catch (Exception e){
            //无实时数据
        }
        //开始时间差度数
        double startTimeChargingDegree =0.0;
        if(differenceStartTime>0){
            //时间差度数
            double chargingDegreeTime = xhpcRealTimeOrderMapper.getChargingDegreeTime(chargingOrderId, startTime);
            startTimeChargingDegree = differenceStartTime*chargingDegreeTime/15;
        }
        double realTimeOrderTime = 0.0;
        try {
            realTimeOrderTime = xhpcRealTimeOrderMapper.getRealTimeOrderTime(chargingOrderId, startTime, endTime);
        }catch (Exception e){
            //无实时数据
        }
        return new BigDecimal(realTimeOrderTime+endTimeChargingDegree-startTimeChargingDegree).setScale(2,BigDecimal.ROUND_HALF_UP);
    }

    //判斷活动时间、电费、服务费、公式是否和场站一致
    private Map<String,Object> getRateOrActivityFormul(String serialNumber,Long internetUserId,Date startTime,Date endTime,Long chargingStationId,String tenantId,Long rateModelId){
        Map<String,Object> map =new HashMap<>();
        List<XhpcActivityInternetDomainDto> activityStationTime = xhpcRealTimeOrderMapper.getActivityStationTime(internetUserId, DateUtil.formatDateTime(startTime), DateUtil.formatDateTime(endTime), chargingStationId, tenantId);
        if(activityStationTime !=null && activityStationTime.size()==1) {
            //活动的时间、电费、服务费、公式
            Integer activityId = activityStationTime.get(0).getActivityId();
            int computeType = activityStationTime.get(0).getComputeType();
            List<XhpcActivityFormulaDomainDto> activityFormulaList = xhpcRealTimeOrderMapper.getActivityFormulaById(activityId);
            //场站的电费和服务费
            List<RateTime> rateTimeList = xhpcRealTimeOrderMapper.getRateTimeList(chargingStationId, rateModelId, null);
            String computeFormula = "";
            if (activityFormulaList != null && rateTimeList != null && activityFormulaList.size() > 0 && activityFormulaList.size() == rateTimeList.size()) {
                for (int i = 0; i < activityFormulaList.size(); i++) {
                    XhpcActivityFormulaDomainDto activit = activityFormulaList.get(i);
                    RateTime rateTime = rateTimeList.get(i);
                    if (activit.getStartTime().equals(rateTime.getStartTime()) && activit.getEndTime().equals(rateTime.getEndTime()) &&
                            activit.getServicePrice().compareTo(rateTime.getServicePrice()) == 0 && activit.getPowerPrice().compareTo(rateTime.getPowerPrice()) == 0) {
                        if (i == 0) {
                            computeFormula = activit.getComputeFormula();
                        } else if (i != activityFormulaList.size() - 1) {
                            if (!computeFormula.equals(activit.getComputeFormula())) {
                                break;
                            }
                        } else {
                            if (!computeFormula.equals(activit.getComputeFormula())) {
                                break;
                            } else {
                                map.put("status","1");
                                map.put("computeFormula",computeFormula);
                                map.put("activityId",activityId);
                                map.put("computeType",computeType);
                                return map;
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
            //查看结算报文是否夸时段
            Map<String, Object> cacheMap = redisService.getCacheMap("order:" + serialNumber);
            if (cacheMap != null) {
                CacheOrderData cacheOrderData = (CacheOrderData) cacheMap.get("orderData");
                if (cacheOrderData != null) {
                    int number = 0;
                    if (cacheOrderData.getT1PowerQuantity() !=null && !"0".equals(cacheOrderData.getT1PowerQuantity().toString())) {
                        number++;
                        rateTimeList = xhpcRealTimeOrderMapper.getRateTimeList(chargingStationId, rateModelId, "00");
                    }
                    if (cacheOrderData.getT2PowerQuantity() !=null &&!"0".equals(cacheOrderData.getT2PowerQuantity().toString())) {
                        number++;
                        rateTimeList = xhpcRealTimeOrderMapper.getRateTimeList(chargingStationId, rateModelId, "01");
                    }
                    if (cacheOrderData.getT3PowerQuantity() !=null && !"0".equals(cacheOrderData.getT3PowerQuantity().toString())) {
                        number++;
                        rateTimeList = xhpcRealTimeOrderMapper.getRateTimeList(chargingStationId, rateModelId, "02");
                    }
                    if (cacheOrderData.getT4PowerQuantity() !=null && !"0".equals(cacheOrderData.getT4PowerQuantity().toString())) {
                        number++;
                        rateTimeList = xhpcRealTimeOrderMapper.getRateTimeList(chargingStationId, rateModelId, "03");
                    }
                    BigDecimal powerPrice = new BigDecimal(0);
                    BigDecimal servicePrice = new BigDecimal(0);
                    if (number == 1) {
                        for (int i = 0; i < rateTimeList.size(); i++) {
                            RateTime rateTime = rateTimeList.get(i);
                            XhpcActivityFormulaDomainDto activity = xhpcRealTimeOrderMapper.getActivityFormulaTimeById(activityStationTime.get(0).getActivityId(), rateTime.getStartTime(), rateTime.getEndTime());
                            if (i == 0) {
                                computeFormula = activity.getComputeFormula();
                                powerPrice = activity.getPowerPrice();
                                servicePrice = activity.getServicePrice();
                                if(rateTimeList.size()==1){
                                    map.put("status","2");
                                    map.put("computeFormula",computeFormula);
                                    map.put("powerPrice",powerPrice);
                                    map.put("servicePrice",servicePrice);
                                    map.put("activityId",activityId);
                                    map.put("computeType",computeType);
                                    return map;
                                }
                            } else if (i != rateTimeList.size() - 1) {
                                if (computeFormula.equals(activity.getComputeFormula())) {
                                    break;
                                }
                                if (powerPrice.compareTo(activity.getPowerPrice()) != 0) {
                                    break;
                                }
                                if (servicePrice.compareTo(activity.getServicePrice()) != 0) {
                                    break;
                                }
                            } else {
                                if (computeFormula.equals(activity.getComputeFormula())) {
                                    break;
                                }
                                if (powerPrice.compareTo(activity.getPowerPrice()) != 0) {
                                    break;
                                }
                                if (servicePrice.compareTo(activity.getServicePrice()) != 0) {
                                    break;
                                }
                                map.put("status","2");
                                map.put("computeFormula",computeFormula);
                                map.put("powerPrice",powerPrice);
                                map.put("servicePrice",servicePrice);
                                map.put("activityId",activityId);
                                map.put("computeType",computeType);
                                return map;
                            }
                        }
                    }
                }

            }
        }
        map.put("status","0");
        return map;
    }

    //发送充电成功订阅消息
    public static void WxMessageSend(String openid,String token,String chargingStationName,String soc,String money,String time){
        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", "a0N2aNLbgMEUKNIujRPuMM14Xw6qsfBZz9w2uVEmjlE");
            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("thing6", map1);

            Map<String, Object> map2 = new LinkedHashMap<>();
            map2.put("value", soc);
            Map<String, Object> map22 = new LinkedHashMap<>();
            map22.put("character_string29", map2);
            map11.putAll(map22);
            Map<String, Object> map3 = new LinkedHashMap<>();
            map3.put("value", money);
            Map<String, Object> map33 = new LinkedHashMap<>();
            map33.put("amount33", map3);
            map11.putAll(map33);



            Map<String, Object> map4 = new LinkedHashMap<>();
            map4.put("value", time);
            Map<String, Object> map44 = new LinkedHashMap<>();
            map44.put("thing8", map4);
            map11.putAll(map44);
            Map<String, Object> map5 = new LinkedHashMap<>();
            map5.put("value", "充电已完成请尽快离场,超时要收占位费哟");
            Map<String, Object> map55 = new LinkedHashMap<>();
            map55.put("thing35", map5);
            map11.putAll(map55);
            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);
            // System.out.println("========101010===========sessionKey:============1010===============");
        }catch (Exception e){

        }
    }
    public static String genOrder(String terminalSerialNumber) {

        Date date = Calendar.getInstance().getTime();
        String format = DateUtil.format(date, "yyMMddHHmmss");
        //自增
        String orderNo = terminalSerialNumber + format ;
        return orderNo;
    }

    //生成历史订单明细集合

    private void installXhpcHistoryOrderChargeDetails(XhpcHistoryOrder horder){

            List<XhpcRateTimeYuDto> xhpcRateTimes = xhpcRealTimeOrderMapper.getReatTimeList(DateUtil.formatTime(horder.getStartTime()), DateUtil.formatTime(horder.getEndTime()), horder.getRateModelId());
        Stack<XhpcHistoryOrderChargeDetails> chargeDetailsStack =new Stack<>();
            Map<String, Object> cacheMap = REDIS.getCacheMap("order:"+ horder.getSerialNumber());
            CacheOrderData cacheOrderData = (CacheOrderData)cacheMap.get("orderData");
            if(cacheOrderData !=null &&cacheOrderData.getT1PowerQuantity()!=null &&cacheOrderData.getT2PowerQuantity()!=null&& cacheOrderData.getT3PowerQuantity()!=null&& cacheOrderData.getT4PowerQuantity()!=null) {

                BigDecimal bigDecimal = new BigDecimal(10000);
                int t1 = 0;
                int t12 = 2;
                int t13 = 3;
                BigDecimal bigDecimal1 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal);
                int t2 = 0;
                int t22 = 2;
                int t23 = 3;
                BigDecimal bigDecimal2 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal);
                int t3 = 0;
                int t32 = 2;
                int t33 = 3;
                BigDecimal bigDecimal3 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal);
                int t4 = 0;
                int t43 = 3;
                int t42 = 2;
                BigDecimal bigDecimal4 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal);


                for (XhpcRateTimeYuDto xpcRateTime : xhpcRateTimes) {
                    String rateValue = xpcRateTime.getRateValue();
                    if ("00".equals(rateValue)) {
                        t1 = t1 + 1;
                    } else if ("01".equals(rateValue)) {
                        t2 = t2 + 1;
                    } else if ("02".equals(rateValue)) {
                        t3 = t3 + 1;
                    } else if ("03".equals(rateValue)) {
                        t4 = t4 + 1;
                    }
                }
                BigDecimal decimalYu = new BigDecimal((horder.getEndTime().getTime() - horder.getStartTime().getTime())).divide(new BigDecimal(60000), 4, BigDecimal.ROUND_HALF_UP);
                BigDecimal divideYu = new BigDecimal(cacheOrderData.getTotalPowerQuantity()).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_UP);
                //每分钟多少度电
                BigDecimal quantity = new BigDecimal(0);
                if (decimalYu.compareTo(new BigDecimal(0)) != 0) {
                    quantity = decimalYu.divide(divideYu, 4, BigDecimal.ROUND_HALF_UP);
                }
                for (XhpcRateTimeYuDto xpcRateTime : xhpcRateTimes) {
                    XhpcHistoryOrderChargeDetails chargeDetails = new XhpcHistoryOrderChargeDetails();
                    String rateValue = xpcRateTime.getRateValue();

                    String rateStartTime = cn.hutool.core.date.DateUtil.format(xpcRateTime.getStartTime(), "HH:mm:ss");

                    String orderStartTime = cn.hutool.core.date.DateUtil.format(horder.getStartTime(), "yyyy-MM-dd HH:mm:ss");

                    rateStartTime = orderStartTime.substring(0, 10) + " " + rateStartTime;

                    String rateEndTime = cn.hutool.core.date.DateUtil.format(xpcRateTime.getEndTime(), "HH:mm:ss");

                    String orderEndTime = cn.hutool.core.date.DateUtil.format(horder.getEndTime(), "yyyy-MM-dd HH:mm:ss");

                    rateEndTime = orderStartTime.substring(0, 10) + " " + rateEndTime;

                    DateTime startTime1 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");

                    DateTime endTime1 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");

                    if ("00".equals(rateValue)) {
                        boolean judgeStart = false;
                        boolean judgeEnd = false;

                        if (horder.getStartTime().getTime() - startTime1.getTime() > 0) {
                            chargeDetails.setDetailStartTime(orderStartTime);
                            judgeStart = true;
                        } else {
                            chargeDetails.setDetailStartTime(rateStartTime);
                        }
                        if (horder.getEndTime().getTime() - endTime1.getTime() > 0) {
                            chargeDetails.setDetailEndTime(rateEndTime);
                        } else {
                            chargeDetails.setDetailEndTime(orderEndTime);
                            judgeEnd = true;
                        }
                        chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                        chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());

                        if (t1 == 1) {
                            BigDecimal divide = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal);

                            BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                            chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                            chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                            chargeDetails.setDetailPower(divide.doubleValue());
                            chargeDetailsStack.push(chargeDetails);
                        } else if (t1 == 2) {

                            if (t12 == 2) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }

                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);

                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));
                                //剩余电量
                                bigDecimal1 = bigDecimal1.subtract(multiply);

                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                            } else {
                                BigDecimal multiply1 = bigDecimal1.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal1.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal1.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t12 = t12 - 1;
                        } else if (t1 == 3) {
                            if (t13 == 3) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));
                                //剩余电量
                                bigDecimal1 = bigDecimal1.subtract(multiply);

                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            } else if (t13 == 2) {

                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal1 = bigDecimal1.subtract(multiply);
                            } else {
                                BigDecimal multiply1 = bigDecimal1.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal1.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal1.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t13 = t13 - 1;
                        }

                    } else if ("01".equals(rateValue)) {
                        boolean judgeStart = false;
                        boolean judgeEnd = false;

                        if (horder.getStartTime().getTime() - startTime1.getTime() > 0) {
                            chargeDetails.setDetailStartTime(orderStartTime);
                            judgeStart = true;
                        } else {
                            chargeDetails.setDetailStartTime(rateStartTime);
                        }
                        if (horder.getEndTime().getTime() - endTime1.getTime() > 0) {
                            chargeDetails.setDetailEndTime(rateEndTime);
                        } else {
                            chargeDetails.setDetailEndTime(orderEndTime);
                            judgeEnd = true;
                        }
                        chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                        chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());

                        if (t2 == 1) {
                            BigDecimal divide = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal);

                            BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                            chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                            chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                            chargeDetails.setDetailPower(divide.doubleValue());
                            chargeDetailsStack.push(chargeDetails);
                        } else if (t2 == 2) {

                            if (t22 == 2) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }

                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);

                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal2 = bigDecimal2.subtract(multiply);

                            } else {
                                BigDecimal multiply1 = bigDecimal2.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal2.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal2.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t22 = t22 - 1;
                        } else if (t2 == 3) {
                            if (t23 == 3) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));

                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal2 = bigDecimal2.subtract(multiply);
                            } else if (t23 == 2) {

                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal2 = bigDecimal2.subtract(multiply);
                            } else {
                                BigDecimal multiply1 = bigDecimal2.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal2.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal2.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t23 = t23 - 1;
                        }

                    } else if ("02".equals(rateValue)) {
                        boolean judgeStart = false;
                        boolean judgeEnd = false;

                        if (horder.getStartTime().getTime() - startTime1.getTime() > 0) {
                            chargeDetails.setDetailStartTime(orderStartTime);
                            judgeStart = true;
                        } else {
                            chargeDetails.setDetailStartTime(rateStartTime);
                        }
                        if (horder.getEndTime().getTime() - endTime1.getTime() > 0) {
                            chargeDetails.setDetailEndTime(rateEndTime);
                        } else {
                            chargeDetails.setDetailEndTime(orderEndTime);
                            judgeEnd = true;
                        }
                        chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                        chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());

                        if (t3 == 1) {
                            BigDecimal divide = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal);

                            BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                            chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                            chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                            chargeDetails.setDetailPower(divide.doubleValue());
                            chargeDetailsStack.push(chargeDetails);
                        } else if (t3 == 2) {

                            if (t32 == 2) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }

                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);

                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal3 = bigDecimal3.subtract(multiply);

                            } else {
                                BigDecimal multiply1 = bigDecimal3.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal3.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal3.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t32 = t32 - 1;
                        } else if (t3 == 3) {
                            if (t33 == 3) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));

                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal3 = bigDecimal3.subtract(multiply);
                            } else if (t33 == 2) {

                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal3 = bigDecimal3.subtract(multiply);
                            } else {
                                BigDecimal multiply1 = bigDecimal3.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal3.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal3.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t33 = t33 - 1;
                        }

                    } else if ("03".equals(rateValue)) {
                        boolean judgeStart = false;
                        boolean judgeEnd = false;

                        if (horder.getStartTime().getTime() - startTime1.getTime() > 0) {
                            chargeDetails.setDetailStartTime(orderStartTime);
                            judgeStart = true;
                        } else {
                            chargeDetails.setDetailStartTime(rateStartTime);
                        }
                        if (horder.getEndTime().getTime() - endTime1.getTime() > 0) {
                            chargeDetails.setDetailEndTime(rateEndTime);
                        } else {
                            chargeDetails.setDetailEndTime(orderEndTime);
                            judgeEnd = true;
                        }
                        chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                        chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());

                        if (t4 == 1) {
                            BigDecimal divide = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal);

                            BigDecimal multiply1 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal multiply2 = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                            chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                            chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                            chargeDetails.setDetailPower(divide.doubleValue());
                            chargeDetailsStack.push(chargeDetails);
                        } else if (t4 == 2) {

                            if (t42 == 2) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }

                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);

                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal4 = bigDecimal4.subtract(multiply);

                            } else {
                                BigDecimal multiply1 = bigDecimal4.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal4.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal4.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t42 = t42 - 1;
                        } else if (t4 == 3) {
                            if (t43 == 3) {
                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));

                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal4 = bigDecimal4.subtract(multiply);
                            } else if (t43 == 2) {

                                if (judgeStart) {
                                    rateStartTime = orderStartTime;
                                }
                                if (judgeEnd) {
                                    rateEndTime = orderEndTime;
                                }
                                DateTime parse2 = cn.hutool.core.date.DateUtil.parse(rateStartTime, "yyyy-MM-dd HH:mm:ss");
                                DateTime parse3 = cn.hutool.core.date.DateUtil.parse(rateEndTime, "yyyy-MM-dd HH:mm:ss");
                                long betweenDay4 = cn.hutool.core.date.DateUtil.between(parse3, parse2, DateUnit.MINUTE);
                                //获得电量
                                BigDecimal multiply = quantity.multiply(new BigDecimal(betweenDay4));


                                BigDecimal multiply1 = multiply.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = multiply.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(multiply.doubleValue());
                                chargeDetailsStack.push(chargeDetails);

                                //剩余电量
                                bigDecimal4 = bigDecimal4.subtract(multiply);
                            } else {
                                BigDecimal multiply1 = bigDecimal4.multiply(xpcRateTime.getPowerFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal multiply2 = bigDecimal4.multiply(xpcRateTime.getServiceFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

                                chargeDetails.setElecPrice(xpcRateTime.getPowerFee().doubleValue());
                                chargeDetails.setSevicePrice(xpcRateTime.getServiceFee().doubleValue());
                                chargeDetails.setDetailElecMoney(multiply1.doubleValue());
                                chargeDetails.setDetailSeviceMoney(multiply2.doubleValue());
                                chargeDetails.setDetailPower(bigDecimal4.doubleValue());
                                chargeDetailsStack.push(chargeDetails);
                            }
                            t43 = t43 - 1;
                        }
                    }
                }

                //写入数据库
                for (int i = 0; i < chargeDetailsStack.size(); i++) {

                    XhpcHistoryOrderChargeDetails xhpcHistoryOrderChargeDetails = chargeDetailsStack.get(i);
                    xhpcHistoryOrderChargeDetails.setHistoryOrdersId(horder.getHistoryOrderId());
                    xhpcHistoryOrderChargeDetails.setStartTime(DateUtil.format(horder.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                    xhpcHistoryOrderChargeDetails.setEndTime(DateUtil.format(horder.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                    xhpcHistoryOrderChargeDetails.setTotalPower(horder.getTotalPower());
                    xhpcHistoryOrderChargeDetails.setTotalElecMoney(horder.getPowerPriceTotal().doubleValue());
                    xhpcHistoryOrderChargeDetails.setTotalSeviceMoney(horder.getServicePriceTotal().doubleValue());
                    xhpcHistoryOrderChargeDetails.setTotalMoney(horder.getTotalPrice().doubleValue());
                    xhpcRealTimeOrderMapper.insertXhpcHistoryOrderChargeDetails(xhpcHistoryOrderChargeDetails);
                }
            }


    }



    public static void main(String[] args) {
        // WxMessageSend("ot6ul4nlSC5ZZOC4rTLS5hedFTGk","69_G2hFrelhCsfOPuFB6OPP5I8j_DKdP-N6QF-shvpUFT2mQ-KjonSxbS_mrP5P9nYyat9OsJLZAcbYA4g5rWdn0i6whxueiU3hWfguoeqSnick1zAGvu7SKa50_VkKPAcAGABGR","黄金东二路","80","76.6");

//        String st ="小华充电润茂酒店用品城汽车充电站1";
//        String str = st.replace("小华充电", "").substring(0,13);
//        System.out.println(str);

        String createTime="2024-07-03 22:57:12";
        DateTime parse = DateUtil.parse(createTime, "yyyy-MM-dd HH:mm:ss");
        DateTime dateTime = DateUtil.offset(parse, DateField.MILLISECOND,10000);
        String format = DateUtil.format(dateTime, "yyyy-MM-dd HH:mm:ss");
        System.out.println("format====:"+format);



        String formatYu = DateUtil.format(DateUtil.offsetDay(new Date(),-15), "yyMMdd");

        System.out.println("formatYu====:"+formatYu);


        String st ="Yu80836000010002012512220705512852";

        System.out.println("formatYu====:"+st.substring(18,24));

    }


}
