huliguo
2 天以前 8115295a64e0809246897fefb8c45de06dce0799
ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java
@@ -1,36 +1,46 @@
package com.ruoyi.order.controller;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.text.DecimalFormat;
import java.time.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.account.api.feignClient.AppUserCarClient;
import com.ruoyi.account.api.feignClient.AppUserClient;
import com.ruoyi.account.api.model.TAppUserCar;
import com.ruoyi.chargingPile.api.domain.SiteMenu;
import com.ruoyi.chargingPile.api.dto.GetSiteListDTO;
import com.ruoyi.chargingPile.api.feignClient.ChargingGunClient;
import com.ruoyi.chargingPile.api.feignClient.ChargingPileClient;
import com.ruoyi.chargingPile.api.feignClient.ParkingLotClient;
import com.ruoyi.chargingPile.api.feignClient.SiteClient;
import com.ruoyi.chargingPile.api.feignClient.*;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.chargingPile.api.model.TChargingGun;
import com.ruoyi.chargingPile.api.model.TChargingPile;
import com.ruoyi.chargingPile.api.model.TParkingRecord;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.dto.ChargingOrderGroup;
import com.ruoyi.common.core.dto.ChargingPercentProvinceDto;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.BasePojo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.log.enums.OperatorType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.Logical;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.integration.api.model.PageChargingOrderAndUploadRealTimeMonitoringDataDto;
import com.ruoyi.integration.api.model.UploadRealTimeMonitoringData;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.integration.api.feignClient.UploadRealTimeMonitoringDataClient;
import com.ruoyi.integration.api.model.ChargingOrderAndUploadRealTimeMonitoringDataDto;
import com.ruoyi.integration.api.model.UploadRealTimeMonitoringPageData;
import com.ruoyi.order.api.dto.ChargingStatisticeDTO;
import com.ruoyi.order.api.model.*;
import com.ruoyi.order.api.query.ChargingOrderQuery;
import com.ruoyi.common.core.dto.MongoChargingOrderQuery;
@@ -49,23 +59,27 @@
import com.ruoyi.order.service.*;
import com.ruoyi.order.util.PreviousSixMonths;
import com.ruoyi.order.vo.EndOfChargePageInfo;
import com.ruoyi.order.vo.StatisticsOfBatteryVO;
import com.ruoyi.order.vo.WatchChargingOrderVo;
import com.ruoyi.other.api.feignClient.RoleSiteClient;
import com.ruoyi.other.api.feignClient.UserSiteClient;
import com.ruoyi.payment.api.feignClient.AliPaymentClient;
import com.ruoyi.payment.api.feignClient.WxPaymentClient;
import com.ruoyi.payment.api.vo.AliQueryOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysUserClient;
import com.ruoyi.system.api.feignClient.SysUserRoleClient;
import com.ruoyi.system.api.model.SysUserRoleVo;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
@@ -94,7 +108,8 @@
    private TokenService tokenService;
    @Autowired
    private TOrderEvaluateService orderEvaluateService;
    @Autowired
    private TGrantVipService tGrantVipService;
    @Resource
    private WxPaymentClient wxPaymentClient;
    
@@ -134,7 +149,49 @@
    
    @Resource
    private TOrderInvoiceService invoiceService;
    @Resource
    private UploadRealTimeMonitoringDataClient uploadRealTimeMonitoringDataClient;
    @Resource
    private PartnerClient partnerClient;
    @Resource
    private SysUserClient sysUserClient;
    @Resource
    private UserSiteClient userSiteClient;
    @Resource
    private RoleSiteClient roleSiteClient;
    @Resource
    private SysUserRoleClient sysUserRoleClient;
    /**
     * 远程调用 监管平台查询前一天用能统计
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/getChargingStatistics")
    public R<List<TChargingOrder>> getChargingStatistics(@RequestBody ChargingStatisticeDTO dto) {
        List<Long> collect = chargingOrderAccountingStrategyService.lambdaQuery().between(TChargingOrderAccountingStrategy::getCreateTime, dto.getStartTime(), dto.getEndTime())
                .list().stream().map(TChargingOrderAccountingStrategy::getChargingOrderId).collect(Collectors.toList());
        if (!collect.isEmpty()){
            List<TChargingOrder> list = chargingOrderService.lambdaQuery()
                    .in(TChargingOrder::getId,collect).list();
            return R.ok(list);
        }
        return R.ok(new ArrayList<TChargingOrder>());
    }
    /**
     * 远程调用 增加管理后台赠送会员记录
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/management/give/vip")
    public R managementGiveVip(@RequestBody TGrantVip grantVip) {
        return R.ok(tGrantVipService.save(grantVip));
    }
    /**
     * 远程调用根据枪id 查询最新的订单id 用户后台结束充电
@@ -157,19 +214,99 @@
        }
        return R.ok();
    }
    @RequiresPermissions(value = {"/invoiceManagement/select_order", "/paymentOrder/order"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/pay/order/list")
    @ApiOperation(value = "列表", tags = {"管理后台-支付订单-订单信息"})
    public R<PageInfo<PayOrderDto>> payOrderList(@RequestBody PayOrderQueryDto payOrderQueryDto) {
        return chargingOrderService.payOrderQuery(payOrderQueryDto);
        Integer pageCurr = payOrderQueryDto.getPageCurr();
        Integer pageSize = payOrderQueryDto.getPageSize();
        payOrderQueryDto.setPageCurr(1);
        payOrderQueryDto.setPageSize(10000999);
        PageInfo<PayOrderDto> data = chargingOrderService.payOrderQuery(payOrderQueryDto).getData();
        List<PayOrderDto> res = new ArrayList<>();
        // 查询当前登陆人按钮权限
        SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
        Integer roleType = sysUser.getRoleType();
        Long userId = tokenService.getLoginUser().getUserid();
        //如果没传siteId,获取当前登陆人所有的siteIds
        List<Integer> siteIds = new ArrayList<>();
        if (userId != null){
            List<GetSiteListDTO> data2 = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data2) {
                siteIds.add(datum.getId());
            }
        }
        if (siteIds.isEmpty()){
            siteIds.add(-1);
        }
        List<TChargingOrder> list = chargingOrderService.list();
        List<TParkingRecord> parkingRecord = parkingLotClient.getSiteIdAll().getData();
        for (PayOrderDto record : data.getRecords()) {
            if (record.getType() == 1){
                TChargingOrder chargingOrder = list.stream().filter(e -> e.getId().equals(Long.valueOf(record.getId()))).findFirst().orElse(null);
                if (chargingOrder!=null){
                    record.setSiteId(chargingOrder.getSiteId());
                }
            }
            if (record.getType()==4){
                TParkingRecord tParkingRecord = parkingRecord.stream().filter(e -> e.getId().equals(Long.valueOf(record.getId()))).findFirst().orElse(null);
                if (tParkingRecord!=null){
                    record.setSiteId(tParkingRecord.getSiteId());
                }
            }
            if (roleType==1||(record.getType()!=1&&record.getType()!=4)){
                res.add(record);
                continue;
            }
            if (roleType==2 && (record.getType()==1||record.getType()==4) && siteIds.contains(record.getSiteId())){
                res.add(record);
            }
        }
        List<PayOrderDto> res1 = testing5(res.size(), pageCurr, pageSize, res);
        data.setTotal(res.size());
        data.setRecords(res1);
        return R.ok(data);
    }
    public static List<PayOrderDto> testing5(long total, long current, long size, List<PayOrderDto> str){
    List<PayOrderDto> result = new ArrayList<>();
    //获取初始化分页结构
    com.ruoyi.order.util.Page<PayOrderDto> page = new com.ruoyi.order.util.Page().getPage(total, size, current - 1);
    //获取集合下标初始值
    long startIndex = page.getStartIndex();
    //获取集合下标结束值
    long endInddex = 0;
    if(startIndex + page.getCurrent() >= total || size > total){
        endInddex = total;
    }else {
        endInddex = Math.min(startIndex + page.getSize(), total);
    }
    //如果输入的开始查询下标大于集合大小,则查询为空值
    if(startIndex > total){
        result = Collections.emptyList();
    }else{
        result = str.subList((int)startIndex,(int)endInddex);
    }
    return result;
}
    @ResponseBody
    @PostMapping(value = "/pay/order/refund")
    @ApiOperation(value = "退款", tags = {"管理后台-支付订单-订单信息"})
    public R refund(@RequestBody PayOrderRefundDto payOrderQueryDto) {
        return chargingOrderService.payRefund(payOrderQueryDto);
    }
    @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/pay/order/pay/detail")
    @ApiOperation(value = "支付信息", tags = {"管理后台-支付订单-订单信息"})
@@ -183,8 +320,10 @@
                payOrderInfoDto.setTradeNo(byId.getRechargeSerialNumber());
                payOrderInfoDto.setPayType(byId.getRechargePaymentType());
                payOrderInfoDto.setPayAmount(byId.getPaymentAmount());
                payOrderInfoDto.setPayTime(byId.getPayTime());
                payOrderInfoDto.setPayTime(byId.getCreateTime());
                payOrderInfoDto.setRefundAmount(byId.getRefundAmount());
                payOrderInfoDto.setRechargeAmount(byId.getRechargeAmount());
                payOrderInfoDto.setFinalAmount(byId.getRechargeAmount().subtract(byId.getRefundAmount()));
                return R.ok(payOrderInfoDto);
            case 2:
                TShoppingOrder byId1 = shoppingOrderService.getById(orderId);
@@ -194,8 +333,10 @@
                payOrderInfoDto1.setTradeNo(byId1.getSerialNumber());
                payOrderInfoDto1.setPayType(byId1.getPaymentType());
                payOrderInfoDto1.setPayAmount(byId1.getPaymentAmount());
                payOrderInfoDto1.setPayTime(byId1.getPayTime());
                payOrderInfoDto1.setPayTime(byId1.getCreateTime());
                payOrderInfoDto1.setRefundAmount(byId1.getRefundAmount());
                payOrderInfoDto1.setRechargeAmount(byId1.getPaymentAmount());
                payOrderInfoDto1.setFinalAmount(byId1.getPaymentAmount().subtract(byId1.getRefundAmount()));
                return R.ok(payOrderInfoDto1);
            case 3:
                TVipOrder byId2 = vipOrderService.getById(orderId);
@@ -205,21 +346,21 @@
                payOrderInfoDto2.setTradeNo(byId2.getSerialNumber());
                payOrderInfoDto2.setPayType(byId2.getPaymentType());
                payOrderInfoDto2.setPayAmount(byId2.getPaymentAmount());
                payOrderInfoDto2.setPayTime(byId2.getPayTime());
                payOrderInfoDto2.setPayTime(byId2.getCreateTime());
                payOrderInfoDto2.setRefundAmount(byId2.getRefundAmount());
                payOrderInfoDto2.setRechargeAmount(byId2.getPaymentAmount());
                payOrderInfoDto2.setFinalAmount(byId2.getPaymentAmount().subtract(byId2.getRefundAmount()));
                return R.ok(payOrderInfoDto2);
            //todo luo 停车场订单
//                case 4:
//                    TParkingRecord byId3 = parkingLotClient.getRecordById(orderId).getData();
//                    PayOrderInfoDto payOrderInfoDto3 = new PayOrderInfoDto();
//                    payOrderInfoDto3.setOrderId(byId3.getId().toString());
//                    payOrderInfoDto3.setCode(byId3.getCode());
//                    payOrderInfoDto3.setTradeNo(byId3);
//                    payOrderInfoDto3.setPayType(0);
//                    payOrderInfoDto3.setPayAmount(new BigDecimal("0"));
//                    payOrderInfoDto3.setPayTime(LocalDateTime.now());
//                    payOrderInfoDto3.setRefundAmount(new BigDecimal("0"));
                case 4:
                    R<TParkingRecord> recordById = parkingLotClient.getRecordById(orderId);
                    TParkingRecord byId3 =recordById.getData();
                    PayOrderInfoDto payOrderInfoDto3 = new PayOrderInfoDto();
                    payOrderInfoDto3.setOrderId(byId3.getId().toString());
                    payOrderInfoDto3.setCode(byId3.getCode());
                    payOrderInfoDto3.setPayTime(byId3.getCreateTime());
                    payOrderInfoDto3.setRechargeAmount(byId3.getPayment());
                    return R.ok(payOrderInfoDto3);
@@ -227,6 +368,10 @@
        return R.ok();
    }
    @ResponseBody
    @GetMapping(value = "/pay/order/refund/detail")
    @ApiOperation(value = "退款信息", tags = {"管理后台-支付订单-订单信息"})
@@ -250,7 +395,7 @@
    @ResponseBody
    @GetMapping(value = "/pay/order/charging")
    @ApiOperation(value = "充电信息", tags = {"管理后台-支付订单-订单信息"})
    public R refundDetail(Long orderId) {
    public R<PayOrderChargingInfo> refundDetail(Long orderId) {
        PayOrderChargingInfo payOrderChargingInfo = new PayOrderChargingInfo();
        TChargingOrder byId = chargingOrderService.getById(orderId);
        List<Site> data = siteClient.getSiteByIds(Collections.singletonList(byId.getSiteId())).getData();
@@ -262,27 +407,151 @@
        if (byId.getAppUserCarId()!=null) {
            List<TAppUserCar> data3 = appUserCarClient.getCarByIds(Collections.singletonList(byId.getAppUserCarId())).getData();
            payOrderChargingInfo.setCarNum(data3.get(0).getLicensePlate());
        }else{
            payOrderChargingInfo.setCarNum(byId.getPlateNum());
        }
        return R.ok();
        payOrderChargingInfo.setTChargingOrder(byId);
        Long count = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, orderId).count();
        payOrderChargingInfo.setPeriodCount(count);
        if (byId.getAppUserCarId()!=null) {
            List<Long> carid = new ArrayList<>();
            carid.add(byId.getAppUserCarId());
            R<List<TAppUserCar>> carByIds = appUserCarClient.getCarByIds(carid);
            payOrderChargingInfo.setCarNum(carByIds.getData().get(0).getLicensePlate());
        }else{
            payOrderChargingInfo.setCarNum(byId.getPlateNum());
        }
        payOrderChargingInfo.setStartTime(byId.getStartTime());
        payOrderChargingInfo.setEndTime(byId.getEndTime());
        payOrderChargingInfo.setTimeCount(payOrderChargingInfo.calculateDuration());
        return R.ok(payOrderChargingInfo);
    }
    @ResponseBody
    @GetMapping(value = "/pay/order/charging/details")
    @ApiOperation(value = "充电明细", tags = {"管理后台-支付订单-订单信息"})
    public R<List<TChargingOrderAccountingStrategy>> chargingDetail(Long orderId) {
        List<TChargingOrderAccountingStrategy> list = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, orderId).orderByDesc(TChargingOrderAccountingStrategy::getStartTime).list();
        TChargingOrder chargingOrder = chargingOrderService.getById(orderId);
        List<TChargingOrderAccountingStrategy> list = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, orderId)
                .orderByDesc(TChargingOrderAccountingStrategy::getStartTime).list();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (TChargingOrderAccountingStrategy tChargingOrderAccountingStrategy : list) {
            LocalDateTime createTime = chargingOrder.getStartTime();
            String format = createTime.format(formatter);
            String startTime = tChargingOrderAccountingStrategy.getStartTime();
            if("00:00".equals(startTime)){
                createTime = createTime.plusDays(1);
                format = createTime.format(formatter);
            }
            tChargingOrderAccountingStrategy.setStartTime(format+" "+tChargingOrderAccountingStrategy.getStartTime());
            tChargingOrderAccountingStrategy.setEndTime(format+" "+tChargingOrderAccountingStrategy.getEndTime());
        }
        //从新排序
        list.sort(new Comparator<TChargingOrderAccountingStrategy>() {
            @Override
            public int compare(TChargingOrderAccountingStrategy o1, TChargingOrderAccountingStrategy o2) {
                String startTime = o1.getStartTime();
                String startTime1 = o2.getStartTime();
                LocalDateTime localDateTime = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                LocalDateTime localDateTime1 = LocalDateTime.parse(startTime1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                if(localDateTime.isBefore(localDateTime1)){
                    return -1;
                }
                if(localDateTime.isAfter(localDateTime1)){
                    return 1;
                }
                return 0;
            }
        });
        return R.ok(list);
    }
    @RequiresPermissions(value = {"/paymentOrder/refund"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/pay/order/refund/list")
    @ApiOperation(value = "列表", tags = {"管理后台-支付订单-退款订单"})
    public R<PageInfo<TChargingOrderRefund>> refundList(@RequestBody ChargingRefundDto chargingRefundDto) {
        return chargingOrderService.getRefundList(chargingRefundDto);
        Integer pageCurr = chargingRefundDto.getPageCurr();
        Integer pageSize = chargingRefundDto.getPageSize();
//        R<PageInfo<TChargingOrderRefund>> refundList = chargingOrderService.getRefundList(chargingRefundDto);
        chargingRefundDto.setPageCurr(1);
        chargingRefundDto.setPageSize(199999999);
        R<PageInfo<TChargingOrderRefund>> refundList1 = chargingOrderService.getRefundList(chargingRefundDto);
        Long userId = tokenService.getLoginUser().getUserid();
        //如果没传siteId,获取当前登陆人所有的siteIds
        List<Integer> siteIds = new ArrayList<>();
            if (userId != null){
                List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
                for (GetSiteListDTO datum : data) {
                    siteIds.add(datum.getId());
                }
            }
        if (siteIds.isEmpty()){
            siteIds.add(-1);
        }
        // 查询当前登陆人按钮权限
        SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
        Integer roleType = sysUser.getRoleType();
        List<TChargingOrderRefund> tChargingOrderRefunds = new ArrayList<>();
        for (TChargingOrderRefund record : refundList1.getData().getRecords()) {
            if (roleType==1){
                tChargingOrderRefunds.add(record);
                continue;
            }
            if (record.getType()!=1){
                tChargingOrderRefunds.add(record);
            }
            TChargingOrder byId = chargingOrderService.getById(record.getOrderId());
            record.setUid(record.getId().toString());
            if (byId==null){
                continue;
            }
            if (roleType==2&&siteIds.contains(byId.getSiteId())){
                tChargingOrderRefunds.add(record);
            }
        }
        PageInfo<TChargingOrderRefund> data = refundList1.getData();
        List<TChargingOrderRefund> res1 = testing4(tChargingOrderRefunds.size(), pageCurr, pageSize, tChargingOrderRefunds);
        data.setTotal(tChargingOrderRefunds.size());
        data.setRecords(res1);
        return refundList1;
    }
    public static List<TChargingOrderRefund> testing4(long total, long current, long size, List<TChargingOrderRefund> str){
        List<TChargingOrderRefund> result = new ArrayList<>();
        //获取初始化分页结构
        com.ruoyi.order.util.Page<TChargingOrderRefund> page = new com.ruoyi.order.util.Page().getPage(total, size, current - 1);
        //获取集合下标初始值
        long startIndex = page.getStartIndex();
        //获取集合下标结束值
        long endInddex = 0;
        if(startIndex + page.getCurrent() >= total || size > total){
            endInddex = total;
        }else {
            endInddex = Math.min(startIndex + page.getSize(), total);
        }
        //如果输入的开始查询下标大于集合大小,则查询为空值
        if(startIndex > total){
            result = Collections.emptyList();
        }else{
            result = str.subList((int)startIndex,(int)endInddex);
        }
        return result;
    }
    @ResponseBody
    @PostMapping(value = "/pay/order/refund/list1")
    @ApiOperation(value = "列表1", tags = {"管理后台-支付订单-退款订单"})
@@ -290,12 +559,13 @@
        return chargingOrderService.getRefundList(chargingRefundDto);
    }
    @RequiresPermissions(value = {"/chargingPileOrder"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/chargingOrder")
    @ApiOperation(value = "充电桩订单列表", tags = {"管理后台-订单管理"})
@@ -306,24 +576,78 @@
        return AjaxResult.success(res);
    }
    @RequiresPermissions(value = {"/chargingPileOrder/monitoring_record"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/chargingOrderInfo")
    @GetMapping(value = "/chargingOrderInfo")
    @ApiOperation(value = "充电桩订单列表查看详情", tags = {"管理后台-订单管理"})
    public AjaxResult<ChargingOrderInfoVO> chargingOrderInfo(String orderId) {
    public AjaxResult<ChargingOrderInfoVO> chargingOrderInfo(String strategyId) {
        TChargingOrder byId = chargingOrderService.getById(strategyId);
        ChargingOrderInfoVO chargingOrderInfoVO = new ChargingOrderInfoVO();
        chargingOrderInfoVO.setCdElectronic("");
        chargingOrderInfoVO.setCdVoltage("");
        chargingOrderInfoVO.setSurplus("");
        chargingOrderInfoVO.setTotalPower("");
        chargingOrderInfoVO.setLicensePlate("");
        chargingOrderInfoVO.setVehicleBrand("");
        chargingOrderInfoVO.setVehicleModel("");
        chargingOrderInfoVO.setVehicleUse("");
        List<TChargingOrderAccountingStrategy> tChargingOrderAccountingStrategies = new ArrayList<>();
        chargingOrderInfoVO.setList(tChargingOrderAccountingStrategies);
        chargingOrderInfoVO.setCdElectronic(byId.getCurrent()!=null?byId.getCurrent().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        chargingOrderInfoVO.setCdVoltage(byId.getVoltage()!=null?byId.getVoltage().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        chargingOrderInfoVO.setSurplus(byId.getTotalElectricity()!=null?byId.getTotalElectricity().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        chargingOrderInfoVO.setTotalPower(byId.getPower()!=null?byId.getPower().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        if (byId.getAppUserCarId()!=null){
            TAppUserCar data = appUserCarClient.getCarById(byId.getAppUserCarId()+"").getData();
            if (data!=null){
                chargingOrderInfoVO.setLicensePlate(data.getLicensePlate());
                chargingOrderInfoVO.setVehicleBrand(data.getVehicleBrand());
                chargingOrderInfoVO.setVehicleModel(data.getVehicleModel());
                chargingOrderInfoVO.setVehicleUse(data.getVehicleUse());
            }
        }else{
            chargingOrderInfoVO.setLicensePlate(byId.getPlateNum());
        }
        // 时段总服务费
        List<TChargingOrderAccountingStrategy> list = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, strategyId).orderByDesc(TChargingOrderAccountingStrategy::getStartTime).list();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (TChargingOrderAccountingStrategy tChargingOrderAccountingStrategy : list) {
            LocalDateTime createTime = byId.getStartTime();
            String format = createTime.format(formatter);
            String startTime = tChargingOrderAccountingStrategy.getStartTime();
            if("00:00".equals(startTime)){
                createTime = createTime.plusDays(1);
                format = createTime.format(formatter);
            }
            tChargingOrderAccountingStrategy.setStartTime(format+" "+tChargingOrderAccountingStrategy.getStartTime());
            tChargingOrderAccountingStrategy.setEndTime(format+" "+tChargingOrderAccountingStrategy.getEndTime());
            if (byId.getVipDiscountAmount()!=null && byId.getServiceCharge().compareTo(BigDecimal.ZERO) != 0){
                BigDecimal multiply = byId.getVipDiscountAmount().divide(byId.getServiceCharge(), 2)
                        .multiply(tChargingOrderAccountingStrategy.getPeriodOriginalServicePrice());
                tChargingOrderAccountingStrategy.setVipDiscount(multiply);
            }
            if (byId.getCouponDiscountAmount()!=null && byId.getServiceCharge().compareTo(BigDecimal.ZERO) != 0){
                BigDecimal multiply = byId.getCouponDiscountAmount().divide(byId.getServiceCharge(), 2)
                        .multiply(tChargingOrderAccountingStrategy.getPeriodOriginalServicePrice());
                tChargingOrderAccountingStrategy.setCouponDiscount(multiply);
            }
        }
        //从新排序
        list.sort(new Comparator<TChargingOrderAccountingStrategy>() {
            @Override
            public int compare(TChargingOrderAccountingStrategy o1, TChargingOrderAccountingStrategy o2) {
                String startTime = o1.getStartTime();
                String startTime1 = o2.getStartTime();
                LocalDateTime localDateTime = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                LocalDateTime localDateTime1 = LocalDateTime.parse(startTime1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                if(localDateTime.isBefore(localDateTime1)){
                    return -1;
                }
                if(localDateTime.isAfter(localDateTime1)){
                    return 1;
                }
                return 0;
            }
        });
        chargingOrderInfoVO.setList(list);
        return AjaxResult.success(chargingOrderInfoVO);
    }
    @Log(title = "【扫一扫】添加评价", businessType = BusinessType.INSERT,operatorType = OperatorType.MOBILE)
    @ResponseBody
    @PostMapping(value = "/addEvaluate")
    @ApiOperation(value = "添加评价", tags = {"小程序-扫一扫"})
@@ -332,6 +656,9 @@
        orderEvaluateService.addOrderEvaluate(dto);
        return AjaxResult.success();
    }
    /**
     * 查询用户最近一次充电记录使用的车辆
     *
@@ -351,6 +678,9 @@
            return R.ok(-1L);
        }
    }
    /**
     * 查询会员在本月有多少次享受了充电折扣
@@ -365,6 +695,8 @@
                .between(TChargingOrder::getStartTime, req.getStartTime(), req.getEndTime())).size();
        return R.ok(size);
    }
    //用户订单数量
    @PostMapping(value = "/useOrderCount")
    public R<Long> useOrderCount(@RequestParam("userId") Long userId) {
@@ -373,11 +705,15 @@
        return R.ok(count);
    }
    //订单详情
    @PostMapping(value = "/detail")
    public R<TChargingOrder> detail(@RequestParam("orderId") Long orderId) {
        return R.ok(chargingOrderService.getById(orderId));
    }
    @PostMapping(value = "/getList")
    public R<List<TChargingOrder>> getList(@RequestParam("siteId") Integer siteId) {
@@ -386,12 +722,35 @@
        return R.ok(list);
    }
    @PostMapping(value = "/getBySiteIdAndTime")
    public R<List<ChargingOrderGroup>> getBySiteIdAndTime(@RequestBody ChargingPercentProvinceDto chargingPercentProvinceDto) {
        List<ChargingOrderGroup> groups = chargingOrderService.chargingOrderGroup(chargingPercentProvinceDto);
        return R.ok(groups);
    }
    /**
     * 根据站点id和时间区间查询订单数据
     * @param chargingPercentProvinceDto
     * @return
     */
    @PostMapping(value = "/getOrderBySiteIdAndTime")
    public R<List<TChargingOrder>> getOrderBySiteIdAndTime(@RequestBody ChargingPercentProvinceDto chargingPercentProvinceDto){
        LocalDate date1 = chargingPercentProvinceDto.getDate1();
        LocalDate date2 = chargingPercentProvinceDto.getDate2();
        String tripartitePlatformName = chargingPercentProvinceDto.getTripartitePlatformName();
        List<TChargingOrder> list = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>().in(TChargingOrder::getSiteId, chargingPercentProvinceDto.getSiteIds())
                .between(null != date1 && null != date2, TChargingOrder::getPayTime, date1.atTime(0, 0, 0), date2.atTime(23, 59, 59))
                .eq(TChargingOrder::getDelFlag, 0).eq(TChargingOrder::getStatus, 5)
                .eq(StringUtils.isNotEmpty(tripartitePlatformName), TChargingOrder::getOrderSource, 2)
                .eq(StringUtils.isNotEmpty(tripartitePlatformName), TChargingOrder::getTripartitePlatformName, tripartitePlatformName));
        return R.ok(list);
    }
    /**
     * 根据充电枪id获取正在进行中的订单
@@ -421,6 +780,11 @@
    @GetMapping(value = "/getMyChargingOrderInfo")
    @ApiOperation(value = "获取充电记订单明细", tags = {"小程序-充电记录"})
    public AjaxResult<MyChargingOrderInfo> getMyChargingOrderInfo(String id) {
        TChargingOrder tChargingOrder = chargingOrderService.getById(id);
        Long userId = tokenService.getLoginUserApplet().getUserId();
        if(!tChargingOrder.getAppUserId().equals(userId)){
            return AjaxResult.error("权限不足");
        }
        MyChargingOrderInfo myChargingOrderInfo = chargingOrderService.getMyChargingOrderInfo(id);
        return AjaxResult.success(myChargingOrderInfo);
    }
@@ -436,7 +800,7 @@
    }
    
    
    @Log(title = "【扫一扫】支付充电充值费用", businessType = BusinessType.UPDATE,operatorType = OperatorType.MOBILE)
    @ResponseBody
    @PostMapping(value = "/paymentChargingOrder")
    @ApiOperation(value = "支付充电充值费用", tags = {"小程序-扫一扫"})
@@ -451,7 +815,7 @@
    @PostMapping(value = "/chargingOrderWXCallback")
    public void chargingOrderWXCallback(@RequestParam("out_trade_no") String out_trade_no, @RequestParam("transaction_id") String transaction_id,
                                        @RequestParam("attach") String attach) {
        AjaxResult ajaxResult = chargingOrderService.chargingOrderCallback(1, out_trade_no, transaction_id, attach);
        chargingOrderService.chargingOrderCallback(1, out_trade_no, transaction_id, attach);
    }
    
    
@@ -462,7 +826,7 @@
    @ResponseBody
    @PostMapping(value = "/securityDetection")
    public void securityDetection(@RequestBody SecurityDetectionVO securityDetection){
        log.error("-------------------安全检测数据-------------------:" + securityDetection);
        log.info("-------------------安全检测数据-------------------:" + securityDetection);
        chargingOrderService.securityDetection(securityDetection);
    }
    
@@ -473,7 +837,7 @@
    @ResponseBody
    @PostMapping(value = "/startChargeSuccessfully")
    public void startChargeSuccessfully(@RequestBody PlatformStartChargingReplyMessageVO message){
        log.error("-------------------远程启动充电请求应答-------------------:" + message);
        log.info("-------------------远程启动充电请求应答-------------------:" + message);
        chargingOrderService.startChargeSuccessfully(message);
    }
    
@@ -484,22 +848,36 @@
     */
    @ResponseBody
    @PostMapping(value = "/chargingOrderALICallback")
    public void chargingOrderALICallback(@RequestBody AliQueryOrder aliQueryOrder, HttpServletResponse response) {
        try {
            String out_trade_no = aliQueryOrder.getOutTradeNo();
            String transaction_id = aliQueryOrder.getTradeNo();
            String attach = aliQueryOrder.getPassbackParams();
            AjaxResult ajaxResult = chargingOrderService.chargingOrderCallback(2, out_trade_no, transaction_id, attach);
            if (ajaxResult.isSuccess()) {
                PrintWriter writer = response.getWriter();
                writer.println("success");
                writer.flush();
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    public void chargingOrderALICallback(@RequestParam("out_trade_no") String out_trade_no,
                                         @RequestParam("transaction_id") String transaction_id,
                                         @RequestParam("attach") String attach) {
        chargingOrderService.chargingOrderCallback(2, out_trade_no, transaction_id, attach);
    }
    /**
     *
     * @param code
     */
    @ResponseBody
    @PostMapping(value = "/refund")
    public R refund(@RequestParam(value = "code") String code){
        chargingOrderService.refund(code);
        return R.ok();
    }
    /**
     *
     * @param code
     */
    @ResponseBody
    @PostMapping(value = "/refund1")
    public R refund1(@RequestParam(value = "code") String code, @RequestParam(value = "money") BigDecimal money){
        chargingOrderService.refund1(code, money);
        return R.ok();
    }
    
    
    /**
@@ -516,8 +894,7 @@
    
    
    
    @ResponseBody
    @GetMapping(value = "/preChargeCheck/{id}")
    @ApiOperation(value = "获取安全检测数据", tags = {"小程序-扫一扫"})
@@ -531,7 +908,6 @@
    }
    
    
    @ResponseBody
    @GetMapping(value = "/getChargingDetails/{id}")
    @ApiOperation(value = "获取充电中页面数据", tags = {"小程序-扫一扫"})
@@ -542,8 +918,8 @@
        ChargingDetails chargingDetails = chargingOrderService.getChargingDetails(id);
        return AjaxResult.success(chargingDetails);
    }
    @Log(title = "【扫一扫】手动停止充电", businessType = BusinessType.STOP,operatorType = OperatorType.MOBILE)
    @ResponseBody
    @PutMapping(value = "/stopCharging/{id}")
    @ApiOperation(value = "手动停止充电", tags = {"小程序-扫一扫"})
@@ -561,7 +937,7 @@
     */
    @PostMapping("/terminateSuccessfulResponse")
    public void terminateSuccessfulResponse(@RequestBody PlatformStopChargingReplyVO platformStopChargingReply){
        log.error("-------------------远程停止充电请求应答-------------------:" + platformStopChargingReply);
        log.info("-------------------远程停止充电请求应答-------------------:" + platformStopChargingReply);
        chargingOrderService.terminateSuccessfulResponse(platformStopChargingReply);
    }
    
@@ -571,19 +947,21 @@
     * @param vo
     */
    @PostMapping("/endChargeBillingCharge")
    public void endChargeBillingCharge(@RequestBody TransactionRecordMessageVO vo){
        log.error("-------------------停止充电返回账单后计算费用及修改业务状态-------------------:" + vo);
        chargingOrderService.endChargeBillingCharge(vo);
    public R endChargeBillingCharge(@RequestBody TransactionRecordMessageVO vo){
        log.info("-------------------停止充电返回账单后计算费用及修改业务状态-------------------:" + vo);
        return chargingOrderService.endChargeBillingCharge(vo);
    }
    @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/six/charge")
    @ApiOperation(value = "电站收入分析", tags = {"后台-数据分析-平台收入分析"})
    public R<List<SixChargingDto>> charge(Integer siteId) {
        Long userId = SecurityUtils.getUserId();
        Long userId = tokenService.getLoginUser().getUserid();
        //如果没传siteId,获取当前登陆人所有的siteIds
        List<Integer> siteIds = new ArrayList<>();
        if (siteId==null){
@@ -594,19 +972,49 @@
        }else {
            siteIds.add(siteId);
        }
        if (siteIds.isEmpty()){
            siteIds.add(-1);
        }
        LocalDate sixBefore = PreviousSixMonths.get();
        //通过siteIds进行sql查询统计
        List<SixChargingDto> sixChargingDtos = generateLastSixMonths();
        List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds);
        for (SixChargingDto sixChargingDto : sixChargingDtos) {
            for (SixChargingDto chargingDto : chargingDtos) {
                if (sixChargingDto.getMonth().equals(chargingDto.getMonth())){
                    BeanUtils.copyProperties(chargingDto,sixChargingDto);
                }
            }
        return R.ok(chargingDtos);
        }
        return R.ok(sixChargingDtos);
    }
    public static List<SixChargingDto> generateLastSixMonths() {
        LocalDate today = LocalDate.now();
        List<SixChargingDto> months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
        for (int i = 5; i >= 0; i--) {
            LocalDate date = today.minusMonths(i);
            String month = date.format(formatter);
            SixChargingDto sixChargingDto = new SixChargingDto();
            sixChargingDto.setMonth(month);
            months.add(sixChargingDto);
        }
        return months;
    }
    @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/six/circle")
    @ApiOperation(value = "电站收入占比", tags = {"后台-数据分析-平台收入分析"})
    public R<List<SixCircleDto>> circle() {
        Long userId = SecurityUtils.getUserId();
        Long userId = tokenService.getLoginUser().getUserid();
        //获取当前登录的siteIds
        List<Integer> siteIds = new ArrayList<>();
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
@@ -615,7 +1023,9 @@
            }
        //进行统计groupBySiteId
        LocalDate sixBefore = PreviousSixMonths.get();
            if (siteIds.isEmpty()){
                siteIds.add(-1);
            }
        List<SixCircleDto> sixCircleDtos = chargingOrderService.circle(siteIds,sixBefore);
        for (SixCircleDto sixCircleDto : sixCircleDtos) {
            Site site = siteClient.getSiteByIds(Arrays.asList(sixCircleDto.getSiteId())).getData().get(0);
@@ -624,8 +1034,9 @@
        return R.ok(sixCircleDtos);
    }
    @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/six/shop")
    @ApiOperation(value = "购物收入", tags = {"后台-数据分析-平台收入分析"})
@@ -633,9 +1044,37 @@
        //count近6个月的数据
        LocalDate sixBefore = PreviousSixMonths.get();
        List<SixShopDto> sixShopDtos =  shoppingOrderService.sixBefore(sixBefore,status);
        return R.ok(sixShopDtos);
        List<SixShopDto> sixChargingDtos = generateLastSixMonths1();
        for (SixShopDto sixChargingDto : sixChargingDtos) {
            for (SixShopDto chargingDto : sixShopDtos) {
                if (sixChargingDto.getMonth().equals(chargingDto.getMonth())){
                    BeanUtils.copyProperties(chargingDto,sixChargingDto);
                }
            }
        }
        return R.ok(sixChargingDtos);
    }
    public static List<SixShopDto> generateLastSixMonths1() {
        LocalDate today = LocalDate.now();
        List<SixShopDto> months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
        for (int i = 5; i >= 0; i--) {
            LocalDate date = today.minusMonths(i);
            String month = date.format(formatter);
            SixShopDto sixChargingDto = new SixShopDto();
            sixChargingDto.setMonth(month);
            months.add(sixChargingDto);
        }
        return months;
    }
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/work/shop")
    @ApiOperation(value = "购物收入", tags = {"后台-工作台"})
@@ -645,7 +1084,8 @@
        List<Map<String,Object >> shopData =  shoppingOrderService.getData(statisticsQueryDto);
        return R.ok(shopData);
    }
    @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/six/vip")
    @ApiOperation(value = "vip收入", tags = {"后台-数据分析-平台收入分析"})
@@ -655,64 +1095,159 @@
        List<SixVipDto> vipDtos =  vipOrderService.sixBefore(sixBefore);
        return R.ok(vipDtos);
    }
    @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/six/total")
    @ApiOperation(value = "底部数据分类", tags = {"后台-数据分析-平台收入分析"})
    public R<Map<String,Object>> total() {
        //count近6个月的数据
        LocalDate sixBefore = PreviousSixMonths.get();
        Map<String,Object>  map = chargingOrderService.countAll(sixBefore);
        BigDecimal data = parkingLotClient.getRecordAmount(sixBefore).getData();
        Long userId = tokenService.getLoginUser().getUserid();
        //获取当前登录的siteIds
        List<Integer> siteIds = new ArrayList<>();
        List<GetSiteListDTO> data9 = siteClient.getSiteListByUserId(userId).getData();
        for (GetSiteListDTO datum : data9) {
            siteIds.add(datum.getId());
        }
        //进行统计groupBySiteId
        if (siteIds.isEmpty()){
            siteIds.add(-1);
        }
        Map<String,Object>  map = chargingOrderService.countAll(siteIds);
        BigDecimal data = parkingLotClient.getRecordAmount().getData();
        if (map ==null){
            map = new HashMap<String,Object>();
        }
        map.put("parkingAmount",data);
        BigDecimal data1 =   shoppingOrderService.getSumAmount(sixBefore);
        BigDecimal data1 =   shoppingOrderService.getSumAmount();
        map.put("shopAmount",data1);
        BigDecimal data2 =   vipOrderService.getSumAmout(sixBefore);
        BigDecimal data2 =   vipOrderService.getSumAmout();
        map.put("vipAmount",data2);
    return R.ok(map);
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().eq(TChargingOrder::getStatus, 5).eq(TChargingOrder::getDelFlag, 0)
                .eq(TChargingOrder::getRechargePaymentStatus, 2).list();
        BigDecimal sharingAmount = BigDecimal.ZERO;
        BigDecimal commissionAmount = BigDecimal.ZERO;
        //计算list中electrovalence的总和
        BigDecimal totalElectrovalence = BigDecimal.ZERO;
        //计算list中serviceCharge的总和
        BigDecimal totalServiceCharge = BigDecimal.ZERO;
        List<TChargingOrderAccountingStrategy> accountingStrategyList = chargingOrderAccountingStrategyService.list();
        for (TChargingOrder order : list) {
            List<TChargingOrderAccountingStrategy> collect = accountingStrategyList.stream().filter(s -> s.getChargingOrderId().equals(order.getId())).collect(Collectors.toList());
            BigDecimal periodElectricPrice = collect.stream().map(TChargingOrderAccountingStrategy::getPeriodElectricPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal periodServicePrice = collect.stream().map(TChargingOrderAccountingStrategy::getPeriodServicePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            totalElectrovalence = totalElectrovalence.add(periodElectricPrice);
            if(2 != order.getOrderSource()){
                totalServiceCharge = totalServiceCharge.add(periodServicePrice);
                commissionAmount = commissionAmount.add((periodElectricPrice.add(periodServicePrice)).multiply(new BigDecimal("0.006")));
            }else{
                totalServiceCharge = totalServiceCharge.add(periodServicePrice.multiply(new BigDecimal("0.8")));
                sharingAmount = sharingAmount.add(periodServicePrice.multiply(new BigDecimal("0.2")));
            }
        }
        map.put("service_charge",totalServiceCharge.setScale(2, BigDecimal.ROUND_HALF_EVEN));
        map.put("electrovalence",totalElectrovalence.setScale(2, BigDecimal.ROUND_HALF_EVEN));
        map.put("commission_amount",commissionAmount.setScale(2, BigDecimal.ROUND_HALF_EVEN));
        map.put("sharing_amount",sharingAmount.setScale(2, BigDecimal.ROUND_HALF_EVEN));
        return R.ok(map);
    }
    @Resource
    private UploadRealTimeMonitoringDataClient uploadRealTimeMonitoringDataClient;
    @RequiresPermissions(value = {"/chargeOrderMonitoring"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/watch/chargingOrder")
    @ApiOperation(value = "监控订单", tags = {"管理后台-订单管理"})
    public R watchChargingOrder(@RequestBody MongoChargingOrderQuery mongoChargingOrderQuery) {
//        Integer page = dto.getPageCurr();
//        Integer pageSize = dto.getPageSize();
//        List<Long> data = appUserClient.getUserIdsByPhone(dto.getPhone()).getData();
//        dto.setUserIds(data);
//        dto.setPageCurr(1);
//        dto.setPageSize(99999);
//        TCharingOrderVO res = chargingOrderService.chargingOrder(dto);
//        Map<String,TChargingOrder> map = new HashMap<>();
//        //吧list放入map中
//        for (ChargingOrderVO record : res.getList().getRecords()) {
//            map.put(record.getCode(),record);
//        }
//        Set<String> strings = map.keySet();
        List<UploadRealTimeMonitoringData> data1 = uploadRealTimeMonitoringDataClient.getAll(mongoChargingOrderQuery).getData();
//        List<ChargingOrderAndUploadRealTimeMonitoringDataDto> dtos = new ArrayList<>();
//        for (UploadRealTimeMonitoringData uploadRealTimeMonitoringData : data1) {
//            ChargingOrderAndUploadRealTimeMonitoringDataDto dataDto = new ChargingOrderAndUploadRealTimeMonitoringDataDto();
//            BeanUtils.copyProperties(uploadRealTimeMonitoringData,dataDto);
//            TChargingOrder tChargingOrder = map.get(uploadRealTimeMonitoringData.getCharging_pile_code());
//            if (tChargingOrder!=null) {
//                BeanUtils.copyProperties(tChargingOrder, dataDto);
//            }
//            dtos.add(dataDto);
//        }
        return R.ok(data1);
    public R watchChargingOrder(@RequestBody MongoChargingOrderQuery query) {
        Set<Integer> ids = null;
        //校验合作商权限
        SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
        Integer roleType = sysUser.getRoleType();
        Integer objectId = sysUser.getObjectId();
        R<Integer> admin = sysUserClient.isAdmin(tokenService.getLoginUser().getUserid());
        //合作商
        if(roleType == 2){
            ids = partnerClient.authSite(objectId, SiteMenu.SITE_LIST.getValue()).getData();
        }else{
            //非管理员需要根据角色和用户配置查询允许的站点数据
            //改用roleId=1来判断
            if(admin.getData()!=1){
                List<Integer> data = userSiteClient.getSiteIds(sysUser.getUserId()).getData();
                List<SysUserRoleVo> data2 = sysUserRoleClient.getRoleByUserId(sysUser.getUserId()).getData();
                if(data2.size() > 0){
                    List<Integer> data1 = roleSiteClient.getSiteIds(data2.get(0).getRoleId()).getData();
                    data.addAll(data1);
                }
                ids = new HashSet<>(data);
            }
        }
        LambdaQueryWrapper<TChargingOrder> queryWrapper = new LambdaQueryWrapper<TChargingOrder>().like(StringUtils.isNotEmpty(query.getCode()), TChargingOrder::getCode, query.getCode())
                .eq(null != query.getOrderType(), TChargingOrder::getOrderType, query.getOrderType())
                .eq(null != query.getSiteId(), TChargingOrder::getSiteId, query.getSiteId())
                .eq(null != query.getPileId(), TChargingOrder::getChargingPileId, query.getPileId())
                .eq(null != query.getGunId(), TChargingOrder::getChargingGunId, query.getGunId())
                .eq(null != query.getStatus(), TChargingOrder::getStatus, query.getStatus())
                .eq(TChargingOrder::getDelFlag, 0).eq(TChargingOrder::getRechargePaymentStatus, 2)
                .in(null != ids && ids.size() > 0, TChargingOrder::getSiteId, ids);
        if(StringUtils.isNotEmpty(query.getCreateTime())){
            String[] split = query.getCreateTime().split(" - ");
            queryWrapper.between(TChargingOrder::getStartTime, split[0], split[1]);
        }
        if(StringUtils.isNotEmpty(query.getLastTime())){
            String[] split = query.getLastTime().split(" - ");
            queryWrapper.between(TChargingOrder::getEndTime, split[0], split[1]);
        }
        PageInfo<TChargingOrder> pageInfo = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        PageInfo<TChargingOrder> orderPageInfo = chargingOrderService.page(pageInfo, queryWrapper.orderByDesc(TChargingOrder::getCreateTime));
        List<Site> siteList = siteClient.getSiteAll().getData();
        List<WatchChargingOrderVo> list = new ArrayList<>();
        for (TChargingOrder record : orderPageInfo.getRecords()) {
            WatchChargingOrderVo vo = new WatchChargingOrderVo();
            BeanUtils.copyProperties(record, vo);
            vo.setIdStr(record.getId().toString());
            Site site = siteList.stream().filter(s->s.getId().equals(record.getSiteId())).findFirst().get();
            vo.setSiteName(site.getName());
            TChargingPile chargingPile = chargingPileClient.getChargingPileById(record.getChargingPileId()).getData();
            vo.setTerminalName(chargingPile.getName());
            TChargingGun chargingGun = chargingGunClient.getChargingGunById(record.getChargingGunId()).getData();
            vo.setTerminalCode(chargingGun.getName());
            if(null != record.getStartTime() && null != record.getEndTime()){
                long time = record.getEndTime().toEpochSecond(ZoneOffset.UTC) - record.getStartTime().toEpochSecond(ZoneOffset.UTC);
                vo.setChargingTime(time + "");
            }
            long count = chargingOrderAccountingStrategyService.count(new LambdaQueryWrapper<TChargingOrderAccountingStrategy>().eq(TChargingOrderAccountingStrategy::getChargingOrderId, record.getId()));
            vo.setTimeFrame(count);
            vo.setAuthInfo(roleType == 1 ? true : partnerClient.authMenu(objectId, record.getSiteId(), SiteMenu.CHARGING_PILE_ORDER_MONITORING_RECORD_INFO.getValue()));
            vo.setAuthDelete(roleType == 1 ? true : partnerClient.authMenu(objectId, record.getSiteId(), SiteMenu.CHARGING_PILE_ORDER_MONITORING_RECORD_DEL.getValue()));
            list.add(vo);
        }
        PageInfo<WatchChargingOrderVo> pageInfos = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        pageInfos.setRecords(list);
        pageInfos.setCurrent(pageInfo.getCurrent());
        pageInfos.setPages(pageInfo.getPages());
        pageInfos.setSize(pageInfo.getSize());
        pageInfos.setStartIndex(pageInfo.getStartIndex());
        pageInfos.setTotal(pageInfo.getTotal());
        return R.ok(pageInfos);
    }
    
    
    @RequiresPermissions(value = {"/chargeOrderMonitoring/del"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/watch/deletes")
    @ApiOperation(value = "监控订单-删除", tags = {"管理后台-订单管理"})
    public R watchChargingOrder(@RequestParam String id) {
        uploadRealTimeMonitoringDataClient.delete(id);
        return R.ok();
    }
    
    /**
     * 处理充电订单实时监控数据相关的业务逻辑
@@ -732,18 +1267,18 @@
        return R.ok(chargingOrderService.getOne(Wrappers.lambdaQuery(TChargingOrder.class)
                .eq(TChargingOrder::getCode,code)));
    }
    @RequiresPermissions(value = {"/chargingOperationAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/charging/statistics")
    @ApiOperation(value = "统计,充电订单分析", tags = {"管理后台-数据分析-充电运营分析"})
    public R<TCharingOrderMapVO> watchChargingOrder(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        List<Integer> siteIds =new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null) {
            Long userId = SecurityUtils.getUserId();
            Long userId = tokenService.getLoginUser().getUserid();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
@@ -752,70 +1287,203 @@
        }else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        if (siteIds.isEmpty())siteIds.add(-1);
        TCharingOrderMapVO tCharingOrderMapVO = new TCharingOrderMapVO();
        LocalDate start = null;
        LocalDate end = null;
        if (statisticsQueryDto.getDayType()==1){
            start = LocalDate.now();
            end = LocalDate.now().plusDays(1);
        }else if (statisticsQueryDto.getDayType()==2){
            LocalDate today = LocalDate.now();
            // 获取本周一的日期
            LocalDate mondayThisWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            System.out.println("本周一是: " + mondayThisWeek);
        }
        else if (statisticsQueryDto.getDayType()==3){
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
        } else if (statisticsQueryDto.getDayType()==3){
            // 获取当前日期
            LocalDate today = LocalDate.now();
            // 获取本月1号的日期
            YearMonth yearMonth = YearMonth.from(today);
//            start = yearMonth.atDay(1);
//
//            System.out.println("本月1号是: " + start);
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
        }else if (statisticsQueryDto.getDayType()==4){
            LocalDate today = LocalDate.now();
            // 获取当前年份
            int currentYear = today.getYear();
            // 获取今年1月1日的日期
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
        }else if (statisticsQueryDto.getDayType()==5){
            // 获取今年1月1日的日期
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
            if (start.equals(end)){
                end =  end.plusDays(1);
            }
        }
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().ge(TChargingOrder::getStartTime, start).le(TChargingOrder::getEndTime, end).in(TChargingOrder::getSiteId, siteIds).list();
        List<Long> chargingOrderIds = list.stream().map(TChargingOrder::getId).collect(Collectors.toList());
        //上方饼图
         List<Map<String,Object>> maps =   chargingOrderService.getSumByType(chargingOrderIds);
         List<Map<String,Object>> maps = chargingOrderService.getSumByType(start,end, siteIds);
        if (statisticsQueryDto.getDayType()==1){
            List<Map<String,Object>> maps1 = chargingOrderService.getDateData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
            List<Map<String,Object>> maps1 = chargingOrderService.getDateData(start,end, siteIds);
            List<Map<String, Object>> charMap = new ArrayList<>();
            // 生成从 "00:00" 到 "23:00" 的时间数据
            for (int hour = 0; hour < 24; hour++) {
                String time = String.format("%02d:00", hour);
                Map<String, Object> mapWithTimeValue = findMapWithTimeValue(maps1, time);
                if (mapWithTimeValue!=null){
                    charMap.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("electrovalence", 0);
                    timeMap.put("orderCount", 0);
                    timeMap.put("paymentAmount", 0);
                    timeMap.put("paymoney", 0);
                    timeMap.put("servicecharge", 0);
                    charMap.add(timeMap);
                }
            }
            tCharingOrderMapVO.setMaps1(charMap);
        }else if (statisticsQueryDto.getDayType()==2){
            List<Map<String,Object>> maps1 = chargingOrderService.getWeekData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
            List<Map<String,Object>> maps1 = chargingOrderService.getWeekData(start,end, siteIds);
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(maps1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("paymentAmount", 0);
                    dateMap.put("paymoney", 0);
                    dateMap.put("servicecharge", 0);
                    dateRangeStatistics.add(dateMap);
                }
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
            tCharingOrderMapVO.setMaps1(dateRangeStatistics);
        }else if (statisticsQueryDto.getDayType()==3){
            List<Map<String,Object>> maps1 = chargingOrderService.getMonthData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
            List<Map<String,Object>> maps1 = chargingOrderService.getMonthData(start,end, siteIds);
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(maps1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("paymentAmount", 0);
                    dateMap.put("paymoney", 0);
                    dateMap.put("servicecharge", 0);
                    dateRangeStatistics.add(dateMap);
                }
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
            tCharingOrderMapVO.setMaps1(dateRangeStatistics);
        }else  if (statisticsQueryDto.getDayType()==4){
            List<Map<String,Object>> maps1 = chargingOrderService.getYearData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
            List<Map<String,Object>> maps1 = chargingOrderService.getYearData(start,end, siteIds);
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(maps1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("paymentAmount", 0);
                    dateMap.put("paymoney", 0);
                    dateMap.put("servicecharge", 0);
                    dateRangeStatistics.add(dateMap);
                }
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
            tCharingOrderMapVO.setMaps1(dateRangeStatistics);
        }else if (statisticsQueryDto.getDayType()==5){
            List<Map<String,Object>> maps1 = chargingOrderService.getByDate(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
            List<Map<String,Object>> maps1 = chargingOrderService.getByDate(start,end, siteIds);
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(maps1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("paymentAmount", 0);
                    dateMap.put("paymoney", 0);
                    dateMap.put("servicecharge", 0);
                    dateRangeStatistics.add(dateMap);
                }
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
            tCharingOrderMapVO.setMaps1(dateRangeStatistics);
        }
        tCharingOrderMapVO.setMaps(maps);
        BigDecimal allMoney = new BigDecimal(0);
        BigDecimal commissionAmount = BigDecimal.ZERO;
        for (Map<String, Object> map : maps) {
            BigDecimal periodElectricPrice = (BigDecimal) map.get("period_electric_price");
            Long order_source = (Long)map.get("order_source");
            if(2 != order_source){
                allMoney = allMoney.add(periodElectricPrice);
            }
            BigDecimal total_amount = (BigDecimal) map.get("total_amount");
            allMoney = allMoney.add(total_amount);
            commissionAmount = commissionAmount.add((BigDecimal) map.get("commissionAmount"));
        }
        allMoney =  allMoney.multiply(new BigDecimal("0.006"));
        tCharingOrderMapVO.setAllMoney(allMoney);
        tCharingOrderMapVO.setCommissionAmount(commissionAmount);
        return R.ok(tCharingOrderMapVO);
    }
@@ -827,7 +1495,7 @@
    public R<TCharingOrderPowerMapVO> power(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            Long userId = tokenService.getLoginUser().getUserid();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
@@ -836,6 +1504,8 @@
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        List<Map<String,Object>> maps1 =  chargingOrderService.queryPower(siteIds);
@@ -847,17 +1517,32 @@
        return R.ok(tCharingOrderPowerMapVO);
    }
    @RequiresPermissions(value = {"/chargingUserAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/charging/users")
    @ApiOperation(value = "除电站流量外", tags = {"管理后台-数据分析-充电用户分析"})
    public R<TCharingUserMapVO> users(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        Long userId = tokenService.getLoginUser().getUserid();
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null){
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        }else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        if (siteIds.isEmpty())siteIds.add(-1);
        statisticsQueryDto.setSiteIds(siteIds);
        TCharingUserMapVO tCharingUserMapVO = new TCharingUserMapVO();
        //上方折现
        if (statisticsQueryDto.getDayType()==1){
        List<Map<String,Object>> map = chargingOrderService.usersDay();
        List<Map<String,Object>> map = chargingOrderService.usersDay(statisticsQueryDto);
            List<Map<String, Object>> charMap = new ArrayList<>();
            // 生成从 "00:00" 到 "23:00" 的时间数据
@@ -897,6 +1582,8 @@
        tCharingUserMapVO.setMap(charMap);
        tCharingUserMapVO.setMap1(charMap1);
        }else {
            List<Map<String,Object>> map =  chargingOrderService.usersByQuery(statisticsQueryDto);
@@ -925,11 +1612,50 @@
                startDate = startDate.plusDays(1);
            }
            tCharingUserMapVO.setMap(map);
            tCharingUserMapVO.setMap(dateRangeStatistics);
            List<Map<String,Object>> map1 =  chargingOrderService.usersByQuery1(statisticsQueryDto);
            LocalDate startDate1 = statisticsQueryDto.getStartTime();
            LocalDate endDate1 = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics1 = new ArrayList<>();
            // 遍历日期范围
            while (!startDate1.isAfter(endDate1)) {
                String formattedDate = startDate1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(map1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics1.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("counts", 0);
                    dateRangeStatistics1.add(dateMap);
                }
                // 移动到下一天
                startDate1 = startDate1.plusDays(1);
            }
            tCharingUserMapVO.setMap1(dateRangeStatistics1);
        }
        //用户标签
      List<Map<String,Object>> maps =    chargingOrderService.getUserTagCount();
        Map<String,Object> stringObjectMap = new HashMap<>();
        Long noTagCount =  chargingOrderService.countNoTag();
        stringObjectMap.put("count",noTagCount);
        maps.add(stringObjectMap);
        //会员标签
        List<Map<String,Object>> maps1 =  chargingOrderService.getVipCount();
@@ -938,8 +1664,21 @@
        //车辆用途
        List<Map<String, Object>> carMap = chargingOrderService.carUserMethod();
        //车辆品牌
        List<Map<String, Object>> carBrandMap = chargingOrderService.carUserBrand();
        List<String> brands = new ArrayList<>();
        for (Map<String, Object> objectMap : carBrandMap) {
            brands.add(objectMap.get("vehicle_brand").toString());
        }
        if (carBrandMap.size()>=5) {
            Long count = chargingOrderService.countCar(brands);
            Map<String, Object> others = new HashMap<>();
            others.put("vehicle_brand", "其他");
            others.put("counts", count);
            carBrandMap.add(others);
        }
        //本地车数量
        Map<String,Object> localCarMap = chargingOrderService.countLocalCar();
@@ -953,13 +1692,16 @@
        return R.ok(tCharingUserMapVO);
    }
    @RequiresPermissions(value = {"/chargingUserAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/charging/sites")
    @ApiOperation(value = "电站评价", tags = {"管理后台-数据分析-充电用户分析"})
    public R<TCharingUserEvaluateVO> sites(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        List<Integer> siteIds =new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null) {
            Long userId = SecurityUtils.getUserId();
            Long userId = tokenService.getLoginUser().getUserid();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
@@ -969,11 +1711,14 @@
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        //查询评价分
        Long aver = chargingOrderService.getAver(siteIds);
        Double aver = chargingOrderService.getAver(siteIds);
        //查询各个分数
       List<Map<String,Object>> evaluate =  chargingOrderService.getLevelEvaluate(siteIds);
        //查询差评回复数
        Long count = orderEvaluateService.lambdaQuery().isNotNull(TOrderEvaluate::getResponseTime).count();
        List<Integer> mark = new ArrayList<>();
        mark.add(1);
        mark.add(2);
        Long count = orderEvaluateService.lambdaQuery().in(TOrderEvaluate::getMark, mark).isNotNull(TOrderEvaluate::getResponseTime).count();
        TCharingUserEvaluateVO tCharingUserEvaluateVO = new TCharingUserEvaluateVO();
        tCharingUserEvaluateVO.setAver(aver);
        tCharingUserEvaluateVO.setEvaluate(evaluate);
@@ -986,21 +1731,23 @@
        List<Map<String,Object>> badTop = orderEvaluateService.badTop(siteIds);
        //流量分析
        List<Map<String,Object>> sourceMap = chargingOrderService.countBySource(siteIds);
        List<Map<String,Object>> sourceMap = chargingOrderService.countBySource(siteIds,statisticsQueryDto);
        tCharingUserEvaluateVO.setGoodTop(goodTop);
        tCharingUserEvaluateVO.setBadTop(badTop);
        tCharingUserEvaluateVO.setFlow(sourceMap);
        //流量
        return R.ok(tCharingUserEvaluateVO);
    }
    @RequiresPermissions(value = {"/operationMaintenanceAnalysis"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/charging/equipment")
    @ApiOperation(value = "电站评价", tags = {"管理后台-数据分析-设备运维分析"})
    public R<TCharingUserEquimentVO> equipment(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        List<Integer> siteIds =new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null) {
            Long userId = SecurityUtils.getUserId();
        if (statisticsQueryDto.getSiteId()==null||statisticsQueryDto.getSiteId()==0) {
            Long userId = tokenService.getLoginUser().getUserid();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
@@ -1011,8 +1758,48 @@
        }
        //直流可用率
        List<Map<String,Object>> equipmentMap1 = chargingOrderService.equipmentUserType1(siteIds,statisticsQueryDto);
        for (Map<String, Object> result : equipmentMap1) {
            Object percentObj = result.get("percent");
            if (percentObj instanceof String) {
                try {
                    BigDecimal percent = new BigDecimal((String) percentObj);
                    if (percent.compareTo(BigDecimal.ZERO) < 0) {
                        result.put("percent", percent.negate().toString());
                    }
                } catch (NumberFormatException e) {
                    // 处理转换异常
                    result.put("percent", BigDecimal.ZERO); // 或者其他默认值
                }
            } else if (percentObj instanceof BigDecimal) {
                BigDecimal percent = (BigDecimal) percentObj;
                if (percent.compareTo(BigDecimal.ZERO) < 0) {
                    result.put("percent", percent.negate().toString());
                }
            }
        }
        //交流可用率
        List<Map<String,Object>> equipmentMap2= chargingOrderService.equipmentUserType2(siteIds,statisticsQueryDto);
        for (Map<String, Object> result : equipmentMap2) {
            Object percentObj = result.get("percent");
            if (percentObj instanceof String) {
                try {
                    BigDecimal percent = new BigDecimal((String) percentObj);
                    if (percent.compareTo(BigDecimal.ZERO) < 0) {
                        result.put("percent", percent.negate().toString());
                    }
                } catch (NumberFormatException e) {
                    // 处理转换异常
                    result.put("percent", BigDecimal.ZERO); // 或者其他默认值
                }
            } else if (percentObj instanceof BigDecimal) {
                BigDecimal percent = (BigDecimal) percentObj;
                if (percent.compareTo(BigDecimal.ZERO) < 0) {
                    result.put("percent", percent.negate().toString());
                }
            }
        }
        //取出直流可用率和交流可用率的percent的平均值保留两位小数
@@ -1061,8 +1848,8 @@
        return R.ok(tCharingUserEquimentVO);
    }
    private static double calculateAveragePercent(List<Map<String, Object>> mapList1, List<Map<String, Object>> mapList2) {
    private static final DecimalFormat DF = new DecimalFormat("#.00");
    public static double calculateAveragePercent(List<Map<String, Object>> mapList1, List<Map<String, Object>> mapList2) {
        int totalElements = mapList1.size() + mapList2.size();
        double sum = 0.0;
@@ -1084,16 +1871,21 @@
        }
        // 计算平均值
        return sum / totalElements;
    }
        double average = sum / totalElements;
        // 格式化为两位小数
        return Double.parseDouble(DF.format(average));
    }
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/work/charge")
    @ApiOperation(value = "上方充电数据统计", tags = {"管理后台-工作台"})
    public R<TCharingWorkVO> workCharge(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            Long userId = tokenService.getLoginUser().getUserid();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
@@ -1102,17 +1894,41 @@
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().in(!siteIds.isEmpty(), TChargingOrder::getSiteId, siteIds).eq(statisticsQueryDto.getSiteId() != null, TChargingOrder::getSiteId, statisticsQueryDto.getSiteId()).list();
        LocalDateTime selectDate = statisticsQueryDto.getSelectDate();
        LocalDateTime min = selectDate.with(LocalTime.MIN);
        LocalDateTime max = selectDate.with(LocalTime.MAX);
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().in(!siteIds.isEmpty(), TChargingOrder::getSiteId, siteIds)
                .between(TChargingOrder::getCreateTime, min, max).eq(TChargingOrder::getStatus,5).eq(TChargingOrder::getDelFlag, 0)
                .eq(TChargingOrder::getRechargePaymentStatus, 2)
                .eq(statisticsQueryDto.getSiteId() != null, TChargingOrder::getSiteId, statisticsQueryDto.getSiteId()).list();
        //当日的订单总数
        int size = list.size();
        //计算list中paymentAmount的总和
        BigDecimal totalPaymentAmount = list.stream().map(TChargingOrder::getOrderAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalPaymentAmount = BigDecimal.ZERO;
        //计算list中electrovalence的总和
        BigDecimal totalElectrovalence = list.stream().map(TChargingOrder::getElectrovalence).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalElectrovalence = BigDecimal.ZERO;
        //计算list中serviceCharge的总和
        BigDecimal totalServiceCharge = list.stream().map(TChargingOrder::getServiceCharge).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalServiceCharge = BigDecimal.ZERO;
        //计算list中charging_capacity的总和
        BigDecimal totalChargingCapacity = list.stream().map(TChargingOrder::getChargingCapacity).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalChargingCapacity = BigDecimal.ZERO;
        List<TChargingOrderAccountingStrategy> accountingStrategyList = chargingOrderAccountingStrategyService.list();
        for (TChargingOrder order : list) {
            List<TChargingOrderAccountingStrategy> collect = accountingStrategyList.stream().filter(s -> s.getChargingOrderId().equals(order.getId())).collect(Collectors.toList());
            BigDecimal periodElectricPrice = collect.stream().map(TChargingOrderAccountingStrategy::getPeriodElectricPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal periodServicePrice = collect.stream().map(TChargingOrderAccountingStrategy::getPeriodServicePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal chargingCapacity = collect.stream().map(TChargingOrderAccountingStrategy::getChargingCapacity).reduce(BigDecimal.ZERO, BigDecimal::add);
            totalElectrovalence = totalElectrovalence.add(periodElectricPrice);
            totalChargingCapacity = totalChargingCapacity.add(chargingCapacity);
            if(2 != order.getOrderSource()){
                totalServiceCharge = totalServiceCharge.add(periodServicePrice);
                totalPaymentAmount = totalPaymentAmount.add(periodElectricPrice).add(periodServicePrice);
            }else{
                totalServiceCharge = totalServiceCharge.add(periodServicePrice.multiply(new BigDecimal("0.8")));
                totalPaymentAmount = totalPaymentAmount.add(periodElectricPrice).add(periodServicePrice.multiply(new BigDecimal("0.8")));
            }
        }
        TCharingWorkVO tCharingWorkVO = new TCharingWorkVO();
        tCharingWorkVO.setCount(size);
        tCharingWorkVO.setTotalPaymentAmount(totalPaymentAmount);
@@ -1121,107 +1937,112 @@
        tCharingWorkVO.setTotalChargingCapacity(totalChargingCapacity);
        return R.ok(tCharingWorkVO);
    }
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/work/chargeDetail")
    @ApiOperation(value = "运营情况", tags = {"管理后台-工作台"})
    public R workCharge(@RequestBody ChargingDetailQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        if (statisticsQueryDto.getDayType()==1) {
          List<Map<String,Object>> charMap1 = chargingOrderService.getHourType(siteIds,statisticsQueryDto);
            List<Map<String, Object>> charMap = new ArrayList<>();
            // 生成从 "00:00" 到 "23:00" 的时间数据
            for (int hour = 0; hour < 24; hour++) {
                String time = String.format("%02d:00", hour);
                 Map<String, Object> mapWithTimeValue = findMapWithTimeValue(charMap1, time);
                if (mapWithTimeValue!=null){
                    charMap.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("electrovalence", 0);
                    timeMap.put("orderCount", 0);
                    timeMap.put("servicecharge", 0);
                    timeMap.put("electricity", 0);
                    charMap.add(timeMap);
        try {
            List<Integer> siteIds = new ArrayList<>();
            if (statisticsQueryDto.getSiteId() == null) {
                Long userId = tokenService.getLoginUser().getUserid();
                //获取当前登录的siteIds
                List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
                for (GetSiteListDTO datum : data) {
                    siteIds.add(datum.getId());
                }
            } else {
                siteIds.add(statisticsQueryDto.getSiteId());
            }
          return R.ok(charMap);
        }else if (statisticsQueryDto.getDayType()==2){
            // 假设 chargingOrderService.getDateType() 返回的是按天的数据
            List<Map<String, Object>> charMap1 = chargingOrderService.getDateType(siteIds, statisticsQueryDto);
            // 解析 startTime 和 endTime 为 LocalDate
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(charMap1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("servicecharge", 0);
                    dateMap.put("electricity", 0);
                    dateRangeStatistics.add(dateMap);
            if (statisticsQueryDto.getDayType()==1) {
                List<Map<String,Object>> charMap1 = chargingOrderService.getHourType(siteIds,statisticsQueryDto);
                List<Map<String, Object>> charMap = new ArrayList<>();
                // 生成从 "00:00" 到 "23:00" 的时间数据
                for (int hour = 0; hour < 24; hour++) {
                    String time = String.format("%02d:00", hour);
                    Map<String, Object> mapWithTimeValue = findMapWithTimeValue(charMap1, time);
                    if (mapWithTimeValue!=null){
                        charMap.add(mapWithTimeValue);
                    }else {
                        Map<String, Object> timeMap = new HashMap<>();
                        timeMap.put("time", time); // 初始化值为 null
                        timeMap.put("electrovalence", 0);
                        timeMap.put("orderCount", 0);
                        timeMap.put("servicecharge", 0);
                        timeMap.put("electricity", 0);
                        charMap.add(timeMap);
                    }
                }
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
                return R.ok(charMap);
            }else if (statisticsQueryDto.getDayType()==2){
                // 假设 chargingOrderService.getDateType() 返回的是按天的数据
                List<Map<String, Object>> charMap1 = chargingOrderService.getDateType(siteIds, statisticsQueryDto);
                // 解析 startTime 和 endTime 为 LocalDate
                LocalDate startDate = statisticsQueryDto.getStartTime();
                LocalDate endDate = statisticsQueryDto.getEndTime();
                List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
                // 遍历日期范围
                while (!startDate.isAfter(endDate)) {
                    String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    Map<String, Object> dailyStats = findMapWithDateValue(charMap1, formattedDate);
                    if (dailyStats != null) {
                        dateRangeStatistics.add(dailyStats);
                    } else {
                        Map<String, Object> dateMap = new HashMap<>();
                        dateMap.put("time", formattedDate);
                        dateMap.put("electrovalence", 0);
                        dateMap.put("orderCount", 0);
                        dateMap.put("servicecharge", 0);
                        dateMap.put("electricity", 0);
                        dateRangeStatistics.add(dateMap);
                    }
                    // 移动到下一天
                    startDate = startDate.plusDays(1);
                }
//            return dateRangeStatistics;
            return R.ok(dateRangeStatistics);
        }else if (statisticsQueryDto.getDayType()==3){
            List<Map<String,Object>> charMap1 =  chargingOrderService.getMonthType(siteIds,statisticsQueryDto);
            // 解析 startTime 和 endTime 为 LocalDate
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                Map<String, Object> dailyStats = findMapWithDateValue(charMap1, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("servicecharge", 0);
                    dateMap.put("electricity", 0);
                    dateRangeStatistics.add(dateMap);
                return R.ok(dateRangeStatistics);
            }else if (statisticsQueryDto.getDayType()==3){
                List<Map<String,Object>> charMap1 =  chargingOrderService.getMonthType(siteIds,statisticsQueryDto);
                // 解析 startTime 和 endTime 为 LocalDate
                LocalDate startDate = statisticsQueryDto.getStartTime();
                LocalDate endDate = statisticsQueryDto.getEndTime();
                List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
                // 遍历日期范围
                while (!startDate.isAfter(endDate)) {
                    String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                    Map<String, Object> dailyStats = findMapWithDateValue(charMap1, formattedDate);
                    if (dailyStats != null) {
                        dateRangeStatistics.add(dailyStats);
                    } else {
                        Map<String, Object> dateMap = new HashMap<>();
                        dateMap.put("time", formattedDate);
                        dateMap.put("electrovalence", 0);
                        dateMap.put("orderCount", 0);
                        dateMap.put("servicecharge", 0);
                        dateMap.put("electricity", 0);
                        dateRangeStatistics.add(dateMap);
                    }
                    // 移动到下一天
                    startDate = startDate.plusMonths(1);
                }
                // 移动到下一天
                startDate = startDate.plusMonths(1);
                return R.ok(dateRangeStatistics);
            }
            return R.ok(dateRangeStatistics);
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok();
@@ -1245,17 +2066,18 @@
        }
        return null;
    }
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @PostMapping(value = "/work/use")
    @ApiOperation(value = "利用率", tags = {"管理后台-工作台"})
    public R workUse(@RequestBody ChargingDetailQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            Long userId = tokenService.getLoginUser().getUserid();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
@@ -1266,19 +2088,18 @@
        }
       List<Map<String,Object>>   capMap  =   chargingOrderService.getchargingCapacity(siteIds,statisticsQueryDto);
        List<TChargingPile> chargingPiles = chargingPileClient.getChargingPileBySiteIds(siteIds).getData();
        //获取chargingPiles的ratedPower的总和再乘以chargingPiles的数量再乘以24
        BigDecimal totalRatedPower = chargingPiles.stream().map(TChargingPile::getRatedPower).reduce(BigDecimal.ZERO, BigDecimal::add).multiply(new BigDecimal(chargingPiles.size())).multiply(new BigDecimal(24));
        //将capMap的chargingCapacity除以totalRatedPower保留两位数
        BigDecimal totalRatedPower = chargingPiles.stream().map(TChargingPile::getRatedPower).reduce(BigDecimal.ZERO, BigDecimal::add);
        //每日利用率=当日充电度数/(桩总功率*24小时)
        BigDecimal multiply1 = totalRatedPower.multiply(new BigDecimal(24));
        System.err.println(JSON.toJSONString(capMap) + "---" + chargingPiles.size() + "---" + totalRatedPower + "---" + multiply1);
        capMap.forEach(map -> {
            BigDecimal chargingCapacity = (BigDecimal) map.get("chargingCapacity");
            BigDecimal result = chargingCapacity.divide(totalRatedPower, 2, RoundingMode.HALF_UP);
            map.put("chargingCapacity", result);
            BigDecimal result = chargingCapacity.divide(multiply1, 4, RoundingMode.HALF_UP);
            BigDecimal multiply = result.multiply(new BigDecimal(100));
            map.put("chargingCapacity", multiply);
        });
        //
        // 解析 startTime 和 endTime 为 LocalDate
        LocalDate startDate = statisticsQueryDto.getStartTime();
        LocalDate endDate = statisticsQueryDto.getEndTime();
@@ -1303,11 +2124,10 @@
            startDate = startDate.plusDays(1);
        }
        return R.ok(dateRangeStatistics);
    }
    
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/work/shopOrder")
    @ApiOperation(value = "购物订单统计", tags = {"管理后台-工作台"})
@@ -1319,7 +2139,9 @@
        counts.add(count1);
        return R.ok(counts);
    }
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/work/invoice")
    @ApiOperation(value = "开票统计", tags = {"管理后台-工作台"})
@@ -1331,7 +2153,8 @@
        counts.add(count1);
        return R.ok(counts);
    }
    @RequiresPermissions(value = {"/workbench"}, logical = Logical.OR)
    @ResponseBody
    @GetMapping(value = "/work/users/count")
    @ApiOperation(value = "用户数量", tags = {"管理后台-工作台"})
@@ -1347,55 +2170,12 @@
        Long userId = tokenService.getLoginUserApplet().getUserId();
        List<TChargingOrder> list = chargingOrderService.list(Wrappers.lambdaQuery(TChargingOrder.class)
                .eq(TChargingOrder::getAppUserId, userId)
                .eq(TChargingOrder::getStatus, 3));
                .in(TChargingOrder::getStatus, Arrays.asList(1,2,3,4)));
        List<Integer> gunIds = list.stream().map(TChargingOrder::getChargingGunId).collect(Collectors.toList());
        return R.ok(gunIds);
    }
    private static List<TChargingOrder> getSampleData() {
        // 这里可以替换为实际查询逻辑
        List<TChargingOrder> list = new ArrayList<>();
        // 示例数据
        for (int i = 0; i < 24; i++) {
            TChargingOrder order = new TChargingOrder();
            order.setStartTime(LocalDateTime.now().minusHours(23 - i));
            order.setOrderAmount(BigDecimal.valueOf(i + 1));
            list.add(order);
        }
        return list;
    }
    private static List<Map<String, BigDecimal>> processData(List<TChargingOrder> list) {
        Map<LocalDateTime, BigDecimal> hourlySum = new HashMap<>();
        // 按每个小时分组并求和
        for (TChargingOrder order : list) {
            LocalDateTime hour = order.getStartTime().truncatedTo(ChronoUnit.HOURS);
            BigDecimal amount = order.getOrderAmount();
            hourlySum.merge(hour, amount, BigDecimal::add);
        }
        // 创建结果列表
        List<Map<String, BigDecimal>> resultList = new ArrayList<>();
        for (int i = 1; i <= 23; i++) {
            LocalDateTime keyHour = LocalDateTime.now().withHour(i);
            BigDecimal sum = BigDecimal.ZERO;
            // 计算键之后的一小时的数据之和
            for (int j = i + 1; j <= 23; j++) {
                LocalDateTime nextHour = LocalDateTime.now().withHour(j);
                sum = sum.add(hourlySum.getOrDefault(nextHour, BigDecimal.ZERO));
            }
            Map<String, BigDecimal> entry = new HashMap<>();
            entry.put(String.valueOf(i), sum);
            resultList.add(entry);
        }
        return resultList;
    }
    /**
@@ -1404,9 +2184,11 @@
     */
    @PostMapping("/endCharge")
    public void endCharge(@RequestParam("code") String code){
        log.error(code + ":-------------------充电桩自动结束充电-------------------");
        log.info(code + ":-------------------充电桩自动结束充电-------------------");
        chargingOrderService.endCharge(code, 2);
    }
    /**
     * 硬件异常结束充电后的处理逻辑
@@ -1414,7 +2196,7 @@
     */
    @PostMapping("/excelEndCharge")
    public void excelEndCharge(@RequestParam("code") String code){
        log.error(code + ":-------------------充电异常,停止充电-------------------");
        log.info(code + ":-------------------充电异常,停止充电-------------------");
        chargingOrderService.excelEndCharge(code);
    }
@@ -1429,6 +2211,8 @@
        TChargingOrder chargingOrder = chargingOrderService.getChargingOrderByLicensePlate(query);
        return R.ok(chargingOrder);
    }
    /**
     * 修改充电订单
     * @param chargingOrder
@@ -1451,4 +2235,150 @@
        EndOfChargePageInfo endOfChargePageInfo = chargingOrderService.getEndOfChargePageInfo(id);
        return AjaxResult.success(endOfChargePageInfo);
    }
    /**
     * 获取订单数据
     * @param order
     * @return
     */
    @PostMapping("/getChargingOrder")
    public R<List<TChargingOrder>> getChargingOrder(@RequestBody TChargingOrderVo order){
        List<TChargingOrder> chargingOrder = chargingOrderService.getChargingOrder(order);
        return R.ok(chargingOrder);
    }
    /**
     * 根据车辆id获取指定时间范围内的数据
     * @param carId
     * @param startTime
     * @param endTime
     * @return
     */
    @PostMapping("/getCarChargingOrder")
    public R<List<TChargingOrder>> getCarChargingOrder(@RequestParam("carId") Long carId, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime){
        List<TChargingOrder> list = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>().eq(TChargingOrder::getAppUserCarId, carId).eq(TChargingOrder::getDelFlag, 0)
                .in(TChargingOrder::getStatus, Arrays.asList(4, 5)).between(TChargingOrder::getStartTime, startTime, endTime));
        return R.ok(list);
    }
    /**
     * 根据车牌号查询指定时间范围内的数据
     * @param plateNum
     * @param startTime
     * @param endTime
     * @return
     */
    @PostMapping("/getCarChargingOrderByPlateNum")
    public R<List<TChargingOrder>> getCarChargingOrderByPlateNum(@RequestParam("plateNum") String plateNum, @RequestParam("startTime") String startTime,
                                                          @RequestParam("endTime") String endTime){
        List<TChargingOrder> list = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>().eq(TChargingOrder::getPlateNum, plateNum).eq(TChargingOrder::getDelFlag, 0)
                .in(TChargingOrder::getStatus, Arrays.asList(4, 5)).between(TChargingOrder::getStartTime, startTime, endTime));
        return R.ok(list);
    }
    /**
     * 添加三方平台充电订单数据
     * @return
     */
    @PostMapping("/addTripartitePlatformOrder")
    public R addTripartitePlatformOrder(@RequestBody AddTripartitePlatformOrder query){
        return chargingOrderService.addTripartitePlatformOrder(query);
    }
    /**
     * 根据三方平台订单id获取充电数据
     * @param startChargeSeq
     * @return
     */
    @PostMapping("/getChargingOrderByStartChargeSeq")
    public R<TChargingOrder> getChargingOrderByStartChargeSeq(@RequestParam("startChargeSeq") String startChargeSeq){
        TChargingOrder chargingOrder = chargingOrderService.getOne(new LambdaQueryWrapper<TChargingOrder>().eq(TChargingOrder::getStartChargeSeq, startChargeSeq));
        return R.ok(chargingOrder);
    }
    /**
     * 根据三方平台订单ids获取充电数据
     * @param startChargeSeqs
     * @return
     */
    @PostMapping("/getChargingOrderByStartChargeSeqs")
    public R<List<TChargingOrder>> getChargingOrderByStartChargeSeqs(@RequestParam("startChargeSeqs") List<String> startChargeSeqs){
        List<TChargingOrder> list = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>().in(TChargingOrder::getStartChargeSeq, startChargeSeqs));
        return R.ok(list);
    }
    /**
     * 三方平台请求停止充电
     * @param startChargeSeq
     * @return
     */
    @PostMapping("/tripartitePlatformStopCharge")
    public R tripartitePlatformStopCharge(@RequestParam("startChargeSeq") String startChargeSeq){
        return chargingOrderService.tripartitePlatformStopCharge(startChargeSeq);
    }
    /**
     * 临时接口
     * 获取充电后没有扣除费用的数据
     * @return
     */
    @GetMapping("/getNotPaymentChargingOrder")
    public R getNotPaymentChargingOrder(){
        return chargingOrderService.getNotPaymentChargingOrder();
    }
    /**
     * 手动推送订单给三方平台
     * @param code
     * @return
     */
    @PostMapping("/pushOrderInfo")
    public R pushOrderInfo(@RequestParam String code){
        return chargingOrderService.pushOrderInfo(code);
    }
    /**
     * 添加汇总数据(临时)
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/addChargingOrderSummaryData")
    public R addChargingOrderSummaryData(){
        return chargingOrderService.addChargingOrderSummaryData();
    }
    /**
     * 充电桩数据大屏  新能源汽车电池安全检测次数统计
     */
    @ResponseBody
    @GetMapping(value = "/getStatisticsOfBattery")
    @ApiOperation(value = "新能源汽车电池安全检测次数统计", tags = {"充电桩数据大屏"})
    public R<StatisticsOfBatteryVO> getStatisticsOfBattery(){
        return chargingOrderService.getStatisticsOfBattery();
    }
    /**
     * 充电桩数据大屏  获取站点集合中总的充电量
     */
    @GetMapping("/getSumDegreeBySiteIds")
    public R<BigDecimal> getSumDegreeBySiteIds(@RequestParam("siteIds") List<Integer> SiteIds){
        return R.ok(chargingOrderService.getSumDegreeBySiteIds(SiteIds));
    }
}