Pu Zhibing
2024-10-16 c4664502dfdaffff555b532e65b51a57ac8b29c2
ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java
@@ -53,7 +53,9 @@
import com.ruoyi.order.dto.OrderEvaluateVo;
import com.ruoyi.order.dto.*;
import com.ruoyi.order.service.*;
import com.ruoyi.order.service.impl.TChargingOrderServiceImpl;
import com.ruoyi.order.util.PreviousSixMonths;
import com.ruoyi.order.vo.EndOfChargePageInfo;
import com.ruoyi.payment.api.feignClient.AliPaymentClient;
import com.ruoyi.payment.api.feignClient.WxPaymentClient;
import com.ruoyi.payment.api.vo.AliQueryOrder;
@@ -61,7 +63,10 @@
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.models.auth.In;
import jdk.nashorn.internal.runtime.ListAdapter;
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;
@@ -73,6 +78,7 @@
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;
import java.util.*;
@@ -92,6 +98,8 @@
@RestController
@RequestMapping("/t-charging-order")
public class TChargingOrderController {
    private Logger log = LoggerFactory.getLogger(TChargingOrderController.class);
    @Resource
    private TChargingOrderService chargingOrderService;
@@ -136,10 +144,32 @@
    private AppUserCarClient appUserCarClient;
    @Resource
    private TChargingOrderAccountingStrategyService chargingOrderAccountingStrategyService;
    @Resource
    private TOrderInvoiceService invoiceService;
    /**
     * 远程调用根据枪id 查询最新的订单id 用户后台结束充电
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/queryOrderByGunId/{id}")
    public R<String> queryOrderByGunId(@PathVariable("id") String id) {
        List<Integer> integers = new ArrayList<>();
        integers.add(2);
        integers.add(3);
        integers.add(4);
        TChargingOrder one = chargingOrderService.lambdaQuery()
                .eq(TChargingOrder::getChargingGunId, id)
                .in(TChargingOrder::getStatus, integers)
                .one();
        if (one!=null){
            return R.ok(one.getId().toString());
        }
        return R.ok();
    }
    @ResponseBody
    @PostMapping(value = "/pay/order/list")
    @ApiOperation(value = "列表", tags = {"管理后台-支付订单-订单信息"})
@@ -321,10 +351,10 @@
     * @param
     * @return
     */
    @GetMapping(value = "/getCar")
    public R<Long> getCar() {
    @GetMapping(value = "/getCar/{id}")
    public R<Long> getCar(@PathVariable("id")String id) {
        List<TChargingOrder> list = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>()
                .eq(TChargingOrder::getAppUserId, tokenService.getLoginUserApplet().getUserId())
                .eq(TChargingOrder::getAppUserId, id)
                .isNotNull(TChargingOrder::getAppUserCarId));
        if (!list.isEmpty()){
            // 最近使用的车辆id
@@ -436,7 +466,31 @@
                                        @RequestParam("attach") String attach) {
        AjaxResult ajaxResult = chargingOrderService.chargingOrderCallback(1, out_trade_no, transaction_id, attach);
    }
    /**
     * 修改安全检测数据
     * @param securityDetection
     */
    @ResponseBody
    @PostMapping(value = "/securityDetection")
    public void securityDetection(@RequestBody SecurityDetectionVO securityDetection){
        log.error("-------------------安全检测数据-------------------:" + securityDetection);
        chargingOrderService.securityDetection(securityDetection);
    }
    /**
     * 远程启动充电应答
     * @param message
     */
    @ResponseBody
    @PostMapping(value = "/startChargeSuccessfully")
    public void startChargeSuccessfully(@RequestBody PlatformStartChargingReplyMessageVO message){
        log.error("-------------------远程启动充电请求应答-------------------:" + message);
        chargingOrderService.startChargeSuccessfully(message);
    }
    /**
     * 支付宝支付成功后的回调
@@ -466,10 +520,10 @@
     */
    @ResponseBody
    @PostMapping(value = "/chargingOrderStartupFailureWxRefund")
    public void chargingOrderStartupFailureWxRefund(@RequestParam("out_trade_no") String out_refund_no,
                                                    @RequestParam("out_trade_no") String refund_id,
                                                    @RequestParam("out_trade_no") String tradeState,
                                                    @RequestParam("out_trade_no") String success_time){
    public void chargingOrderStartupFailureWxRefund(@RequestParam("out_refund_no") String out_refund_no,
                                                    @RequestParam("refund_id") String refund_id,
                                                    @RequestParam("tradeState") String tradeState,
                                                    @RequestParam("success_time") String success_time){
        chargingOrderService.chargingOrderStartupFailureWxRefund(out_refund_no, refund_id, tradeState, success_time);
    }
    
@@ -512,6 +566,31 @@
    public AjaxResult stopCharging(@PathVariable String id) {
        return chargingOrderService.stopCharging(id);
    }
    /**
     * 停止充电应答处理逻辑
     * @param platformStopChargingReply
     */
    @PostMapping("/terminateSuccessfulResponse")
    public void terminateSuccessfulResponse(@RequestBody PlatformStopChargingReplyVO platformStopChargingReply){
        log.error("-------------------远程停止充电请求应答-------------------:" + platformStopChargingReply);
        chargingOrderService.terminateSuccessfulResponse(platformStopChargingReply);
    }
    /**
     * 停止充电返回账单后计算费用
     * @param vo
     */
    @PostMapping("/endChargeBillingCharge")
    public void endChargeBillingCharge(@RequestBody TransactionRecordMessageVO vo){
        log.error("-------------------停止充电返回账单后计算费用及修改业务状态-------------------:" + vo);
        chargingOrderService.endChargeBillingCharge(vo);
    }
    @ResponseBody
    @GetMapping(value = "/six/charge")
@@ -634,7 +713,10 @@
        for (UploadRealTimeMonitoringData uploadRealTimeMonitoringData : data1) {
            ChargingOrderAndUploadRealTimeMonitoringDataDto dataDto = new ChargingOrderAndUploadRealTimeMonitoringDataDto();
            BeanUtils.copyProperties(uploadRealTimeMonitoringData,dataDto);
            BeanUtils.copyProperties(map.get(uploadRealTimeMonitoringData.getCharging_pile_code()),dataDto);
            TChargingOrder tChargingOrder = map.get(uploadRealTimeMonitoringData.getCharging_pile_code());
            if (tChargingOrder!=null) {
                BeanUtils.copyProperties(tChargingOrder, dataDto);
            }
            dtos.add(dataDto);
        }
@@ -705,16 +787,16 @@
            // 获取本月1号的日期
            YearMonth yearMonth = YearMonth.from(today);
            start = yearMonth.atDay(1);
            System.out.println("本月1号是: " + start);
//            start = yearMonth.atDay(1);
//
//            System.out.println("本月1号是: " + start);
        }else if (statisticsQueryDto.getDayType()==4){
            LocalDate today = LocalDate.now();
            // 获取当前年份
            int currentYear = today.getYear();
            // 获取今年1月1日的日期
            start = LocalDate.of(currentYear, 1, 1);
            System.out.println("今年1月1日是: " + start);
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
        }else if (statisticsQueryDto.getDayType()==5){
            // 获取今年1月1日的日期
@@ -789,9 +871,73 @@
        //上方折现
        if (statisticsQueryDto.getDayType()==1){
        List<Map<String,Object>> map = chargingOrderService.usersDay();
        tCharingUserMapVO.setMap(map);
            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(map, time);
                if (mapWithTimeValue!=null){
                    charMap.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("counts", 0);
                    charMap.add(timeMap);
                }
            }
            List<Map<String,Object>> map1 = chargingOrderService.usersDay1();
            List<Map<String, Object>> charMap1 = 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(map1, time);
                if (mapWithTimeValue!=null){
                    charMap1.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("counts", 0);
                    charMap1.add(timeMap);
                }
            }
        tCharingUserMapVO.setMap(charMap);
        tCharingUserMapVO.setMap1(charMap1);
        }else {
            List<Map<String,Object>> map =  chargingOrderService.usersByQuery(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(map, formattedDate);
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("counts", 0);
                    dateRangeStatistics.add(dateMap);
                }
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
            tCharingUserMapVO.setMap(map);
        }
@@ -880,18 +1026,37 @@
        List<Map<String,Object>> equipmentMap1 = chargingOrderService.equipmentUserType1(siteIds,statisticsQueryDto);
        //交流可用率
        List<Map<String,Object>> equipmentMap2= chargingOrderService.equipmentUserType2(siteIds,statisticsQueryDto);
        //取出直流可用率和交流可用率的percent的平均值保留两位小数
        double average1 = calculateAveragePercent(equipmentMap1, equipmentMap2);
        System.out.printf("The average percent is: %.2f\n", average1);
        //直流故障率
        List<Map<String,Object>> equipmentMapbroke1 = chargingOrderService.equipmentMapbroke1(siteIds,statisticsQueryDto);
        //交流故障率
        List<Map<String,Object>> equipmentMapbroke2 = chargingOrderService.equipmentMapbroke2(siteIds,statisticsQueryDto);
        double average2 = calculateAveragePercent(equipmentMapbroke1, equipmentMapbroke2);
        System.out.printf("The average percent is: %.2f\n", average2);
        //直流离网率
        List<Map<String,Object>> equipmentMapOut1 = chargingOrderService.equipmentMapOut1(siteIds,statisticsQueryDto);
        //交流离网率
        List<Map<String,Object>> equipmentMapOut2 = chargingOrderService.equipmentMapOut2(siteIds,statisticsQueryDto);
        double average3 = calculateAveragePercent(equipmentMapOut1, equipmentMapOut2);
        System.out.printf("The average percent is: %.2f\n", average3);
        //需求电流满足率
        List<Map<String,Object>>  needElec =  chargingOrderService.needElec(siteIds,statisticsQueryDto);
        List<Map<String,Object>>  needElec1 =  chargingOrderService.needElec(siteIds,statisticsQueryDto);
        List<Map<String,Object>>  needElec2 =  chargingOrderService.needElec1(siteIds,statisticsQueryDto);
        double average4 = calculateAveragePercent(needElec1, needElec2);
        System.out.printf("The average percent is: %.2f\n", average4);
        TCharingUserEquimentVO tCharingUserEquimentVO = new TCharingUserEquimentVO();
        tCharingUserEquimentVO.setEquipmentMap1(equipmentMap1);
@@ -900,10 +1065,40 @@
        tCharingUserEquimentVO.setEquipmentMapbroke2(equipmentMapbroke2);
        tCharingUserEquimentVO.setEquipmentMapOut1(equipmentMapOut1);
        tCharingUserEquimentVO.setEquipmentMapOut2(equipmentMapOut2);
        tCharingUserEquimentVO.setNeedElec(needElec);
        tCharingUserEquimentVO.setNeedElec1(needElec1);
        tCharingUserEquimentVO.setNeedElec2(needElec2);
        tCharingUserEquimentVO.setAverage1(average1);
        tCharingUserEquimentVO.setAverage2(average2);
        tCharingUserEquimentVO.setAverage3(average3);
        tCharingUserEquimentVO.setAverage4(average4);
        return R.ok(tCharingUserEquimentVO);
    }
    private static double calculateAveragePercent(List<Map<String, Object>> mapList1, List<Map<String, Object>> mapList2) {
        int totalElements = mapList1.size() + mapList2.size();
        double sum = 0.0;
        // 累加两个列表中所有元素的 "percent" 值
        for (Map<String, Object> map : mapList1) {
            if (map.containsKey("percent")) {
                sum += Double.parseDouble((String) map.get("percent"));
            }
        }
        for (Map<String, Object> map : mapList2) {
            if (map.containsKey("percent")) {
                sum += Double.parseDouble((String) map.get("percent"));
            }
        }
        // 防止除以零错误
        if (totalElements == 0) {
            return 0.0;
        }
        // 计算平均值
        return sum / totalElements;
    }
    @ResponseBody
    @PostMapping(value = "/work/charge")
@@ -978,11 +1173,67 @@
            }
          return R.ok(charMap);
        }else if (statisticsQueryDto.getDayType()==2){
            List<Map<String,Object>> charMap =  chargingOrderService.getDateType(siteIds,statisticsQueryDto);
            return R.ok(charMap);
            // 假设 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>> charMap =  chargingOrderService.getMonthType(siteIds,statisticsQueryDto);
            return R.ok(charMap);
            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);
            }
            return R.ok(dateRangeStatistics);
        }
        return R.ok();
@@ -999,13 +1250,21 @@
        return null; // 如果没有找到,返回 null
    }
    private Map<String, Object> findMapWithDateValue(List<Map<String, Object>> list, String date) {
        for (Map<String, Object> map : list) {
            if (date.equals(map.get("time"))) {
                return map;
            }
        }
        return null;
    }
    @ResponseBody
    @PostMapping(value = "/work/use")
    @ApiOperation(value = "运营情况", tags = {"管理后台-工作台"})
    @ApiOperation(value = "利用率", tags = {"管理后台-工作台"})
    public R workUse(@RequestBody ChargingDetailQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
@@ -1029,13 +1288,39 @@
            BigDecimal result = chargingCapacity.divide(totalRatedPower, 2, RoundingMode.HALF_UP);
            map.put("chargingCapacity", result);
        });
        return R.ok(capMap);
        //
        // 解析 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(capMap, formattedDate);
            if (dailyStats != null) {
                dateRangeStatistics.add(dailyStats);
            } else {
                Map<String, Object> dateMap = new HashMap<>();
                dateMap.put("time", formattedDate);
                dateMap.put("chargingCapacity", 0);
                dateRangeStatistics.add(dateMap);
            }
            // 移动到下一天
            startDate = startDate.plusDays(1);
        }
        return R.ok(dateRangeStatistics);
    }
    @Resource
    private TOrderInvoiceService invoiceService;
    @ResponseBody
    @GetMapping(value = "/work/shopOrder")
    @ApiOperation(value = "购物订单统计", tags = {"管理后台-工作台"})
@@ -1068,14 +1353,18 @@
            return R.ok(userMap);
    }
    public static void main(String[] args) {
        // 示例数据
        List<TChargingOrder> list = getSampleData();
        System.err.println(list);
        List<Map<String, BigDecimal>> result = processData(list);
        result.forEach(System.out::println);
    @GetMapping(value = "/getGunIdsByUserId")
    @ApiOperation(value = "查询当前用户正在充电中的枪id集合", tags = {"小程序-首页-用户充电订单信息"})
    public R<List<Integer>> getGunIdsByUserId() {
        Long userId = tokenService.getLoginUserApplet().getUserId();
        List<TChargingOrder> list = chargingOrderService.list(Wrappers.lambdaQuery(TChargingOrder.class)
                .eq(TChargingOrder::getAppUserId, userId)
                .eq(TChargingOrder::getStatus, 3));
        List<Integer> gunIds = list.stream().map(TChargingOrder::getChargingGunId).collect(Collectors.toList());
        return R.ok(gunIds);
    }
    private static List<TChargingOrder> getSampleData() {
@@ -1128,6 +1417,7 @@
     */
    @PostMapping("/endCharge")
    public void endCharge(@RequestParam("code") String code){
        log.error(code + ":-------------------充电桩自动结束充电-------------------");
        chargingOrderService.endCharge(code, 2);
    }
@@ -1137,6 +1427,7 @@
     */
    @PostMapping("/excelEndCharge")
    public void excelEndCharge(@RequestParam("code") String code){
        log.error(code + ":-------------------充电异常,停止充电-------------------");
        chargingOrderService.excelEndCharge(code);
    }
@@ -1161,4 +1452,16 @@
        chargingOrderService.updateById(chargingOrder);
        return R.ok();
    }
    @ResponseBody
    @GetMapping(value = "/getEndOfChargePageInfo/{id}")
    @ApiOperation(value = "获取充电结束页面数据", tags = {"小程序-扫一扫"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", required = true)
    })
    public AjaxResult<EndOfChargePageInfo> getEndOfChargePageInfo(@PathVariable("id") String id){
        EndOfChargePageInfo endOfChargePageInfo = chargingOrderService.getEndOfChargePageInfo(id);
        return AjaxResult.success(endOfChargePageInfo);
    }
}