From 976ff3fe092ee2f9515013dbfab77d25b2944b75 Mon Sep 17 00:00:00 2001
From: puzhibing <393733352@qq.com>
Date: 星期三, 14 十月 2026 11:18:29 +0800
Subject: [PATCH] 修改bug

---
 ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java | 1148 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 1,057 insertions(+), 91 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 30ceeb2..df80466 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
@@ -10,19 +10,25 @@
 import java.math.RoundingMode;
 import java.text.DecimalFormat;
 import java.time.*;
+import java.util.concurrent.TimeUnit;
 
 
 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.*;
+import com.ruoyi.chargingPile.api.model.Partner;
 import com.ruoyi.chargingPile.api.model.Site;
 import com.ruoyi.chargingPile.api.model.TChargingGun;
 import com.ruoyi.chargingPile.api.model.TChargingPile;
 import com.ruoyi.chargingPile.api.model.TParkingRecord;
+import com.ruoyi.chargingPile.api.vo.GetChargingGunByChargingPileIdsVo;
 import com.ruoyi.common.core.domain.R;
 import com.ruoyi.common.core.dto.ChargingOrderGroup;
 import com.ruoyi.common.core.dto.ChargingPercentProvinceDto;
@@ -37,6 +43,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;
@@ -52,19 +59,28 @@
 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.*;
+import com.ruoyi.order.support.FranchiseeUserStatistics;
 import com.ruoyi.order.util.PreviousSixMonths;
 import com.ruoyi.order.util.mongodb.service.UploadRealTimeMonitoringDataService;
 import com.ruoyi.order.vo.EndOfChargePageInfo;
 import com.ruoyi.order.vo.ChargingSimulationVO;
 import com.ruoyi.order.vo.IcbcAdminSubOrderVO;
 import com.ruoyi.order.vo.StatisticsOfBatteryVO;
+import com.ruoyi.order.vo.ReservationRecommendationVO;
 import com.ruoyi.order.vo.UpdateOrderPaymentAmountDto;
 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;
@@ -88,6 +104,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;
@@ -111,6 +130,10 @@
 
     @Resource
     private TChargingOrderService chargingOrderService;
+    @Resource
+    private TCardChargingOrderService cardChargingOrderService;
+    @Resource
+    private TVinChargingOrderService vinChargingOrderService;
     @Autowired
     private TokenService tokenService;
     @Autowired
@@ -152,10 +175,16 @@
     @Resource
     private AppUserCarClient appUserCarClient;
     @Resource
+    private AppUserTagClient appUserTagClient;
+    @Resource
+    private UserTagClient userTagClient;
+    @Resource
     private TChargingOrderAccountingStrategyService chargingOrderAccountingStrategyService;
     
     @Resource
     private TOrderInvoiceService invoiceService;
+    @Resource
+    private TOrderInvoiceDetailService orderInvoiceDetailService;
     @Resource
     private UploadRealTimeMonitoringDataService uploadRealTimeMonitoringDataService;
     @Resource
@@ -169,7 +198,684 @@
     @Resource
     private RoleSiteClient roleSiteClient;
     @Resource
+    private VipClient vipClient;
+    @Resource
+    private OtherClient otherClient;
+    @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<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<>();
+        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(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);
+        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", 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")
+    public R<Map<String, Object>> franchiseeUser(@RequestBody(required = false) Map<String, Object> params) {
+        Partner partner = franchiseePartner();
+        List<Integer> siteIds = partner == null ? Collections.emptyList() : franchiseeSiteIds(params, partner.getId());
+        LocalDateTime[] range = franchiseeRange(params);
+        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.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));
+            if (userResult != null && userResult.getData() != null) appUsers = userResult.getData();
+        }
+        Map<Long, TAppUser> userMap = appUsers.stream().filter(user -> user.getId() != null)
+                .collect(Collectors.toMap(TAppUser::getId, user -> user, (left, right) -> left));
+
+        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);
+            if (carResult != null && carResult.getData() != null) cars = carResult.getData();
+        }
+
+        Map<String, Object> evaluation = franchiseeEvaluation(siteIds);
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("summary", userStatistics.getSummary());
+        result.put("userStats", userStatistics.getTrend());
+        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(aggs, userMap));
+        result.put("evaluation", evaluation.get("summary"));
+        result.put("goodTags", evaluation.get("goodTags"));
+        result.put("badTags", evaluation.get("badTags"));
+        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);
+    }
+
+    @PostMapping("/app/franchisee/operation")
+    public R<Map<String, Object>> franchiseeOperation(@RequestBody(required = false) Map<String, Object> params) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        List<Integer> siteIds = franchiseeSiteIds(params);
+        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));
+        }
+
+        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 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 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) {
+        Partner partner = franchiseePartner();
+        if (partner == null || partner.getId() == null) return Collections.emptyList();
+        return franchiseeSiteIds(params, partner.getId());
+    }
+
+    private Partner franchiseePartner() {
+        if (tokenService.getLoginUserApplet() == null || tokenService.getLoginUserApplet().getUserId() == null) return null;
+        Long appUserId = tokenService.getLoginUserApplet().getUserId();
+        R<Partner> partnerResult = partnerClient.getPartnerByAppUserId(appUserId);
+        return partnerResult == null ? null : partnerResult.getData();
+    }
+
+    private List<Integer> franchiseeSiteIds(Map<String, Object> params, Integer partnerId) {
+        R<List<Site>> siteResult = siteClient.getSiteAll();
+        List<Site> sites = siteResult == null ? null : siteResult.getData();
+        List<Integer> siteIds = sites == null ? new ArrayList<>() : sites.stream().filter(s -> Objects.equals(s.getPartnerId(), partnerId)).map(Site::getId).collect(Collectors.toList());
+        Object requestedSite = params == null ? null : params.get("siteId");
+        if (requestedSite != null && !String.valueOf(requestedSite).isEmpty()) {
+            Integer siteId = Integer.valueOf(String.valueOf(requestedSite)); siteIds = siteIds.contains(siteId) ? Collections.singletonList(siteId) : Collections.singletonList(-1);
+        }
+        return siteIds;
+    }
+
+    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) {
+        long ordinary = users.stream().filter(user -> user.getVipId() == null || user.getVipId() == 0).count();
+        Map<Integer, Long> vipCounts = users.stream().filter(user -> user.getVipId() != null && user.getVipId() != 0)
+                .collect(Collectors.groupingBy(TAppUser::getVipId, Collectors.counting()));
+        List<Map<String, Object>> result = new ArrayList<>();
+        if (ordinary > 0) result.add(namedCount("普通用户", ordinary));
+        vipCounts.forEach((vipId, count) -> result.add(namedCount(vipNames.getOrDefault(vipId, "会员" + vipId), count)));
+        return result;
+    }
+
+    private Map<String, Object> franchiseeCompanyRank(List<FranchiseeUserAgg> aggs, Map<Long, TAppUser> userMap) {
+        Map<Integer, BigDecimal> totals = new HashMap<>();
+        aggs.forEach(agg -> {
+            TAppUser user = userMap.get(agg.getAppUserId());
+            if (user != null && user.getCompanyId() != null) {
+                totals.merge(user.getCompanyId(), value(agg.getCapacity()), BigDecimal::add);
+            }
+        });
+        List<Map.Entry<Integer, BigDecimal>> sorted = totals.entrySet().stream()
+                .sorted(Map.Entry.<Integer, BigDecimal>comparingByValue().reversed()).limit(5).collect(Collectors.toList());
+        Map<String, Object> chart = new LinkedHashMap<>();
+        chart.put("categories", sorted.stream().map(entry -> {
+            R<TCompany> companyResult = otherClient.unitDetail(entry.getKey());
+            TCompany company = companyResult == null ? null : companyResult.getData();
+            return company == null || StringUtils.isBlank(company.getName()) ? "单位" + entry.getKey() : company.getName();
+        }).collect(Collectors.toList()));
+        Map<String, Object> series = new LinkedHashMap<>(); series.put("name", "充电量");
+        series.put("data", sorted.stream().map(Map.Entry::getValue).collect(Collectors.toList()));
+        chart.put("series", Collections.singletonList(series)); return chart;
+    }
+
+    private Map<String, Object> franchiseeEvaluation(List<Integer> siteIds) {
+        if (siteIds == null || siteIds.isEmpty()) {
+            Map<String, Object> emptySummary = new LinkedHashMap<>();
+            emptySummary.put("score", 0D); emptySummary.put("goodCount", 0); emptySummary.put("mediumCount", 0); emptySummary.put("badCount", 0);
+            emptySummary.put("goodRate", BigDecimal.ZERO); emptySummary.put("mediumRate", BigDecimal.ZERO); emptySummary.put("badRate", BigDecimal.ZERO);
+            Map<String, Object> empty = new LinkedHashMap<>(); empty.put("summary", emptySummary); empty.put("goodTags", Collections.emptyList()); empty.put("badTags", Collections.emptyList()); return empty;
+        }
+        Double score = chargingOrderService.getAver(siteIds);
+        List<Map<String, Object>> levels = chargingOrderService.getLevelEvaluate(siteIds);
+        long good = 0, medium = 0, bad = 0;
+        if (levels != null) for (Map<String, Object> level : levels) {
+            String range = String.valueOf(level.get("score_range")); long count = numberValue(level.get("count"));
+            if ("4-5".equals(range)) good += count; else if ("3".equals(range)) medium += count; else if ("1-2".equals(range)) bad += count;
+        }
+        long total = good + medium + bad;
+        Map<String, Object> summary = new LinkedHashMap<>(); summary.put("score", score == null ? 0D : score);
+        summary.put("goodCount", good); summary.put("mediumCount", medium); summary.put("badCount", bad);
+        summary.put("goodRate", ratePercent(good, total)); summary.put("mediumRate", ratePercent(medium, total)); summary.put("badRate", ratePercent(bad, total));
+        Map<String, Object> result = new LinkedHashMap<>(); result.put("summary", summary);
+        result.put("goodTags", safeList(orderEvaluateService.goodTop(siteIds))); result.put("badTags", safeList(orderEvaluateService.badTop(siteIds))); return result;
+    }
+
+    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>> 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());
+    }
+
+    private List<Map<String, Object>> namedCounts(String[] names, long[] values) {
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (int i = 0; i < names.length; i++) if (values[i] > 0) result.add(namedCount(names[i], values[i]));
+        return result;
+    }
+
+    private Map<String, Object> namedCount(String name, long value) { Map<String, Object> result = new LinkedHashMap<>(); result.put("name", name); result.put("value", value); return result; }
+    private long numberValue(Object value) { return value instanceof Number ? ((Number) value).longValue() : 0L; }
+    private BigDecimal ratePercent(long numerator, long denominator) { return denominator == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(numerator * 100D / denominator).setScale(2, RoundingMode.HALF_UP); }
+    private <T> List<T> safeList(List<T> values) { return values == null ? Collections.emptyList() : values; }
+
+    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, 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};
+        String[] names = {"可用率", "故障率", "离网率", "电量满足率"};
+        for (int i = 0; i < keys.length; i++) {
+            final int status = statuses[i]; Map<String, Object> chart = new LinkedHashMap<>(); chart.put("key", keys[i]);
+            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
+                    ? 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) {
+        LocalDate today = LocalDate.now();
+        if (params != null && params.get("startTime") != null && params.get("endTime") != null) {
+            String startText = String.valueOf(params.get("startTime"));
+            String endText = String.valueOf(params.get("endTime"));
+            if (!startText.isEmpty() && !endText.isEmpty()) {
+                try {
+                    return new LocalDateTime[]{LocalDate.parse(startText).atStartOfDay(), LocalDate.parse(endText).plusDays(1).atStartOfDay()};
+                } catch (RuntimeException ignored) {
+                    // 日期格式异常时回退到快捷日期范围。
+                }
+            }
+        }
+        String type = params == null ? "today" : String.valueOf(params.getOrDefault("dateType", "today"));
+        if ("year".equals(type)) return new LocalDateTime[]{today.withDayOfYear(1).atStartOfDay(), today.plusDays(1).atStartOfDay()};
+        if ("month".equals(type)) return new LocalDateTime[]{today.withDayOfMonth(1).atStartOfDay(), today.plusDays(1).atStartOfDay()};
+        if ("week".equals(type)) { LocalDate start = today.minusDays(today.getDayOfWeek().getValue() - 1); return new LocalDateTime[]{start.atStartOfDay(), today.plusDays(1).atStartOfDay()}; }
+        return new LocalDateTime[]{today.atStartOfDay(), today.plusDays(1).atStartOfDay()};
+    }
+
+    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<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));
+            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 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 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);
+        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<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();
+        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(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<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<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<Integer> siteIds, LocalDateTime[] range) {
+        String[] names = {"0-30kW", "30-60kW", "60-120kW", "120-300kW", "300kW以上"}; long[] counts = new long[5];
+        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)));
+    }
+    /** 收支分析近6月柱状图:与后台 电站收入分析 一致(历史月结算账单 + 当月原始订单)。 */
+    private Map<String, Object> franchiseeIncomeTrendFromSix(List<SixChargingDto> months) {
+        List<String> categories = new ArrayList<>();
+        List<BigDecimal> electricity = new ArrayList<>(), service = new ArrayList<>();
+        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;
+    }
 
 
 
@@ -280,9 +986,34 @@
         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());
+        export.setChargingCapacity(dto.getChargingCapacity());
+        export.setElectrovalence(dto.getElectrovalence());
+        export.setServiceCharge(dto.getServiceCharge());
+        export.setEndMode(formatChargingEndMode(dto.getEndMode()));
+        export.setPeriodCount(dto.getPeriodCount());
         return export;
+    }
+
+    private String formatChargingEndMode(Integer endMode) {
+        if (endMode == null) {
+            return "-";
+        }
+        switch (endMode) {
+            case 0:
+                return "异常终止";
+            case 1:
+                return "主动终止";
+            case 2:
+                return "满电终止";
+            case 3:
+                return "费用不足终止";
+            default:
+                return "-";
+        }
     }
 
     private String formatEnterpriseOrderType(Integer type) {
@@ -326,6 +1057,7 @@
     @PostMapping(value = "/pay/order/list")
     @ApiOperation(value = "列表", tags = {"管理后台-支付订单-订单信息"})
     public R<PageInfo<PayOrderDto>> payOrderList(@RequestBody PayOrderQueryDto payOrderQueryDto) {
+        resolveInvoiceOrderIds(payOrderQueryDto);
         return chargingOrderService.payOrderQuery(payOrderQueryDto);
     }
 
@@ -335,6 +1067,7 @@
     @ApiOperation(value = "导出查看订单列表", tags = {"管理后台-支付订单-订单信息"})
     @Log(title = "发票管理查看订单导出", businessType = BusinessType.EXPORT)
     public void exportPayOrder(@RequestBody PayOrderQueryDto payOrderQueryDto) {
+        resolveInvoiceOrderIds(payOrderQueryDto);
         payOrderQueryDto.setPageCurr(1);
         payOrderQueryDto.setPageSize(10000);
         R<PageInfo<PayOrderDto>> result = chargingOrderService.payOrderQuery(payOrderQueryDto);
@@ -356,6 +1089,26 @@
         } catch (IOException e) {
             log.error("导出查看订单列表失败", e);
         }
+    }
+
+    /**
+     * 查看开票订单时以数据库中的开票明细为准,避免前端遗漏或篡改订单 ID。
+     */
+    private void resolveInvoiceOrderIds(PayOrderQueryDto query) {
+        if (query == null || query.getInvoiceId() == null) {
+            return;
+        }
+        LambdaQueryWrapper<TOrderInvoiceDetail> wrapper = new LambdaQueryWrapper<TOrderInvoiceDetail>()
+                .eq(TOrderInvoiceDetail::getOrderInvoiceId, query.getInvoiceId());
+        if (query.getType() != null) {
+            wrapper.eq(TOrderInvoiceDetail::getOrderType, query.getType());
+        }
+        List<String> orderIds = orderInvoiceDetailService.list(wrapper).stream()
+                .map(TOrderInvoiceDetail::getOrderId)
+                .filter(Objects::nonNull)
+                .map(String::valueOf)
+                .collect(Collectors.toList());
+        query.setIds(orderIds);
     }
 
     private PayOrderExport buildPayOrderExport(PayOrderDto dto) {
@@ -432,6 +1185,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) {
@@ -478,6 +1232,7 @@
                 payOrderInfoDto.setThirdPayAmount(byId.getThirdPayAmount());
                 payOrderInfoDto.setBalanceRefundAmount(byId.getBalanceRefundAmount());
                 payOrderInfoDto.setThirdRefundAmount(byId.getThirdRefundAmount());
+                payOrderInfoDto.setRefundableAmount(chargingOrderService.getManualRefundableAmount(byId.getId()));
                 return R.ok(payOrderInfoDto);
             case 2:
                 TShoppingOrder byId1 = shoppingOrderService.getById(orderId);
@@ -527,6 +1282,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) {
@@ -547,6 +1303,7 @@
     }
 
     @ResponseBody
+    @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR)
     @GetMapping(value = "/pay/order/charging")
     @ApiOperation(value = "充电信息", tags = {"管理后台-支付订单-订单信息"})
     public R<PayOrderChargingInfo> refundDetail(Long orderId) {
@@ -578,6 +1335,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) {
@@ -623,54 +1381,19 @@
     @PostMapping(value = "/pay/order/refund/list")
     @ApiOperation(value = "列表", tags = {"管理后台-支付订单-退款订单"})
     public R<PageInfo<TChargingOrderRefund>> refundList(@RequestBody ChargingRefundDto chargingRefundDto) {
-        Integer pageCurr = chargingRefundDto.getPageCurr();
-        Integer pageSize = chargingRefundDto.getPageSize();
-//        R<PageInfo<TChargingOrderRefund>> refundList = chargingOrderService.getRefundList(chargingRefundDto);
-        chargingRefundDto.setPageCurr(1);
-        chargingRefundDto.setPageSize(199999999);
-        R<PageInfo<TChargingOrderRefund>> refundList1 = chargingOrderService.getRefundList(chargingRefundDto);
         Long userId = tokenService.getLoginUser().getUserid();
-        //如果没传siteId,获取当前登陆人所有的siteIds
-        List<Integer> siteIds = new ArrayList<>();
-            if (userId != null){
-                List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
-                for (GetSiteListDTO datum : data) {
-                    siteIds.add(datum.getId());
+        SysUser sysUser = sysUserClient.getSysUser(userId).getData();
+        if (sysUser != null && Integer.valueOf(2).equals(sysUser.getRoleType())) {
+            List<Integer> siteIds = new ArrayList<>();
+            List<GetSiteListDTO> sites = siteClient.getSiteListByUserId(userId).getData();
+            if (sites != null) {
+                for (GetSiteListDTO site : sites) {
+                    siteIds.add(site.getId());
                 }
             }
-
-        if (siteIds.isEmpty()){
-            siteIds.add(-1);
+            chargingRefundDto.setSiteIds(siteIds.isEmpty() ? Collections.singletonList(-1) : siteIds);
         }
-        // 查询当前登陆人按钮权限
-        SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
-        Integer roleType = sysUser.getRoleType();
-        List<TChargingOrderRefund> tChargingOrderRefunds = new ArrayList<>();
-        for (TChargingOrderRefund record : refundList1.getData().getRecords()) {
-            if (roleType==1){
-                tChargingOrderRefunds.add(record);
-                continue;
-            }
-            if (record.getType()!=1){
-                tChargingOrderRefunds.add(record);
-            }
-            TChargingOrder byId = chargingOrderService.getById(record.getOrderId());
-            record.setUid(record.getId().toString());
-            if (byId==null){
-                continue;
-            }
-            if (roleType==2&&siteIds.contains(byId.getSiteId())){
-
-                tChargingOrderRefunds.add(record);
-            }
-        }
-        PageInfo<TChargingOrderRefund> data = refundList1.getData();
-
-        List<TChargingOrderRefund> res1 = testing4(tChargingOrderRefunds.size(), pageCurr, pageSize, tChargingOrderRefunds);
-        data.setTotal(tChargingOrderRefunds.size());
-        data.setRecords(res1);
-        return refundList1;
-
+        return chargingOrderService.getRefundList(chargingRefundDto);
     }
     
     
@@ -763,6 +1486,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){
@@ -881,6 +1606,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));
     }
 
 
@@ -1058,14 +1791,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);
+        }
     }
     
     
@@ -1132,6 +1872,12 @@
     
     
     
+    /**
+     * 安全检测等待窗口(秒):设备在此时长内未上报有效安全检测时,前端按「未插枪」提示用户,
+     * 超时订单由启动超时兜底任务自动取消,避免订单永久停留在启动中状态。
+     */
+    private static final long STARTUP_WAIT_SECONDS = 90L;
+
     @ResponseBody
     @GetMapping(value = "/preChargeCheck/{id}")
     @ApiOperation(value = "获取安全检测数据", tags = {"小程序-扫一扫"})
@@ -1141,10 +1887,17 @@
     public AjaxResult<PreChargeCheck> preChargeCheck(@PathVariable Integer id) {
         String key = "AQJC_" + id;
         PreChargeCheck cacheObject = redisService.getCacheObject(key);
-        if(null != cacheObject){
-            if(LocalDateTime.now().minusMinutes(1).isAfter(cacheObject.getAddTime())){
-                redisService.deleteObject(key);
-                cacheObject = null;
+        if (null != cacheObject) {
+            LocalDateTime addTime = cacheObject.getAddTime();
+            // 等待安全检测超出窗口且启动指令尚未下发时,按「未插枪」提示前端;
+            // 缓存必须保留:设备安全检测上报依赖该缓存推进启动,删除会导致订单永久卡在启动中
+            if (Integer.valueOf(1).equals(cacheObject.getStartupSuccess())
+                    && !Boolean.TRUE.equals(cacheObject.getStartCommandSent())
+                    && null != addTime
+                    && LocalDateTime.now().isAfter(addTime.plusSeconds(STARTUP_WAIT_SECONDS))) {
+                cacheObject.setStartupSuccess(3);
+                cacheObject.setFailureCause(5);
+                redisService.setCacheObject(key, cacheObject, 24L, TimeUnit.HOURS);
             }
         }
         return AjaxResult.success(cacheObject);
@@ -1173,28 +1926,53 @@
     })
     public AjaxResult stopCharging(@PathVariable String id) {
         log.info("小程序主动发起停止充电,订单ID:{}", id);
+        // VIN 码充电订单路由:VD 订单存于 t_vin_charging_order,不在 t_charging_order;
+        // VD 表存在该 ID 订单时优先走 VIN 停充(内部按状态返回准确的“不能重复操作/还未开始充电”),
+        // 其余情况回落普通停充。雪花 ID 两表同源生成,撞号概率可忽略
+        TVinChargingOrder vinOrder = null;
+        try {
+            vinOrder = vinChargingOrderService.getById(Long.valueOf(id));
+        } catch (NumberFormatException ignored) {
+            // 非数字订单ID,按普通停充处理
+        }
+        if (vinOrder != null) {
+            return vinChargingOrderService.stopChargingByApplet(id);
+        }
         return chargingOrderService.stopCharging(id);
     }
     
     
     /**
-     * 停止充电应答处理逻辑
+     * 停止充电应答处理逻辑(普通订单原逻辑 + 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);
     }
 
@@ -1206,13 +1984,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);
@@ -1224,9 +2009,7 @@
             }
 
         }
-
-        return R.ok(sixChargingDtos);
-
+        return sixChargingDtos;
     }
 
 
@@ -1271,13 +2054,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());
@@ -1358,23 +2141,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){
-            BigDecimal data = parkingLotClient.getRecordAmount().getData();
+            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);
@@ -1389,11 +2188,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));
     }
@@ -1406,7 +2205,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();
@@ -1424,10 +2224,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;
     }
 
     
@@ -1523,29 +2351,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")
@@ -2470,25 +3414,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);
+        }
     }
 
 
@@ -2659,9 +3615,10 @@
     @ResponseBody
     @GetMapping(value = "/getStatisticsOfBattery")
     @ApiOperation(value = "新能源汽车电池安全检测次数统计", tags = {"充电桩数据大屏"})
-    public R<StatisticsOfBatteryVO> getStatisticsOfBattery(){
+    public R<StatisticsOfBatteryVO> getStatisticsOfBattery(
+            @RequestParam(value = "siteIds", required = false) List<Integer> siteIds){
 
-        return chargingOrderService.getStatisticsOfBattery();
+        return chargingOrderService.getStatisticsOfBattery(siteIds);
     }
 
     /**
@@ -2674,6 +3631,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