From 3650ce7f5d42d1bef58abea9693f20d1f209d3b0 Mon Sep 17 00:00:00 2001
From: puzhibing <393733352@qq.com>
Date: 星期六, 10 十月 2026 14:02:27 +0800
Subject: [PATCH] 修改bug

---
 ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java |  905 +++++++++++++++++++++++++++++++++++++++++++++-----------
 1 files changed, 720 insertions(+), 185 deletions(-)

diff --git a/ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java b/ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java
index 54fb61d..40ef089 100644
--- a/ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java
+++ b/ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java
@@ -15,8 +15,10 @@
 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.feignClient.AppUserTagClient;
 import com.ruoyi.account.api.model.TAppUser;
 import com.ruoyi.account.api.model.TAppUserCar;
+import com.ruoyi.account.api.model.TAppUserTag;
 import com.ruoyi.chargingPile.api.domain.SiteMenu;
 import com.ruoyi.chargingPile.api.dto.GetSiteListDTO;
 import com.ruoyi.chargingPile.api.feignClient.*;
@@ -25,7 +27,6 @@
 import com.ruoyi.chargingPile.api.model.TChargingGun;
 import com.ruoyi.chargingPile.api.model.TChargingPile;
 import com.ruoyi.chargingPile.api.model.TParkingRecord;
-import com.ruoyi.chargingPile.api.model.TPartnerAppUser;
 import com.ruoyi.chargingPile.api.vo.GetChargingGunByChargingPileIdsVo;
 import com.ruoyi.common.core.domain.R;
 import com.ruoyi.common.core.dto.ChargingOrderGroup;
@@ -41,6 +42,7 @@
 import com.ruoyi.common.core.web.domain.AjaxResult;
 import com.ruoyi.common.core.web.page.PageInfo;
 import com.ruoyi.order.api.dto.ChargingStatisticeDTO;
+import com.ruoyi.order.api.dto.DeviceStartChargingDTO;
 import com.ruoyi.order.api.model.*;
 import com.ruoyi.order.api.query.ChargingOrderQuery;
 import com.ruoyi.common.core.dto.MongoChargingOrderQuery;
@@ -56,6 +58,7 @@
 import com.ruoyi.order.dto.MyChargingOrderList;
 import com.ruoyi.order.dto.OrderEvaluateVo;
 import com.ruoyi.order.dto.*;
+import com.ruoyi.order.mapper.TChargingOrderMapper;
 import com.ruoyi.order.export.PayOrderExport;
 import com.ruoyi.order.export.EnterpriseChargingDetailExport;
 import com.ruoyi.order.service.*;
@@ -71,10 +74,12 @@
 import com.ruoyi.order.vo.WatchChargingOrderVo;
 import com.ruoyi.other.api.feignClient.RoleSiteClient;
 import com.ruoyi.other.api.feignClient.UserSiteClient;
+import com.ruoyi.other.api.feignClient.UserTagClient;
 import com.ruoyi.other.api.feignClient.VipClient;
 import com.ruoyi.other.api.feignClient.OtherClient;
 import com.ruoyi.other.api.domain.TCompany;
 import com.ruoyi.other.api.domain.TVip;
+import com.ruoyi.other.api.domain.TUserTag;
 import com.ruoyi.payment.api.feignClient.AliPaymentClient;
 import com.ruoyi.payment.api.feignClient.WxPaymentClient;
 import com.ruoyi.payment.api.vo.IcbcPaymentResp;
@@ -98,6 +103,9 @@
 import java.time.format.DateTimeFormatter;
 import java.util.*;
 import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.stream.Collectors;
 
 import com.ruoyi.common.core.utils.DateUtils;
@@ -121,6 +129,10 @@
 
     @Resource
     private TChargingOrderService chargingOrderService;
+    @Resource
+    private TCardChargingOrderService cardChargingOrderService;
+    @Resource
+    private TVinChargingOrderService vinChargingOrderService;
     @Autowired
     private TokenService tokenService;
     @Autowired
@@ -162,6 +174,10 @@
     @Resource
     private AppUserCarClient appUserCarClient;
     @Resource
+    private AppUserTagClient appUserTagClient;
+    @Resource
+    private UserTagClient userTagClient;
+    @Resource
     private TChargingOrderAccountingStrategyService chargingOrderAccountingStrategyService;
     
     @Resource
@@ -187,57 +203,139 @@
     @Resource
     private SysUserRoleClient sysUserRoleClient;
 
+    @Resource
+    private TChargingOrderMapper chargingOrderMapper;
+
+    /** 尖峰平谷反查分块 id 上限:MyCat/druid 对 IN 列表的解析路由成本随 id 数非线性增长
+     *  (实测 500 个约 5s、5000 个 70s+ 触发读超时;100 个内约 0.2s/块,约 2ms/个)。 */
+    private static final int PHASE_ID_BATCH_SIZE = 100;
+    /** 尖峰平谷分块反查并发度:46k id 实测 ~20s,典型加盟商 <3s(串行 5000/块 >70s 读超时)。 */
+    private static final ExecutorService PHASE_QUERY_EXECUTOR = Executors.newFixedThreadPool(16);
+
     @GetMapping("/reservationRecommendation")
     @ApiOperation(value = "获取站点预约充电推荐时段", tags = {"管理后台-充电桩信息"})
     public R<ReservationRecommendationVO> getReservationRecommendation(@RequestParam Integer siteId) {
         return R.ok(chargingOrderService.getReservationRecommendation(siteId));
     }
 
-    /** 小程序加盟商看板:站点范围始终从登录账号绑定关系解析。 */
+    /** 小程序加盟商看板:站点范围始终从登录账号绑定关系解析。聚合查询下推到分片,避免全量拉订单。 */
     @PostMapping("/app/franchisee/charge-data")
     public R<Map<String, Object>> franchiseeChargeData(@RequestBody(required = false) Map<String, Object> params) {
-        List<TChargingOrder> orders = franchiseeOrders(params);
+        List<Integer> siteIds = franchiseeSiteIds(params);
         LocalDateTime[] range = franchiseeRange(params);
+        List<FranchiseeDayStat> dayStats = franchiseeDayStats(siteIds, range);
+        List<Map<String, Object>> managementOrderStats = franchiseeManagementOrderStats(siteIds, range);
         Map<String, Object> summary = new LinkedHashMap<>();
-        summary.put("orderAmountWan", sum(orders, TChargingOrder::getOrderAmount).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
-        summary.put("serviceFeeWan", sum(orders, TChargingOrder::getServiceCharge).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
-        summary.put("chargingPowerWan", sum(orders, TChargingOrder::getChargingCapacity).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
-        summary.put("chargingAmount", sum(orders, TChargingOrder::getPaymentAmount));
-        summary.put("chargingOrderCount", orders.size());
-        summary.put("powerUtilizationRate", observedPowerUtilization(orders));
-        summary.put("demandPowerSatisfactionRate", demandPowerSatisfaction(orders));
+        BigDecimal incomeWan = franchiseeIncomeWan(dayStats);
+        BigDecimal totalChargingCapacityWan = sum(dayStats, FranchiseeDayStat::getCapacity).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP);
+        summary.put("incomeWan", incomeWan);
+        summary.put("orderAmountWan", incomeWan);
+        summary.put("serviceFeeWan", sum(dayStats, FranchiseeDayStat::getServiceFee).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
+        summary.put("totalChargingCapacityWan", totalChargingCapacityWan);
+        summary.put("chargingPowerWan", totalChargingCapacityWan);
+        summary.put("chargingAmount", sumManagementOrderField(managementOrderStats, "paymoney"));
+        summary.put("chargingOrderCount", sumManagementOrderField(managementOrderStats, "orderCount").longValue());
+        summary.put("powerUtilizationRate", observedPowerUtilization(dayStats));
+        summary.put("demandPowerSatisfactionRate", demandPowerSatisfaction(dayStats));
         Map<String, Object> result = new LinkedHashMap<>();
         result.put("summary", summary);
-        result.put("keyDataLine", franchiseeDailyTrend(orders, range, "订单金额", order -> firstNonNull(order.getOrderAmount(), order.getPaymentAmount())));
-        result.put("keyDataRing", franchiseePhaseRing(orders));
-        result.put("orderStats", franchiseeOrderTrend(orders, range));
-        result.put("efficiency", franchiseeEfficiencyTrend(orders, range));
-        result.put("powerDistribution", franchiseePowerDistribution(orders));
+        result.put("keyDataLine", franchiseeDailyTrend(dayStats, range, "收入合计", FranchiseeDayStat::getChargingIncome));
+        result.put("keyDataRing", franchiseePhaseRing(siteIds, range));
+        result.put("orderStats", franchiseeManagementOrderTrend(managementOrderStats));
+        result.put("efficiency", franchiseeEfficiencyTrend(dayStats, range));
+        result.put("powerDistribution", franchiseePowerDistribution(siteIds, range));
         return R.ok(result);
     }
 
     @PostMapping("/app/franchisee/income")
     public R<Map<String, Object>> franchiseeIncome(@RequestBody(required = false) Map<String, Object> params) {
         List<Integer> siteIds = franchiseeSiteIds(params);
-        LocalDate firstMonth = YearMonth.now().minusMonths(5).atDay(1);
-        LocalDate nextMonth = YearMonth.now().plusMonths(1).atDay(1);
-        List<TChargingOrder> orders = franchiseeOrders(siteIds, firstMonth.atStartOfDay(), nextMonth.atStartOfDay());
+        List<SixChargingDto> sixChargingDtos;
+        if (siteIds.isEmpty()) {
+            // 无授权站点:返回近6月全零骨架,避免空 IN 导致全站点统计
+            sixChargingDtos = generateLastSixMonths(LocalDate.now());
+        } else {
+            // 与后台 数据分析-平台总收入分析 电站收入分析口径一致:历史月读结算账单、当月补原始订单
+            LocalDate sixBefore = PreviousSixMonths.get();
+            List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds, false);
+            LocalDate statisticsEndMonth = resolveStatisticsEndMonth(LocalDate.now(), chargingDtos);
+            sixChargingDtos = generateLastSixMonths(statisticsEndMonth);
+            for (SixChargingDto sixChargingDto : sixChargingDtos) {
+                for (SixChargingDto chargingDto : chargingDtos) {
+                    if (sixChargingDto.getMonth().equals(chargingDto.getMonth())) {
+                        BeanUtils.copyProperties(chargingDto, sixChargingDto);
+                    }
+                }
+            }
+        }
+        BigDecimal electricity = sixChargingDtos.stream()
+                .filter(Objects::nonNull)
+                .map(SixChargingDto::getElectrovalence)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add);
+        BigDecimal service = sixChargingDtos.stream()
+                .filter(Objects::nonNull)
+                .map(SixChargingDto::getServiceCharge)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add);
         Map<String, Object> result = new LinkedHashMap<>();
-        result.put("totalIncome", sum(orders, TChargingOrder::getPaymentAmount));
-        result.put("electricityFee", sum(orders, TChargingOrder::getElectrovalence));
-        result.put("serviceFee", sum(orders, TChargingOrder::getServiceCharge));
-        result.put("incomeColumn", franchiseeIncomeTrend(orders, firstMonth, 6));
-        List<Map<String, Object>> incomePie = new ArrayList<>();
-        Map<String, Object> electricityItem = new LinkedHashMap<>();
-        electricityItem.put("name", "充电费");
-        electricityItem.put("value", sum(orders, TChargingOrder::getElectrovalence));
-        incomePie.add(electricityItem);
-        Map<String, Object> serviceItem = new LinkedHashMap<>();
-        serviceItem.put("name", "服务费");
-        serviceItem.put("value", sum(orders, TChargingOrder::getServiceCharge));
-        incomePie.add(serviceItem);
-        result.put("incomePie", incomePie);
+        result.put("totalIncome", electricity.add(service));
+        result.put("electricityFee", electricity);
+        result.put("serviceFee", service);
+        result.put("incomeColumn", franchiseeIncomeTrendFromSix(sixChargingDtos));
+        // 电站收入占比:口径与后台 /six/circle 一致(近6月结算账单按站点分组,电费+服务费-三方佣金)
+        result.put("incomePie", franchiseeIncomePieBySite(siteIds));
         return R.ok(result);
+    }
+
+    /** 加盟商看板"电站收入占比":复用 /six/circle 统计口径,按金额降序返回站点占比列表 */
+    private List<Map<String, Object>> franchiseeIncomePieBySite(List<Integer> siteIds) {
+        List<Map<String, Object>> incomePie = new ArrayList<>();
+        if (siteIds == null || siteIds.isEmpty()) {
+            return incomePie;
+        }
+        List<SixCircleDto> circleDtos = chargingOrderService.circle(siteIds, PreviousSixMonths.get(), false);
+        if (circleDtos == null || circleDtos.isEmpty()) {
+            return incomePie;
+        }
+        // 站点名批量映射,避免逐个远程调用
+        Map<Integer, String> siteNameMap = new HashMap<>();
+        R<List<Site>> siteResult = siteClient.getSiteAll();
+        List<Site> sites = siteResult == null ? null : siteResult.getData();
+        if (sites != null) {
+            for (Site site : sites) {
+                if (site != null && site.getId() != null) {
+                    siteNameMap.put(site.getId(), site.getName());
+                }
+            }
+        }
+        circleDtos.sort((a, b) -> {
+            BigDecimal amountA = a == null || a.getPaymentAmount() == null ? BigDecimal.ZERO : a.getPaymentAmount();
+            BigDecimal amountB = b == null || b.getPaymentAmount() == null ? BigDecimal.ZERO : b.getPaymentAmount();
+            return amountB.compareTo(amountA);
+        });
+        // 总额用于计算各站点占比,name+value 为服务端拼好的饼图标签文本(站点名 xx.x%)
+        BigDecimal total = BigDecimal.ZERO;
+        for (SixCircleDto dto : circleDtos) {
+            if (dto != null && dto.getPaymentAmount() != null) {
+                total = total.add(dto.getPaymentAmount());
+            }
+        }
+        for (SixCircleDto dto : circleDtos) {
+            if (dto == null || dto.getSiteId() == null || dto.getPaymentAmount() == null) {
+                continue;
+            }
+            Map<String, Object> item = new LinkedHashMap<>();
+            String name = siteNameMap.getOrDefault(dto.getSiteId(), "电站" + dto.getSiteId());
+            item.put("name", name);
+            item.put("value", dto.getPaymentAmount());
+            String percent = total.compareTo(BigDecimal.ZERO) > 0
+                    ? dto.getPaymentAmount().multiply(BigDecimal.valueOf(100)).divide(total, 1, RoundingMode.HALF_UP).toPlainString()
+                    : "0.0";
+            item.put("name+value", name + " " + percent + "%");
+            incomePie.add(item);
+        }
+        return incomePie;
     }
 
     @PostMapping("/app/franchisee/user")
@@ -245,20 +343,29 @@
         Partner partner = franchiseePartner();
         List<Integer> siteIds = partner == null ? Collections.emptyList() : franchiseeSiteIds(params, partner.getId());
         LocalDateTime[] range = franchiseeRange(params);
-        List<TChargingOrder> orders = franchiseeOrders(siteIds, range[0], range[1]).stream()
-                .filter(order -> Objects.equals(order.getStatus(), 5))
-                .collect(Collectors.toList());
-        Set<Long> users = orders.stream().map(TChargingOrder::getAppUserId).filter(Objects::nonNull).collect(Collectors.toSet());
-        List<TPartnerAppUser> relations = Collections.emptyList();
-        if (partner != null && partner.getId() != null) {
-            R<List<TPartnerAppUser>> relationResult = partnerClient.getBoundAppUserRelations(partner.getId());
-            if (relationResult != null && relationResult.getData() != null) {
-                relations = relationResult.getData();
+        List<FranchiseeUserAgg> aggs = franchiseeUserAggs(siteIds, range);
+        Map<LocalDate, Set<Long>> chargingUsersByDay = new LinkedHashMap<>();
+        for (FranchiseeUserAgg agg : aggs) {
+            if (agg == null || agg.getAppUserId() == null || agg.getStatDay() == null) {
+                continue;
+            }
+            chargingUsersByDay.computeIfAbsent(agg.getStatDay(), key -> new HashSet<>()).add(agg.getAppUserId());
+        }
+        Map<LocalDate, Long> newUsersByDay = new LinkedHashMap<>();
+        if (siteIds != null && !siteIds.isEmpty() && range != null && range[0] != null && range[1] != null) {
+            List<FranchiseeUserFirstCharge> firstCharges = chargingOrderMapper.franchiseeUserFirstChargedDays(siteIds, range[0], range[1]);
+            if (firstCharges != null) {
+                for (FranchiseeUserFirstCharge fc : firstCharges) {
+                    if (fc != null && fc.getAppUserId() != null && fc.getFirstChargedDay() != null) {
+                        newUsersByDay.merge(fc.getFirstChargedDay(), 1L, Long::sum);
+                    }
+                }
             }
         }
-        FranchiseeUserStatistics.Result userStatistics = FranchiseeUserStatistics.calculate(
-                orders, relations, range[0], range[1]);
+        FranchiseeUserStatistics.Result userStatistics = FranchiseeUserStatistics.calculateByUserDays(
+                chargingUsersByDay, newUsersByDay, range[0], range[1]);
 
+        Set<Long> users = aggs.stream().map(FranchiseeUserAgg::getAppUserId).filter(Objects::nonNull).collect(Collectors.toSet());
         List<TAppUser> appUsers = Collections.emptyList();
         if (!users.isEmpty()) {
             R<List<TAppUser>> userResult = appUserClient.getUserByIds(new ArrayList<>(users));
@@ -267,7 +374,7 @@
         Map<Long, TAppUser> userMap = appUsers.stream().filter(user -> user.getId() != null)
                 .collect(Collectors.toMap(TAppUser::getId, user -> user, (left, right) -> left));
 
-        List<Long> carIds = orders.stream().map(TChargingOrder::getAppUserCarId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
+        List<Long> carIds = aggs.stream().map(FranchiseeUserAgg::getAppUserCarId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
         List<TAppUserCar> cars = Collections.emptyList();
         if (!carIds.isEmpty()) {
             R<List<TAppUserCar>> carResult = appUserCarClient.getCarByIds(carIds);
@@ -278,18 +385,18 @@
         Map<String, Object> result = new LinkedHashMap<>();
         result.put("summary", userStatistics.getSummary());
         result.put("userStats", userStatistics.getTrend());
-        result.put("userTags", franchiseeUserTags(orders));
+        result.put("userTags", franchiseeUserTags(aggs));
         Map<Integer, String> vipNames = new HashMap<>();
         R<List<TVip>> vipResult = vipClient.getAllVip();
         if (vipResult != null && vipResult.getData() != null) vipResult.getData().forEach(vip -> vipNames.put(vip.getId(), vip.getName()));
         result.put("memberType", franchiseeMemberTypes(appUsers, vipNames));
-        result.put("corpRank", franchiseeCompanyRank(orders, userMap));
+        result.put("corpRank", franchiseeCompanyRank(aggs, userMap));
         result.put("evaluation", evaluation.get("summary"));
         result.put("goodTags", evaluation.get("goodTags"));
         result.put("badTags", evaluation.get("badTags"));
-        result.put("traffic", franchiseeTraffic(orders));
-        result.put("vehicleClass", franchiseeCarGroup(cars, TAppUserCar::getVehicleUse, "未知用途", 5));
-        result.put("vehicleBrand", franchiseeCarGroup(cars, TAppUserCar::getVehicleBrand, "其他", 5));
+        result.put("traffic", franchiseeTraffic(siteIds, range));
+        result.put("vehicleClass", franchiseeOrderCarGroup(aggs, cars, TAppUserCar::getVehicleUse, "未知用途", 5));
+        result.put("vehicleBrand", franchiseeOrderCarGroup(aggs, cars, TAppUserCar::getVehicleBrand, "其他", 5));
         return R.ok(result);
     }
 
@@ -297,38 +404,93 @@
     public R<Map<String, Object>> franchiseeOperation(@RequestBody(required = false) Map<String, Object> params) {
         Map<String, Object> result = new LinkedHashMap<>();
         List<Integer> siteIds = franchiseeSiteIds(params);
-        List<TChargingPile> piles = Collections.emptyList();
-        if (!siteIds.isEmpty()) { R<List<TChargingPile>> pileResult = chargingPileClient.getChargingPileBySiteIds(siteIds); if (pileResult != null && pileResult.getData() != null) piles = pileResult.getData(); }
-        List<TChargingGun> guns = Collections.emptyList();
-        List<Integer> pileIds = piles.stream().map(TChargingPile::getId).filter(Objects::nonNull).collect(Collectors.toList());
-        if (!pileIds.isEmpty()) {
-            GetChargingGunByChargingPileIdsVo query = new GetChargingGunByChargingPileIdsVo(); query.setChargingPileIds(pileIds);
-            R<List<TChargingGun>> gunResult = chargingGunClient.getChargingGunByChargingPileIds(query);
-            if (gunResult != null && gunResult.getData() != null) guns = gunResult.getData();
+        LocalDateTime[] range = franchiseeRange(params);
+        ChargingStatisticsQueryDto query = new ChargingStatisticsQueryDto();
+        String dateType = params == null ? "today" : String.valueOf(params.getOrDefault("dateType", "today"));
+        int dayType = "week".equals(dateType) ? 2 : "month".equals(dateType) ? 3 : "year".equals(dateType) ? 4 : "custom".equals(dateType) ? 5 : 1;
+        query.setDayType(dayType);
+        if (dayType == 5) {
+            query.setStartTime(range[0].toLocalDate());
+            query.setEndTime(range[1].toLocalDate().minusDays(1));
         }
-        BigDecimal total = BigDecimal.valueOf(guns.size());
-        BigDecimal available = BigDecimal.valueOf(guns.stream().filter(this::isAvailableGun).count());
-        BigDecimal fault = countGuns(guns, 7), offline = countGuns(guns, 1);
-        List<TChargingOrder> operationOrders = franchiseeOrders(params);
-        BigDecimal powerSatisfaction = demandPowerSatisfaction(operationOrders);
-        Map<String, Object> summary = new LinkedHashMap<>(); summary.put("availableRate", rate(available, total)); summary.put("faultRate", rate(fault, total)); summary.put("offlineRate", rate(offline, total)); summary.put("powerSatisfactionRate", powerSatisfaction);
-        result.put("summary", summary); result.put("dcCharts", operationCharts(guns, operationOrders, true)); result.put("acCharts", operationCharts(guns, operationOrders, false));
+
+        List<Map<String, Object>> dcAvailable = safeList(chargingOrderService.equipmentUserType1(siteIds, query));
+        List<Map<String, Object>> acAvailable = safeList(chargingOrderService.equipmentUserType2(siteIds, query));
+        List<Map<String, Object>> dcFault = safeList(chargingOrderService.equipmentMapbroke1(siteIds, query));
+        List<Map<String, Object>> acFault = safeList(chargingOrderService.equipmentMapbroke2(siteIds, query));
+        List<Map<String, Object>> dcOffline = safeList(chargingOrderService.equipmentMapOut1(siteIds, query));
+        List<Map<String, Object>> acOffline = safeList(chargingOrderService.equipmentMapOut2(siteIds, query));
+        List<Map<String, Object>> dcSatisfaction = safeList(chargingOrderService.needElec(siteIds, query));
+        List<Map<String, Object>> acSatisfaction = safeList(chargingOrderService.needElec1(siteIds, query));
+        normalizeOperationPercents(dcAvailable);
+        normalizeOperationPercents(acAvailable);
+        normalizeOperationPercents(dcFault);
+        normalizeOperationPercents(acFault);
+        normalizeOperationPercents(dcOffline);
+        normalizeOperationPercents(acOffline);
+        normalizeOperationPercents(dcSatisfaction);
+        normalizeOperationPercents(acSatisfaction);
+
+        Map<String, Object> summary = new LinkedHashMap<>();
+        summary.put("availableRate", calculateAveragePercent(dcAvailable, acAvailable));
+        summary.put("faultRate", calculateAveragePercent(dcFault, acFault));
+        summary.put("offlineRate", calculateAveragePercent(dcOffline, acOffline));
+        summary.put("powerSatisfactionRate", calculateAveragePercent(dcSatisfaction, acSatisfaction));
+        result.put("summary", summary);
+        result.put("dcCharts", Arrays.asList(
+                operationChart(dcAvailable, "可用率"),
+                operationChart(dcFault, "故障率"),
+                operationChart(dcOffline, "离网率"),
+                operationChart(dcSatisfaction, "需求电流满足率")));
+        result.put("acCharts", Arrays.asList(
+                operationChart(acAvailable, "可用率"),
+                operationChart(acFault, "故障率"),
+                operationChart(acOffline, "离网率"),
+                operationChart(acSatisfaction, "需求电流满足率")));
         return R.ok(result);
     }
 
-    private List<TChargingOrder> franchiseeOrders(Map<String, Object> params) {
-        List<Integer> siteIds = franchiseeSiteIds(params);
-        if (siteIds.isEmpty()) return Collections.emptyList();
-        LocalDateTime[] range = franchiseeRange(params);
-        return franchiseeOrders(siteIds, range[0], range[1]);
+    private Map<String, Object> operationChart(List<Map<String, Object>> rows, String name) {
+        List<String> categories = rows.stream().map(row -> {
+            String gunName = row.get("name") == null ? "" : String.valueOf(row.get("name"));
+            return StringUtils.isBlank(gunName) ? "未命名充电枪" : gunName;
+        }).collect(Collectors.toList());
+        List<Object> values = rows.stream().map(row -> row.getOrDefault("percent", "0")).collect(Collectors.toList());
+        Map<String, Object> chart = new LinkedHashMap<>();
+        chart.put("categories", categories);
+        Map<String, Object> series = new LinkedHashMap<>();
+        series.put("name", name);
+        series.put("data", values);
+        chart.put("series", Collections.singletonList(series));
+        return chart;
     }
 
-    private List<TChargingOrder> franchiseeOrders(List<Integer> siteIds, LocalDateTime start, LocalDateTime end) {
-        if (siteIds == null || siteIds.isEmpty()) return Collections.emptyList();
-        LambdaQueryWrapper<TChargingOrder> query = Wrappers.lambdaQuery(TChargingOrder.class).in(TChargingOrder::getSiteId, siteIds).eq(TChargingOrder::getDelFlag, 0).eq(TChargingOrder::getRechargePaymentStatus, 2);
-        if (start != null) query.ge(TChargingOrder::getEndTime, start);
-        if (end != null) query.lt(TChargingOrder::getEndTime, end);
-        return chargingOrderService.list(query);
+    private void normalizeOperationPercents(List<Map<String, Object>> rows) {
+        for (Map<String, Object> row : rows) {
+            Object raw = row.get("percent");
+            try {
+                BigDecimal percent = raw == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(raw));
+                row.put("percent", percent.abs().toPlainString());
+            } catch (NumberFormatException ignored) {
+                row.put("percent", "0");
+            }
+        }
+    }
+
+    /** 加盟商看板按日聚合(siteIds 为空直接返回空,避免空 IN)。 */
+    private List<FranchiseeDayStat> franchiseeDayStats(List<Integer> siteIds, LocalDateTime[] range) {
+        if (siteIds == null || siteIds.isEmpty() || range == null || range[0] == null || range[1] == null) {
+            return Collections.emptyList();
+        }
+        return chargingOrderMapper.franchiseeDayStats(siteIds, range[0], range[1]);
+    }
+
+    /** 加盟商看板用户维度聚合(仅已结束订单;siteIds 为空直接返回空)。 */
+    private List<FranchiseeUserAgg> franchiseeUserAggs(List<Integer> siteIds, LocalDateTime[] range) {
+        if (siteIds == null || siteIds.isEmpty() || range == null || range[0] == null || range[1] == null) {
+            return Collections.emptyList();
+        }
+        return chargingOrderMapper.franchiseeUserAggs(siteIds, range[0], range[1]);
     }
 
     private List<Integer> franchiseeSiteIds(Map<String, Object> params) {
@@ -355,13 +517,39 @@
         return siteIds;
     }
 
-    private List<Map<String, Object>> franchiseeUserTags(List<TChargingOrder> orders) {
-        Map<Long, Long> counts = orders.stream().filter(order -> order.getAppUserId() != null)
-                .collect(Collectors.groupingBy(TChargingOrder::getAppUserId, Collectors.counting()));
-        long active = counts.values().stream().filter(count -> count >= 5).count();
-        long normal = counts.values().stream().filter(count -> count >= 2 && count < 5).count();
-        long lowFrequency = counts.values().stream().filter(count -> count == 1).count();
-        return namedCounts(new String[]{"活跃用户", "普通用户", "低频用户"}, new long[]{active, normal, lowFrequency});
+    private List<Map<String, Object>> franchiseeUserTags(List<FranchiseeUserAgg> aggs) {
+        Set<Long> userIds = aggs.stream()
+                .map(FranchiseeUserAgg::getAppUserId)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toSet());
+        if (userIds.isEmpty()) {
+            return Collections.emptyList();
+        }
+        R<List<TUserTag>> tagResult = userTagClient.getAllUserTag();
+        List<TUserTag> tags = tagResult == null || tagResult.getData() == null
+                ? Collections.emptyList() : tagResult.getData();
+        // 单次批量拉取全部用户标签关系(t_app_user_tag 分片键 app_user_id 精确路由),
+        // 避免原先 标签×用户 双层循环逐个远程调用导致接口 40s+。
+        R<List<TAppUserTag>> relationResult = appUserTagClient.listByUserIds(new ArrayList<>(userIds));
+        List<TAppUserTag> relations = relationResult == null || relationResult.getData() == null
+                ? Collections.emptyList() : relationResult.getData();
+        Map<Integer, Set<Long>> usersByTag = relations.stream()
+                .filter(relation -> relation.getUserTagId() != null && relation.getAppUserId() != null)
+                .collect(Collectors.groupingBy(TAppUserTag::getUserTagId,
+                        Collectors.mapping(TAppUserTag::getAppUserId, Collectors.toSet())));
+        Map<String, Long> counts = new LinkedHashMap<>();
+        for (TUserTag tag : tags) {
+            if (tag == null || tag.getId() == null || StringUtils.isBlank(tag.getName())) {
+                continue;
+            }
+            Set<Long> taggedUsers = usersByTag.get(tag.getId());
+            if (taggedUsers != null && !taggedUsers.isEmpty()) {
+                counts.put(tag.getName(), (long) taggedUsers.size());
+            }
+        }
+        return counts.entrySet().stream()
+                .map(entry -> namedCount(entry.getKey(), entry.getValue()))
+                .collect(Collectors.toList());
     }
 
     private List<Map<String, Object>> franchiseeMemberTypes(List<TAppUser> users, Map<Integer, String> vipNames) {
@@ -374,12 +562,12 @@
         return result;
     }
 
-    private Map<String, Object> franchiseeCompanyRank(List<TChargingOrder> orders, Map<Long, TAppUser> userMap) {
+    private Map<String, Object> franchiseeCompanyRank(List<FranchiseeUserAgg> aggs, Map<Long, TAppUser> userMap) {
         Map<Integer, BigDecimal> totals = new HashMap<>();
-        orders.forEach(order -> {
-            TAppUser user = userMap.get(order.getAppUserId());
+        aggs.forEach(agg -> {
+            TAppUser user = userMap.get(agg.getAppUserId());
             if (user != null && user.getCompanyId() != null) {
-                totals.merge(user.getCompanyId(), value(order.getChargingCapacity()), BigDecimal::add);
+                totals.merge(user.getCompanyId(), value(agg.getCapacity()), BigDecimal::add);
             }
         });
         List<Map.Entry<Integer, BigDecimal>> sorted = totals.entrySet().stream()
@@ -417,17 +605,38 @@
         result.put("goodTags", safeList(orderEvaluateService.goodTop(siteIds))); result.put("badTags", safeList(orderEvaluateService.badTop(siteIds))); return result;
     }
 
-    private List<Map<String, Object>> franchiseeTraffic(List<TChargingOrder> orders) {
-        Map<String, Long> counts = orders.stream().collect(Collectors.groupingBy(order -> {
-            String source = order.getTripartitePlatformName(); return source == null || source.isEmpty() ? "明星充电" : source;
-        }, Collectors.counting()));
-        return counts.entrySet().stream().map(entry -> namedCount(entry.getKey(), entry.getValue())).collect(Collectors.toList());
+    private List<Map<String, Object>> franchiseeTraffic(List<Integer> siteIds, LocalDateTime[] range) {
+        if (siteIds == null || siteIds.isEmpty() || range == null || range[0] == null || range[1] == null) {
+            return Collections.emptyList();
+        }
+        List<Map<String, Object>> result = new ArrayList<>();
+        chargingOrderMapper.franchiseeTrafficStats(siteIds, range[0], range[1]).forEach(stat -> {
+            if (stat == null || stat.getOrderCount() == null || stat.getOrderCount() == 0) {
+                return;
+            }
+            String source = stat.getSource() == null || stat.getSource().isEmpty() ? "明星充电" : stat.getSource();
+            result.add(namedCount(source, stat.getOrderCount()));
+        });
+        return result;
     }
 
-    private List<Map<String, Object>> franchiseeCarGroup(List<TAppUserCar> cars, java.util.function.Function<TAppUserCar, String> getter, String emptyName, int limit) {
-        Map<String, Long> counts = cars.stream().collect(Collectors.groupingBy(car -> {
-            String value = getter.apply(car); return value == null || value.trim().isEmpty() ? emptyName : value;
-        }, Collectors.counting()));
+    private List<Map<String, Object>> franchiseeOrderCarGroup(List<FranchiseeUserAgg> aggs,
+                                                               List<TAppUserCar> cars,
+                                                               java.util.function.Function<TAppUserCar, String> getter,
+                                                               String emptyName,
+                                                               int limit) {
+        Map<Long, TAppUserCar> carsById = cars.stream()
+                .filter(car -> car.getId() != null)
+                .collect(Collectors.toMap(TAppUserCar::getId, car -> car, (left, right) -> left));
+        Map<String, Long> counts = new HashMap<>();
+        aggs.forEach(agg -> {
+            if (agg == null || agg.getOrderCount() == null) {
+                return;
+            }
+            TAppUserCar car = agg.getAppUserCarId() == null ? null : carsById.get(agg.getAppUserCarId());
+            String value = car == null ? null : getter.apply(car);
+            counts.merge(value == null || value.trim().isEmpty() ? emptyName : value, agg.getOrderCount(), Long::sum);
+        });
         return counts.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).limit(limit)
                 .map(entry -> namedCount(entry.getKey(), entry.getValue())).collect(Collectors.toList());
     }
@@ -446,7 +655,7 @@
     private BigDecimal countGuns(List<TChargingGun> guns, int status) { return BigDecimal.valueOf(guns.stream().filter(gun -> Objects.equals(gun.getStatus(), status)).count()); }
     private boolean isAvailableGun(TChargingGun gun) { return gun.getStatus() != null && gun.getStatus() >= 2 && gun.getStatus() <= 6; }
     private BigDecimal rate(BigDecimal numerator, BigDecimal denominator) { return denominator.signum() == 0 ? BigDecimal.ZERO : numerator.multiply(BigDecimal.valueOf(100)).divide(denominator, 2, RoundingMode.HALF_UP); }
-    private List<Map<String, Object>> operationCharts(List<TChargingGun> guns, List<TChargingOrder> orders, boolean dc) {
+    private List<Map<String, Object>> operationCharts(List<TChargingGun> guns, Map<Integer, FranchiseeGunSat> gunSatMap, boolean dc) {
         List<TChargingGun> selected = guns.stream().filter(gun -> dc ? Objects.equals(gun.getType(), 4) : gun.getType() != null && gun.getType() >= 1 && gun.getType() <= 3).collect(Collectors.toList());
         List<Map<String, Object>> charts = new ArrayList<>();
         String[] keys = {"availableRate", "faultRate", "offlineRate", "powerSatisfactionRate"}; int[] statuses = {0, 7, 1, 0};
@@ -456,12 +665,20 @@
             List<String> categories = selected.stream().map(TChargingGun::getName).map(name -> name == null ? "未命名充电枪" : name).collect(Collectors.toList());
             final int metricIndex = i;
             List<BigDecimal> values = selected.stream().map(gun -> metricIndex == 3
-                    ? demandPowerSatisfaction(orders.stream().filter(order -> Objects.equals(order.getChargingGunId(), gun.getId())).collect(Collectors.toList()))
+                    ? gunSatisfaction(gunSatMap, gun.getId())
                     : BigDecimal.valueOf(metricIndex == 0 ? (isAvailableGun(gun) ? 100 : 0) : (Objects.equals(gun.getStatus(), status) ? 100 : 0))).collect(Collectors.toList());
             chart.put("categories", categories);
             Map<String, Object> series = new LinkedHashMap<>(); series.put("name", names[i]); series.put("data", values); chart.put("series", Collections.singletonList(series)); charts.add(chart);
         }
         return charts;
+    }
+
+    private BigDecimal gunSatisfaction(Map<Integer, FranchiseeGunSat> gunSatMap, Integer gunId) {
+        FranchiseeGunSat sat = gunId == null ? null : gunSatMap.get(gunId);
+        if (sat == null || sat.getSatCount() == null || sat.getSatCount() == 0) {
+            return BigDecimal.ZERO;
+        }
+        return value(sat.getSatSum()).divide(BigDecimal.valueOf(sat.getSatCount()), 2, RoundingMode.HALF_UP);
     }
 
     private LocalDateTime[] franchiseeRange(Map<String, Object> params) {
@@ -484,81 +701,179 @@
         return new LocalDateTime[]{today.atStartOfDay(), today.plusDays(1).atStartOfDay()};
     }
 
-    private BigDecimal sum(List<TChargingOrder> orders, java.util.function.Function<TChargingOrder, BigDecimal> getter) { return orders.stream().map(getter).map(this::value).reduce(BigDecimal.ZERO, BigDecimal::add); }
-    private BigDecimal firstNonNull(BigDecimal first, BigDecimal second) { return first != null ? first : value(second); }
+    static BigDecimal franchiseeIncomeWan(List<FranchiseeDayStat> stats) {
+        return stats.stream().map(FranchiseeDayStat::getChargingIncome)
+                .map(value -> value == null ? BigDecimal.ZERO : value)
+                .reduce(BigDecimal.ZERO, BigDecimal::add)
+                .divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP);
+    }
+
+    private <T> BigDecimal sum(List<T> items, java.util.function.Function<T, BigDecimal> getter) { return items.stream().map(getter).map(this::value).reduce(BigDecimal.ZERO, BigDecimal::add); }
     private BigDecimal value(BigDecimal value) { return value == null ? BigDecimal.ZERO : value; }
-    private Map<String, Object> franchiseeTrend(List<TChargingOrder> orders, String name, java.util.function.Function<TChargingOrder, BigDecimal> getter) { Map<String, Object> chart = new LinkedHashMap<>(); chart.put("categories", Collections.singletonList(LocalDate.now().toString())); Map<String, Object> series = new LinkedHashMap<>(); series.put("name", name); series.put("data", Collections.singletonList(sum(orders, getter))); chart.put("series", new ArrayList<>(Collections.singletonList(series))); return chart; }
-    private Map<String, Object> franchiseeDailyTrend(List<TChargingOrder> orders, LocalDateTime[] range, String name, java.util.function.Function<TChargingOrder, BigDecimal> getter) {
+    private Map<LocalDate, FranchiseeDayStat> dayStatByDay(List<FranchiseeDayStat> stats) {
+        return stats.stream().filter(stat -> stat != null && stat.getStatDay() != null)
+                .collect(Collectors.toMap(FranchiseeDayStat::getStatDay, stat -> stat, (left, right) -> left));
+    }
+    private Map<String, Object> franchiseeDailyTrend(List<FranchiseeDayStat> stats, LocalDateTime[] range, String name, java.util.function.Function<FranchiseeDayStat, BigDecimal> getter) {
+        Map<LocalDate, FranchiseeDayStat> byDay = dayStatByDay(stats);
         List<String> categories = new ArrayList<>(); List<BigDecimal> data = new ArrayList<>();
         LocalDate start = range[0] == null ? LocalDate.now() : range[0].toLocalDate();
         LocalDate end = range[1] == null ? start.plusDays(1) : range[1].toLocalDate();
         for (LocalDate day = start; day.isBefore(end); day = day.plusDays(1)) {
             categories.add(day.toString().substring(5));
-            LocalDateTime dayStart = day.atStartOfDay(), dayEnd = day.plusDays(1).atStartOfDay();
-            data.add(sum(orders.stream().filter(order -> order.getEndTime() != null && !order.getEndTime().isBefore(dayStart) && order.getEndTime().isBefore(dayEnd)).collect(Collectors.toList()), getter));
+            FranchiseeDayStat stat = byDay.get(day);
+            data.add(stat == null ? BigDecimal.ZERO : value(getter.apply(stat)));
         }
         Map<String, Object> chart = new LinkedHashMap<>(); chart.put("categories", categories);
         Map<String, Object> series = new LinkedHashMap<>(); series.put("name", name); series.put("data", data); chart.put("series", new ArrayList<>(Collections.singletonList(series))); return chart;
     }
-    private Map<String, Object> franchiseeOrderTrend(List<TChargingOrder> orders, LocalDateTime[] range) {
-        Map<String, Object> chart = franchiseeDailyTrend(orders, range, "充电金额", order -> firstNonNull(order.getPaymentAmount(), order.getOrderAmount()));
-        ((List<Map<String, Object>>) chart.get("series")).get(0).put("type", "column");
-        List<BigDecimal> countData = new ArrayList<>(); List<String> categories = (List<String>) chart.get("categories");
-        LocalDate start = range[0] == null ? LocalDate.now() : range[0].toLocalDate();
-        for (int i = 0; i < categories.size(); i++) { LocalDate day = start.plusDays(i); LocalDateTime dayStart = day.atStartOfDay(), dayEnd = day.plusDays(1).atStartOfDay(); countData.add(BigDecimal.valueOf(orders.stream().filter(order -> order.getEndTime() != null && !order.getEndTime().isBefore(dayStart) && order.getEndTime().isBefore(dayEnd)).count())); }
-        Map<String, Object> countSeries = new LinkedHashMap<>(); countSeries.put("name", "充电订单"); countSeries.put("data", countData); countSeries.put("type", "line"); countSeries.put("style", "curve"); countSeries.put("index", 1); ((List<Map<String, Object>>) chart.get("series")).add(countSeries); return chart;
+    private List<Map<String, Object>> franchiseeManagementOrderStats(List<Integer> siteIds, LocalDateTime[] range) {
+        if (siteIds == null || siteIds.isEmpty() || range == null || range.length < 2
+                || range[0] == null || range[1] == null || !range[1].isAfter(range[0])) {
+            return Collections.emptyList();
+        }
+        LocalDate start = range[0].toLocalDate();
+        LocalDate end = range[1].minusNanos(1).toLocalDate();
+        return safeList(chargingOrderService.getByDate(start, end, siteIds));
     }
-    private Map<String, Object> franchiseePhaseRing(List<TChargingOrder> orders) {
+
+    private BigDecimal sumManagementOrderField(List<Map<String, Object>> stats, String field) {
+        return safeList(stats).stream()
+                .map(row -> decimalValue(row == null ? null : row.get(field)))
+                .reduce(BigDecimal.ZERO, BigDecimal::add);
+    }
+
+    private BigDecimal decimalValue(Object value) {
+        if (value == null) return BigDecimal.ZERO;
+        try {
+            return new BigDecimal(String.valueOf(value));
+        } catch (NumberFormatException ignored) {
+            return BigDecimal.ZERO;
+        }
+    }
+
+    private Map<String, Object> franchiseeManagementOrderTrend(List<Map<String, Object>> stats) {
+        List<String> categories = new ArrayList<>();
+        List<BigDecimal> amountData = new ArrayList<>();
+        List<BigDecimal> countData = new ArrayList<>();
+        for (Map<String, Object> row : safeList(stats)) {
+            if (row == null) continue;
+            categories.add(String.valueOf(row.get("time")));
+            amountData.add(decimalValue(row.get("paymoney")));
+            countData.add(decimalValue(row.get("orderCount")));
+        }
+        Map<String, Object> amountSeries = new LinkedHashMap<>();
+        amountSeries.put("name", "充电金额"); amountSeries.put("data", amountData); amountSeries.put("type", "column");
+        Map<String, Object> countSeries = new LinkedHashMap<>();
+        countSeries.put("name", "充电订单"); countSeries.put("data", countData); countSeries.put("type", "line");
+        countSeries.put("style", "curve"); countSeries.put("index", 1);
+        Map<String, Object> chart = new LinkedHashMap<>();
+        chart.put("categories", categories);
+        chart.put("series", new ArrayList<>(Arrays.asList(amountSeries, countSeries)));
+        return chart;
+    }
+
+    private Map<String, Object> franchiseePhaseRing(List<Integer> siteIds, LocalDateTime[] range) {
         Map<Integer, BigDecimal> phase = new LinkedHashMap<>(); phase.put(1, BigDecimal.ZERO); phase.put(2, BigDecimal.ZERO); phase.put(3, BigDecimal.ZERO); phase.put(4, BigDecimal.ZERO);
-        List<Long> ids = orders.stream().map(TChargingOrder::getId).filter(Objects::nonNull).collect(Collectors.toList());
-        if (!ids.isEmpty()) { chargingOrderAccountingStrategyService.lambdaQuery().in(TChargingOrderAccountingStrategy::getChargingOrderId, ids).list().forEach(item -> phase.computeIfPresent(item.getType(), (key, total) -> total.add(value(item.getChargingCapacity())))); }
+        if (siteIds != null && !siteIds.isEmpty() && range != null && range[0] != null && range[1] != null) {
+            List<Long> ids = chargingOrderMapper.franchiseeOrderIds(siteIds, range[0], range[1]);
+            if (!ids.isEmpty()) {
+                // 分块并行反查 strategy 表(分片键 charging_order_id):MyCat 按 id 路由成本约 2ms/个,
+                // 串行 5000/块在大范围下 70s+ 读超时;100/块 × 16 线程实测 46k id 约 20s(代理并发吞吐有限)。
+                List<CompletableFuture<Void>> futures = new ArrayList<>();
+                for (int from = 0; from < ids.size(); from += PHASE_ID_BATCH_SIZE) {
+                    List<Long> chunk = ids.subList(from, Math.min(from + PHASE_ID_BATCH_SIZE, ids.size()));
+                    futures.add(CompletableFuture.runAsync(() -> {
+                        List<FranchiseePhaseStat> items = chargingOrderMapper.franchiseePhaseStatsByOrderIds(chunk);
+                        if (items != null) {
+                            synchronized (phase) {
+                                items.forEach(item -> {
+                                    if (item != null && item.getType() != null) {
+                                        phase.computeIfPresent(item.getType(), (key, total) -> total.add(value(item.getCapacity())));
+                                    }
+                                });
+                            }
+                        }
+                    }, PHASE_QUERY_EXECUTOR));
+                }
+                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
+            }
+        }
         String[] names = {"尖", "峰", "平", "谷"}; List<Map<String, Object>> data = new ArrayList<>();
         for (int i = 1; i <= 4; i++) { Map<String, Object> item = new LinkedHashMap<>(); item.put("name", names[i - 1]); item.put("value", phase.get(i)); data.add(item); }
         Map<String, Object> chart = new LinkedHashMap<>(); chart.put("series", Collections.singletonList(Collections.singletonMap("data", data))); return chart;
     }
-    private Map<String, Object> franchiseeEfficiencyTrend(List<TChargingOrder> orders, LocalDateTime[] range) {
-        Map<String, Object> chart = franchiseeDailyTrend(orders, range, "功率", order -> value(order.getChargingPower() == null ? order.getPower() : order.getChargingPower()));
-        List<BigDecimal> powerData = new ArrayList<>(), utilization = new ArrayList<>(); List<String> categories = (List<String>) chart.get("categories");
+    private Map<String, Object> franchiseeEfficiencyTrend(List<FranchiseeDayStat> stats, LocalDateTime[] range) {
+        Map<LocalDate, FranchiseeDayStat> byDay = dayStatByDay(stats);
+        List<String> categories = new ArrayList<>();
+        List<BigDecimal> powerData = new ArrayList<>(), utilization = new ArrayList<>();
         LocalDate start = range[0] == null ? LocalDate.now() : range[0].toLocalDate();
-        for (int i = 0; i < categories.size(); i++) { LocalDate day = start.plusDays(i); LocalDateTime dayStart = day.atStartOfDay(), dayEnd = day.plusDays(1).atStartOfDay(); List<TChargingOrder> dayOrders = orders.stream().filter(order -> order.getEndTime() != null && !order.getEndTime().isBefore(dayStart) && order.getEndTime().isBefore(dayEnd)).collect(Collectors.toList()); powerData.add(averagePower(dayOrders)); utilization.add(observedPowerUtilization(dayOrders)); }
-        ((List<Map<String, Object>>) chart.get("series")).get(0).put("data", powerData);
-        Map<String, Object> utilizationSeries = new LinkedHashMap<>(); utilizationSeries.put("name", "功率利用率"); utilizationSeries.put("data", utilization); ((List<Map<String, Object>>) chart.get("series")).add(utilizationSeries); return chart;
+        LocalDate end = range[1] == null ? start.plusDays(1) : range[1].toLocalDate();
+        for (LocalDate day = start; day.isBefore(end); day = day.plusDays(1)) {
+            categories.add(day.toString().substring(5));
+            FranchiseeDayStat stat = byDay.get(day);
+            powerData.add(stat == null ? BigDecimal.ZERO : averagePower(stat));
+            utilization.add(observedPowerUtilization(stat == null ? Collections.emptyList() : Collections.singletonList(stat)));
+        }
+        Map<String, Object> chart = new LinkedHashMap<>(); chart.put("categories", categories);
+        Map<String, Object> powerSeries = new LinkedHashMap<>(); powerSeries.put("name", "功率"); powerSeries.put("data", powerData);
+        Map<String, Object> utilizationSeries = new LinkedHashMap<>(); utilizationSeries.put("name", "功率利用率"); utilizationSeries.put("data", utilization);
+        chart.put("series", new ArrayList<>(Arrays.asList(powerSeries, utilizationSeries))); return chart;
     }
-    private BigDecimal averagePower(List<TChargingOrder> orders) {
-        List<BigDecimal> powers = orders.stream().map(order -> order.getChargingPower() == null ? order.getPower() : order.getChargingPower()).filter(Objects::nonNull).collect(Collectors.toList());
-        return powers.isEmpty() ? BigDecimal.ZERO : powers.stream().reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(powers.size()), 2, RoundingMode.HALF_UP);
+    private BigDecimal averagePower(FranchiseeDayStat stat) {
+        if (stat == null || stat.getPowerCount() == null || stat.getPowerCount() == 0 || stat.getTotalPower() == null) {
+            return BigDecimal.ZERO;
+        }
+        return stat.getTotalPower().divide(BigDecimal.valueOf(stat.getPowerCount()), 2, RoundingMode.HALF_UP);
     }
-    private BigDecimal observedPowerUtilization(List<TChargingOrder> orders) {
-        List<BigDecimal> powers = orders.stream().map(order -> order.getChargingPower() == null ? order.getPower() : order.getChargingPower()).filter(Objects::nonNull).filter(power -> power.signum() > 0).collect(Collectors.toList());
-        if (powers.isEmpty()) return BigDecimal.ZERO; BigDecimal maximum = powers.stream().max(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
-        return maximum.signum() == 0 ? BigDecimal.ZERO : powers.stream().reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(powers.size()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).divide(maximum, 2, RoundingMode.HALF_UP);
+    private BigDecimal observedPowerUtilization(List<FranchiseeDayStat> stats) {
+        BigDecimal sum = stats.stream().map(FranchiseeDayStat::getUtilPowerSum).map(this::value).reduce(BigDecimal.ZERO, BigDecimal::add);
+        long count = stats.stream().mapToLong(stat -> numberValue(stat.getUtilPowerCount())).sum();
+        if (count == 0) return BigDecimal.ZERO;
+        BigDecimal maximum = stats.stream().map(FranchiseeDayStat::getMaxPower).filter(Objects::nonNull).max(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
+        if (maximum.signum() == 0) return BigDecimal.ZERO;
+        return sum.divide(BigDecimal.valueOf(count), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).divide(maximum, 2, RoundingMode.HALF_UP);
     }
-    private BigDecimal demandPowerSatisfaction(List<TChargingOrder> orders) {
-        List<TChargingOrder> valid = orders.stream().filter(order -> order.getCurrent() != null && order.getNeedElec() != null && order.getNeedElec().signum() > 0).collect(Collectors.toList());
-        if (valid.isEmpty()) return BigDecimal.ZERO;
-        BigDecimal total = valid.stream().map(order -> order.getCurrent().multiply(BigDecimal.valueOf(100)).divide(order.getNeedElec(), 4, RoundingMode.HALF_UP).min(BigDecimal.valueOf(100))).reduce(BigDecimal.ZERO, BigDecimal::add);
-        return total.divide(BigDecimal.valueOf(valid.size()), 2, RoundingMode.HALF_UP);
+    private BigDecimal demandPowerSatisfaction(List<FranchiseeDayStat> stats) {
+        BigDecimal total = stats.stream().map(FranchiseeDayStat::getElecSatSum).map(this::value).reduce(BigDecimal.ZERO, BigDecimal::add);
+        long count = stats.stream().mapToLong(stat -> numberValue(stat.getElecSatCount())).sum();
+        if (count == 0) return BigDecimal.ZERO;
+        return total.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP);
     }
-    private Map<String, Object> franchiseePowerDistribution(List<TChargingOrder> orders) {
+    private Map<String, Object> franchiseePowerDistribution(List<Integer> siteIds, LocalDateTime[] range) {
         String[] names = {"0-30kW", "30-60kW", "60-120kW", "120-300kW", "300kW以上"}; long[] counts = new long[5];
-        orders.forEach(order -> { BigDecimal power = order.getChargingPower() == null ? order.getPower() : order.getChargingPower(); if (power == null) return; double value = power.doubleValue(); int index = value < 30 ? 0 : value < 60 ? 1 : value < 120 ? 2 : value < 300 ? 3 : 4; counts[index]++; });
+        if (siteIds != null && !siteIds.isEmpty() && range != null && range[0] != null && range[1] != null) {
+            chargingOrderMapper.franchiseePowerBuckets(siteIds, range[0], range[1]).forEach(bucket -> {
+                if (bucket != null && bucket.getBucket() != null && bucket.getBucket() >= 0 && bucket.getBucket() < 5) {
+                    counts[bucket.getBucket()] += numberValue(bucket.getOrderCount());
+                }
+            });
+        }
         List<Map<String, Object>> data = new ArrayList<>(); for (int i = 0; i < names.length; i++) { Map<String, Object> item = new LinkedHashMap<>(); item.put("name", names[i]); item.put("value", counts[i]); data.add(item); }
         return Collections.singletonMap("series", Collections.singletonList(Collections.singletonMap("data", data)));
     }
-    private Map<String, Object> franchiseeIncomeTrend(List<TChargingOrder> orders, LocalDate firstMonth, int monthCount) {
+    /** 收支分析近6月柱状图:与后台 电站收入分析 一致(历史月结算账单 + 当月原始订单)。 */
+    private Map<String, Object> franchiseeIncomeTrendFromSix(List<SixChargingDto> months) {
         List<String> categories = new ArrayList<>();
         List<BigDecimal> electricity = new ArrayList<>(), service = new ArrayList<>();
-        for (int i = 0; i < monthCount; i++) {
-            YearMonth month = YearMonth.from(firstMonth).plusMonths(i);
-            categories.add(String.format("%02d月", month.getMonthValue()));
-            LocalDateTime start = month.atDay(1).atStartOfDay(), end = month.plusMonths(1).atDay(1).atStartOfDay();
-            electricity.add(sum(orders.stream().filter(o -> o.getEndTime() != null && !o.getEndTime().isBefore(start) && o.getEndTime().isBefore(end)).collect(Collectors.toList()), TChargingOrder::getElectrovalence));
-            service.add(sum(orders.stream().filter(o -> o.getEndTime() != null && !o.getEndTime().isBefore(start) && o.getEndTime().isBefore(end)).collect(Collectors.toList()), TChargingOrder::getServiceCharge));
+        for (SixChargingDto month : months) {
+            if (month == null) {
+                continue;
+            }
+            categories.add(month.getMonth() + "月");
+            electricity.add(month.getElectrovalence() == null ? BigDecimal.ZERO : month.getElectrovalence());
+            service.add(month.getServiceCharge() == null ? BigDecimal.ZERO : month.getServiceCharge());
         }
-        Map<String, Object> chart = new LinkedHashMap<>(); chart.put("categories", categories);
-        Map<String, Object> electricitySeries = new LinkedHashMap<>(); electricitySeries.put("name", "充电费"); electricitySeries.put("data", electricity);
-        Map<String, Object> serviceSeries = new LinkedHashMap<>(); serviceSeries.put("name", "服务费"); serviceSeries.put("data", service);
-        chart.put("series", new ArrayList<>(Arrays.asList(electricitySeries, serviceSeries))); return chart;
+        Map<String, Object> chart = new LinkedHashMap<>();
+        chart.put("categories", categories);
+        Map<String, Object> electricitySeries = new LinkedHashMap<>();
+        electricitySeries.put("name", "充电费");
+        electricitySeries.put("data", electricity);
+        Map<String, Object> serviceSeries = new LinkedHashMap<>();
+        serviceSeries.put("name", "服务费");
+        serviceSeries.put("data", service);
+        chart.put("series", new ArrayList<>(Arrays.asList(electricitySeries, serviceSeries)));
+        return chart;
     }
 
 
@@ -670,6 +985,7 @@
         export.setPartnerName(dto.getPartnerName());
         export.setPhone(dto.getPhone());
         export.setOrderSource(formatOrderSource(dto.getOrderSource()));
+        export.setCreateTime(dto.getCreateTime() == null ? null : DateUtils.localDateTimeToString(dto.getCreateTime()));
         export.setStartTime(dto.getStartTime() == null ? null : DateUtils.localDateTimeToString(dto.getStartTime()));
         export.setEndTime(dto.getEndTime() == null ? null : DateUtils.localDateTimeToString(dto.getEndTime()));
         export.setLicensePlate(dto.getLicensePlate());
@@ -868,6 +1184,7 @@
 
 
     @ResponseBody
+    @RequiresPermissions(value = {"/paymentOrder/refund", "/paymentOrder/refund/select"}, logical = Logical.OR)
     @PostMapping(value = "/pay/order/refund")
     @ApiOperation(value = "退款", tags = {"管理后台-支付订单-订单信息"})
     public R refund(@RequestBody PayOrderRefundDto payOrderQueryDto) {
@@ -964,6 +1281,7 @@
 
 
     @ResponseBody
+    @RequiresPermissions(value = {"/paymentOrder/refund", "/paymentOrder/refund/select"}, logical = Logical.OR)
     @GetMapping(value = "/pay/order/refund/detail")
     @ApiOperation(value = "退款信息", tags = {"管理后台-支付订单-订单信息"})
     public R refundDetail(Long orderId, Integer type) {
@@ -984,6 +1302,7 @@
     }
 
     @ResponseBody
+    @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR)
     @GetMapping(value = "/pay/order/charging")
     @ApiOperation(value = "充电信息", tags = {"管理后台-支付订单-订单信息"})
     public R<PayOrderChargingInfo> refundDetail(Long orderId) {
@@ -1015,6 +1334,7 @@
     }
 
     @ResponseBody
+    @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR)
     @GetMapping(value = "/pay/order/charging/details")
     @ApiOperation(value = "充电明细", tags = {"管理后台-支付订单-订单信息"})
     public R<List<TChargingOrderAccountingStrategy>> chargingDetail(Long orderId) {
@@ -1165,6 +1485,8 @@
         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)+"":"");
+        chargingOrderInfoVO.setVin(byId.getActualVin());
+        chargingOrderInfoVO.setActualVin(byId.getActualVin());
         if (byId.getAppUserCarId()!=null){
             TAppUserCar data = appUserCarClient.getCarById(byId.getAppUserCarId()+"").getData();
             if (data!=null){
@@ -1283,6 +1605,14 @@
         Long count = chargingOrderService.lambdaQuery().eq(TChargingOrder::getAppUserId, userId).count();
 
         return R.ok(count);
+    }
+
+    /**
+     * 查询指定站点中实际发生过充电的用户ID
+     */
+    @PostMapping(value = "/getAppUserIdsBySiteIds")
+    public R<List<Long>> getAppUserIdsBySiteIds(@RequestBody List<Integer> siteIds) {
+        return R.ok(chargingOrderService.getAppUserIdsBySiteIds(siteIds));
     }
 
 
@@ -1460,14 +1790,21 @@
     }
     
     /**
-     * 远程启动充电应答
+     * 远程启动充电应答(按订单号前缀路由:SD=刷卡订单,VD=VIN订单,其余=普通订单)
      * @param message
      */
     @ResponseBody
     @PostMapping(value = "/startChargeSuccessfully")
     public void startChargeSuccessfully(@RequestBody PlatformStartChargingReplyMessageVO message){
         log.info("-------------------远程启动充电请求应答-------------------:" + message);
-        chargingOrderService.startChargeSuccessfully(message);
+        String orderCode = message == null ? null : message.getTransaction_serial_number();
+        if (isCardOrder(orderCode)) {
+            cardChargingOrderService.cardStartChargeSuccessfully(message);
+        } else if (isVinOrder(orderCode)) {
+            vinChargingOrderService.vinStartChargeSuccessfully(message);
+        } else {
+            chargingOrderService.startChargeSuccessfully(message);
+        }
     }
     
     
@@ -1580,23 +1917,36 @@
     
     
     /**
-     * 停止充电应答处理逻辑
+     * 停止充电应答处理逻辑(普通订单原逻辑 + VIN订单按枪兜底确认)
      * @param platformStopChargingReply
      */
     @PostMapping("/terminateSuccessfulResponse")
     public void terminateSuccessfulResponse(@RequestBody PlatformStopChargingReplyVO platformStopChargingReply){
         log.info("-------------------远程停止充电请求应答-------------------:" + platformStopChargingReply);
+        // VIN订单平台停止应答兜底(按枪定位停止中订单,内部自带空判断,不影响普通订单处理)
+        try {
+            vinChargingOrderService.vinTerminateStopByReply(platformStopChargingReply);
+        } catch (Exception ex) {
+            log.error("VIN订单停止应答处理异常:", ex);
+        }
         chargingOrderService.terminateSuccessfulResponse(platformStopChargingReply);
     }
-    
-    
+
+
     /**
-     * 停止充电返回账单后计算费用
+     * 停止充电返回账单后计算费用(按订单号前缀路由:SD=刷卡订单,VD=VIN订单,其余=普通订单)
      * @param vo
      */
     @PostMapping("/endChargeBillingCharge")
     public R endChargeBillingCharge(@RequestBody TransactionRecordMessageVO vo){
         log.info("-------------------停止充电返回账单后计算费用及修改业务状态-------------------:" + vo);
+        String orderCode = vo == null ? null : vo.getTransaction_serial_number();
+        if (isCardOrder(orderCode)) {
+            return cardChargingOrderService.cardEndChargeBillingCharge(vo);
+        }
+        if (isVinOrder(orderCode)) {
+            return vinChargingOrderService.vinEndChargeBillingCharge(vo);
+        }
         return chargingOrderService.endChargeBillingCharge(vo);
     }
 
@@ -1608,13 +1958,20 @@
     @ResponseBody
     @GetMapping(value = "/six/charge")
     @ApiOperation(value = "电站收入分析", tags = {"后台-数据分析-平台收入分析"})
-    public R<List<SixChargingDto>> charge(Integer siteId) {
+    public R<List<SixChargingDto>> charge(Integer siteId, Integer partnerId) {
         Long userId = tokenService.getLoginUser().getUserid();
         SysUser sysUser = sysUserClient.getSysUser(userId).getData();
-        boolean partnerView = isPartnerView(sysUser);
-        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId);
-        LocalDate sixBefore = PreviousSixMonths.get();
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
         //通过siteIds进行sql查询统计
+        return R.ok(buildLastSixMonths(siteIds, false));
+    }
+
+    /**
+     * 近6月+当月电站收入:历史月读结算账单、当月补原始订单。
+     * 与「电站收入分析」图表、底部数据分类及加盟商收支同口径。
+     */
+    private List<SixChargingDto> buildLastSixMonths(List<Integer> siteIds, boolean partnerView) {
+        LocalDate sixBefore = PreviousSixMonths.get();
         List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds, partnerView);
         LocalDate statisticsEndMonth = resolveStatisticsEndMonth(LocalDate.now(), chargingDtos);
         List<SixChargingDto> sixChargingDtos = generateLastSixMonths(statisticsEndMonth);
@@ -1626,9 +1983,7 @@
             }
 
         }
-
-        return R.ok(sixChargingDtos);
-
+        return sixChargingDtos;
     }
 
 
@@ -1673,13 +2028,13 @@
     @ResponseBody
     @GetMapping(value = "/six/circle")
     @ApiOperation(value = "电站收入占比", tags = {"后台-数据分析-平台收入分析"})
-    public R<List<SixCircleDto>> circle(Integer siteId) {
+    public R<List<SixCircleDto>> circle(Integer siteId, Integer partnerId) {
         Long userId = tokenService.getLoginUser().getUserid();
         SysUser sysUser = sysUserClient.getSysUser(userId).getData();
         boolean partnerView = isPartnerView(sysUser);
-        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId);
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
         LocalDate sixBefore = PreviousSixMonths.get();
-        List<SixCircleDto> sixCircleDtos = chargingOrderService.circle(siteIds,sixBefore, partnerView);
+        List<SixCircleDto> sixCircleDtos = chargingOrderService.circle(siteIds,sixBefore, false);
         for (SixCircleDto sixCircleDto : sixCircleDtos) {
             Site site = siteClient.getSiteByIds(Arrays.asList(sixCircleDto.getSiteId())).getData().get(0);
             sixCircleDto.setSiteName(site.getName());
@@ -1760,25 +2115,39 @@
     @ResponseBody
     @GetMapping(value = "/six/total")
     @ApiOperation(value = "底部数据分类", tags = {"后台-数据分析-平台收入分析"})
-    public R<Map<String,Object>> total(Integer siteId) {
+    public R<Map<String,Object>> total(Integer siteId, Integer partnerId) {
         //count近6个月的数据
         Long userId = tokenService.getLoginUser().getUserid();
         SysUser sysUser = sysUserClient.getSysUser(userId).getData();
         boolean partnerView = isPartnerView(sysUser);
-        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId);
-        Map<String,Object>  map = chargingOrderService.countAll(siteIds, partnerView);
-        if (map == null) {
-            map = new HashMap<String,Object>();
-        }
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
+        LocalDate sixBefore = PreviousSixMonths.get();
+        Map<String,Object> map = new HashMap<String,Object>();
+        // 电费/服务费与上方「电站收入分析」图表同口径:近6月结算账单 + 当月原始订单,保证底部合计=图表6个月相加
+        List<SixChargingDto> sixChargingDtos = buildLastSixMonths(siteIds, false);
+        map.put("electrovalence", sixChargingDtos.stream()
+                .filter(Objects::nonNull)
+                .map(SixChargingDto::getElectrovalence)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add));
+        map.put("service_charge", sixChargingDtos.stream()
+                .filter(Objects::nonNull)
+                .map(SixChargingDto::getServiceCharge)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add));
+        // 合作商分成/三方平台分佣按近6月结算口径统计(与图表月份窗口一致)
+        Map<String,Object> sub = chargingOrderService.countAll(siteIds, false, sixBefore);
+        map.put("commission_amount", sub == null ? BigDecimal.ZERO : sub.get("commission_amount"));
+        map.put("sharing_amount", sub == null ? BigDecimal.ZERO : sub.get("sharing_amount"));
         boolean platformVisible = !partnerView;
         if(platformVisible){
-            R<BigDecimal> parkingAmountResult = parkingLotClient.getRecordAmount(siteIds);
+            R<BigDecimal> parkingAmountResult = parkingLotClient.getRecordAmount(siteIds, sixBefore.toString());
             BigDecimal data = parkingAmountResult == null || parkingAmountResult.getData() == null
                     ? BigDecimal.ZERO : parkingAmountResult.getData();
             map.put("parkingAmount",data);
-            BigDecimal data1 =   shoppingOrderService.getSumAmount();
+            BigDecimal data1 =   shoppingOrderService.getSumAmount(sixBefore);
             map.put("shopAmount",data1);
-            BigDecimal data2 =   vipOrderService.getSumAmout();
+            BigDecimal data2 =   vipOrderService.getSumAmout(sixBefore);
             map.put("vipAmount",data2);
         }else{
             map.put("parkingAmount",0);
@@ -1793,11 +2162,11 @@
     @ResponseBody
     @GetMapping(value = "/six/pay-type-circle")
     @ApiOperation(value = "收入类型占比", tags = {"后台-数据分析-平台收入分析"})
-    public R<List<SixIncomeCircleDto>> payTypeCircle(Integer siteId) {
+    public R<List<SixIncomeCircleDto>> payTypeCircle(Integer siteId, Integer partnerId) {
         Long userId = tokenService.getLoginUser().getUserid();
         SysUser sysUser = sysUserClient.getSysUser(userId).getData();
         boolean partnerView = isPartnerView(sysUser);
-        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId);
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
         LocalDate sixBefore = PreviousSixMonths.get();
         return R.ok(chargingOrderService.payTypeCircle(sixBefore, siteIds, partnerView));
     }
@@ -1810,7 +2179,8 @@
      * 解析平台收入分析页面允许查看的站点范围。
      * 合作商使用授权站点,其他后台账号沿用用户站点列表;传入站点时需做授权校验。
      */
-    private List<Integer> resolvePlatformRevenueSiteIds(Long userId, SysUser sysUser, Integer siteId) {
+    private List<Integer> resolvePlatformRevenueSiteIds(Long userId, SysUser sysUser,
+                                                        Integer siteId, Integer partnerId) {
         List<Integer> siteIds = new ArrayList<>();
         if (sysUser != null && Integer.valueOf(2).equals(sysUser.getRoleType())) {
             Set<Integer> authSiteIds = partnerClient.authSite(sysUser.getObjectId(), SiteMenu.SITE_LIST.getValue()).getData();
@@ -1828,10 +2198,38 @@
         if (siteId != null) {
             return siteIds.contains(siteId) ? Collections.singletonList(siteId) : Collections.singletonList(-1);
         }
+        if (partnerId != null && !siteIds.isEmpty()) {
+            R<List<Site>> siteResult = siteClient.getSiteByIds(siteIds);
+            return filterPlatformRevenueSiteIdsByPartner(siteIds,
+                    siteResult == null ? null : siteResult.getData(), partnerId);
+        }
         if (siteIds.isEmpty()) {
             siteIds.add(-1);
         }
         return siteIds;
+    }
+
+    static List<Integer> filterPlatformRevenueSiteIdsByPartner(List<Integer> allowedSiteIds,
+                                                               List<Site> sites,
+                                                               Integer partnerId) {
+        if (partnerId == null) {
+            return allowedSiteIds == null || allowedSiteIds.isEmpty()
+                    ? Collections.singletonList(-1) : new ArrayList<>(allowedSiteIds);
+        }
+        if (allowedSiteIds == null || allowedSiteIds.isEmpty() || sites == null || sites.isEmpty()) {
+            return Collections.singletonList(-1);
+        }
+        Set<Integer> allowed = new HashSet<>(allowedSiteIds);
+        List<Integer> result = sites.stream()
+                .filter(Objects::nonNull)
+                .filter(site -> allowed.contains(site.getId()))
+                // 合作商类型不参与筛选:主合作商或场地方匹配均属于该合作商名下电站。
+                .filter(site -> Objects.equals(site.getPartnerId(), partnerId)
+                        || Objects.equals(site.getVenuePartnerId(), partnerId))
+                .map(Site::getId)
+                .distinct()
+                .collect(Collectors.toList());
+        return result.isEmpty() ? Collections.singletonList(-1) : result;
     }
 
     
@@ -1927,29 +2325,145 @@
     }
     
     /**
-     * 处理充电订单实时监控数据相关的业务逻辑
+     * 处理充电订单实时监控数据相关的业务逻辑(按订单号前缀路由)
      * @param query
      */
     @PostMapping("/chargeMonitoring")
     public void chargeMonitoring(@RequestBody UploadRealTimeMonitoringDataQuery query){
-        chargingOrderService.chargeMonitoring(query);
+        String orderCode = query == null ? null : query.getTransaction_serial_number();
+        if (isCardOrder(orderCode)) {
+            cardChargingOrderService.cardChargeMonitoring(query);
+        } else if (isVinOrder(orderCode)) {
+            vinChargingOrderService.vinChargeMonitoring(query);
+        } else {
+            chargingOrderService.chargeMonitoring(query);
+        }
     }
     /**
-     * 通过流水号查询订单
+     * 通过流水号查询订单(统一前缀路由:SD=刷卡订单,VD=VIN订单,其余=普通订单)
+     * <p>设备链路(实时监控/BMS需求/交易记录确认等)统一经此按订单号前缀取三类订单,
+     * SD/VD 订单实体继承自 TChargingOrder,字段兼容直接返回。</p>
      * @param code
      * @return
      */
     @PostMapping(value = "/getOrderByCode/{code}")
     public R<TChargingOrder> getOrderByCode(@PathVariable("code") String code){
-        TChargingOrder one = chargingOrderService.getOne(Wrappers.lambdaQuery(TChargingOrder.class)
-                .eq(TChargingOrder::getCode, code));
+        TChargingOrder one;
+        if (isCardOrder(code)) {
+            one = cardChargingOrderService.getCardOrderByCode(code);
+        } else if (isVinOrder(code)) {
+            one = vinChargingOrderService.getVinOrderByCode(code);
+        } else {
+            one = chargingOrderService.getOne(Wrappers.lambdaQuery(TChargingOrder.class)
+                    .eq(TChargingOrder::getCode, code));
+        }
+        if (one == null) {
+            return R.ok(null);
+        }
         one.setIdStr(one.getId().toString());
         return R.ok(one);
     }
-    
-    
-    
-    
+
+    @PostMapping("/updateHandshakeVin")
+    public R<Boolean> updateHandshakeVin(@RequestParam("orderCode") String orderCode,
+                                         @RequestParam("vin") String vin) {
+        if (StringUtils.isEmpty(orderCode)) {
+            return R.ok(false);
+        }
+        boolean updated;
+        if (orderCode.startsWith("CD")) {
+            updated = StringUtils.isNotEmpty(vin) && chargingOrderService.update(Wrappers.<TChargingOrder>lambdaUpdate()
+                    .eq(TChargingOrder::getCode, orderCode)
+                    .set(TChargingOrder::getActualVin, vin));
+        } else if (orderCode.startsWith("SD")) {
+            // SD/VD:VIN 为空也进入握手处理(状态推进必达);服务内部仅非空回写 VIN,且仅状态=启动中(2)才推进
+            updated = cardChargingOrderService.handleHandshakeVin(orderCode, vin);
+        } else if (orderCode.startsWith("VD")) {
+            updated = vinChargingOrderService.handleHandshakeVin(orderCode, vin);
+        } else {
+            log.warn("握手VIN回写失败,未知订单类型:{}", orderCode);
+            return R.ok(false);
+        }
+        return R.ok(updated);
+    }
+
+    /**
+     * 设备链路订单号前缀判断:SD=刷卡充电订单
+     */
+    private boolean isCardOrder(String orderCode) {
+        return orderCode != null && orderCode.startsWith("SD");
+    }
+
+    /**
+     * 设备链路订单号前缀判断:VD=VIN码充电订单
+     */
+    private boolean isVinOrder(String orderCode) {
+        return orderCode != null && orderCode.startsWith("VD");
+    }
+
+    /**
+     * 设备主动发起充电(刷卡/VIN码)鉴权建单统一入口。
+     * <p>协议 start_method:1=刷卡(创建SD订单),2=账号启动(暂不支持),3=VIN码(创建VD订单)。</p>
+     */
+    @PostMapping("/inner/device-start-charging")
+    public R<DeviceStartChargingVO> deviceStartCharging(@RequestBody DeviceStartChargingDTO dto) {
+        if (dto == null || dto.getStartMethod() == null) {
+            log.warn("[设备启动] 缺少启动方式,拒绝建单 dto={}", dto);
+            return R.ok(DeviceStartChargingVO.fail(null));
+        }
+        DeviceStartChargingVO result;
+        switch (dto.getStartMethod()) {
+            case 1:
+                result = cardChargingOrderService.startCardCharging(dto);
+                break;
+            case 3:
+                result = vinChargingOrderService.startVinCharging(dto);
+                break;
+            case 2:
+                // 账号启动暂不支持(协议无对应失败码,按最接近的“账户不存在”返回)
+                log.warn("[设备启动] 账号启动方式暂不支持 pile={} account={}", dto.getChargingPileCode(), dto.getAccount());
+                result = DeviceStartChargingVO.fail(1);
+                break;
+            default:
+                log.warn("[设备启动] 未知启动方式 startMethod={} pile={} gun={}",
+                        dto.getStartMethod(), dto.getChargingPileCode(), dto.getChargingGunCode());
+                result = DeviceStartChargingVO.fail(null);
+                break;
+        }
+        return R.ok(result);
+    }
+
+    /**
+     * 内部接口:统计公司名下进行中充电订单数(三表合计,状态 2=启动中/3=充电中/4=停止中,
+     * 账户模式切换:分配→共享 前校验使用)
+     */
+    @PostMapping("/inner/count-active-by-company")
+    public R<Integer> countActiveByCompany(@RequestParam("companyId") Integer companyId) {
+        if (companyId == null) {
+            return R.ok(0);
+        }
+        try {
+            List<Integer> activeStatuses = Arrays.asList(2, 3, 4);
+            long count = 0L;
+            count += chargingOrderService.lambdaQuery()
+                    .eq(TChargingOrder::getCompanyId, companyId)
+                    .in(TChargingOrder::getStatus, activeStatuses)
+                    .count();
+            count += cardChargingOrderService.lambdaQuery()
+                    .eq(TCardChargingOrder::getCompanyId, companyId)
+                    .in(TCardChargingOrder::getStatus, activeStatuses)
+                    .count();
+            count += vinChargingOrderService.lambdaQuery()
+                    .eq(TVinChargingOrder::getCompanyId, companyId)
+                    .in(TVinChargingOrder::getStatus, activeStatuses)
+                    .count();
+            return R.ok((int) count);
+        } catch (RuntimeException ex) {
+            log.error("统计公司进行中充电订单失败:companyId={}", companyId, ex);
+            return R.fail("统计公司进行中充电订单失败:" + ex.getMessage());
+        }
+    }
+
     @RequiresPermissions(value = {"/chargingOperationAnalysis"}, logical = Logical.OR)
     @ResponseBody
     @PostMapping(value = "/charging/statistics")
@@ -2874,25 +3388,37 @@
 
 
     /**
-     * 硬件充电结束后的处理逻辑
+     * 硬件充电结束后的处理逻辑(按订单号前缀路由,结束方式2=设备自动结束)
      * @param code
      */
     @PostMapping("/endCharge")
     public void endCharge(@RequestParam("code") String code){
         log.info(code + ":-------------------充电桩自动结束充电-------------------");
-        chargingOrderService.endCharge(code, 2);
+        if (isCardOrder(code)) {
+            cardChargingOrderService.cardEndCharge(code, 2);
+        } else if (isVinOrder(code)) {
+            vinChargingOrderService.vinEndCharge(code, 2);
+        } else {
+            chargingOrderService.endCharge(code, 2);
+        }
     }
 
 
 
     /**
-     * 硬件异常结束充电后的处理逻辑
+     * 硬件异常结束充电后的处理逻辑(按订单号前缀路由,结束方式0=异常终止)
      * @param code
      */
     @PostMapping("/excelEndCharge")
     public void excelEndCharge(@RequestParam("code") String code){
         log.info(code + ":-------------------充电异常,停止充电-------------------");
-        chargingOrderService.excelEndCharge(code);
+        if (isCardOrder(code)) {
+            cardChargingOrderService.cardEndCharge(code, 0);
+        } else if (isVinOrder(code)) {
+            vinChargingOrderService.vinEndCharge(code, 0);
+        } else {
+            chargingOrderService.excelEndCharge(code);
+        }
     }
 
 
@@ -3079,6 +3605,15 @@
 
         return R.ok(new BigDecimal(sumDegreeBySiteIds));
     }
+
+    /**
+     * 充电桩数据大屏 获取站点集合中累计充电量(与 /large-screen/summary 同口径: 已结束+已支付订单)
+     */
+    @ResponseBody
+    @GetMapping("/getLargeScreenTotalCapacity")
+    public R<BigDecimal> getLargeScreenTotalCapacity(@RequestParam("siteIds") List<Integer> siteIds){
+        return R.ok(chargingOrderService.getLargeScreenTotalCapacity(siteIds));
+    }
     @ResponseBody
     @PostMapping("/addChargingOrder")
     public R<Long> addChargingOrder(@RequestBody TChargingOrder chargingOrder){

--
Gitblit v1.7.1