From a9f8225832b24f04d174e8002365db63ad4f482b Mon Sep 17 00:00:00 2001
From: longz <longzhaoz@qq.com>
Date: 星期三, 05 八月 2026 15:01:57 +0800
Subject: [PATCH] fix: shorten franchisee gun labels

---
 ruoyi-service/ruoyi-order/src/main/java/com/ruoyi/order/controller/TChargingOrderController.java | 1303 +++++++++++++++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 1,174 insertions(+), 129 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 c22641d..8d789e7 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
@@ -1,8 +1,11 @@
 package com.ruoyi.order.controller;
+import cn.afterturn.easypoi.excel.ExcelExportUtil;
+import cn.afterturn.easypoi.excel.entity.ExportParams;
 import com.alibaba.fastjson2.JSON;
 import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 
+import java.io.IOException;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.text.DecimalFormat;
@@ -12,14 +15,20 @@
 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.model.TPartnerAppUser;
+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;
@@ -49,17 +58,33 @@
 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;
+import com.ruoyi.payment.api.vo.IcbcRefundResp;
+import com.ruoyi.payment.api.vo.IcbcSubOrderRefundResp;
 import com.ruoyi.system.api.domain.SysUser;
 import com.ruoyi.system.api.feignClient.SysUserClient;
 import com.ruoyi.system.api.feignClient.SysUserRoleClient;
@@ -72,10 +97,20 @@
 import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.net.URLEncoder;
 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;
+import com.ruoyi.common.core.utils.WebUtils;
+import org.apache.poi.ss.usermodel.Workbook;
 
 /**
  * <p>
@@ -135,10 +170,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
@@ -152,7 +193,622 @@
     @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);
+        Map<String, Object> summary = new LinkedHashMap<>();
+        summary.put("orderAmountWan", sum(dayStats, FranchiseeDayStat::getOrderAmount).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
+        summary.put("serviceFeeWan", sum(dayStats, FranchiseeDayStat::getServiceFee).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
+        summary.put("chargingPowerWan", sum(dayStats, FranchiseeDayStat::getCapacity).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP));
+        summary.put("chargingAmount", sum(dayStats, FranchiseeDayStat::getPaymentAmount));
+        summary.put("chargingOrderCount", dayStats.stream().mapToLong(stat -> numberValue(stat.getOrderCount())).sum());
+        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::getOrderAmountEffective));
+        result.put("keyDataRing", franchiseePhaseRing(siteIds, range));
+        result.put("orderStats", franchiseeOrderTrend(dayStats, range));
+        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));
+        List<Map<String, Object>> incomePie = new ArrayList<>();
+        Map<String, Object> electricityItem = new LinkedHashMap<>();
+        electricityItem.put("name", "充电费");
+        electricityItem.put("value", electricity);
+        incomePie.add(electricityItem);
+        Map<String, Object> serviceItem = new LinkedHashMap<>();
+        serviceItem.put("name", "服务费");
+        serviceItem.put("value", service);
+        incomePie.add(serviceItem);
+        result.put("incomePie", incomePie);
+        return R.ok(result);
+    }
+
+    @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());
+        }
+        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();
+            }
+        }
+        FranchiseeUserStatistics.Result userStatistics = FranchiseeUserStatistics.calculateByUserDays(
+                chargingUsersByDay, relations, 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()};
+    }
+
+    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 Map<String, Object> franchiseeOrderTrend(List<FranchiseeDayStat> stats, LocalDateTime[] range) {
+        if (franchiseeUseMonthlyTrend(range)) {
+            return franchiseeMonthlyOrderTrend(stats, range);
+        }
+        Map<String, Object> chart = franchiseeDailyTrend(stats, range, "充电金额", FranchiseeDayStat::getOrderAmountEffective);
+        ((List<Map<String, Object>>) chart.get("series")).get(0).put("type", "column");
+        Map<LocalDate, FranchiseeDayStat> byDay = dayStatByDay(stats);
+        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); FranchiseeDayStat stat = byDay.get(day); countData.add(BigDecimal.valueOf(stat == null ? 0L : numberValue(stat.getOrderCount()))); }
+        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;
+    }
+
+    /** Ranges longer than 31 days use monthly buckets so the mobile chart stays readable. */
+    private boolean franchiseeUseMonthlyTrend(LocalDateTime[] range) {
+        if (range == null || range.length < 2 || range[0] == null || range[1] == null) {
+            return false;
+        }
+        return range[0].toLocalDate().plusDays(31).isBefore(range[1].toLocalDate());
+    }
+
+    private Map<String, Object> franchiseeMonthlyOrderTrend(List<FranchiseeDayStat> stats, LocalDateTime[] range) {
+        Map<YearMonth, List<FranchiseeDayStat>> statsByMonth = stats.stream()
+                .filter(stat -> stat != null && stat.getStatDay() != null)
+                .collect(Collectors.groupingBy(stat -> YearMonth.from(stat.getStatDay())));
+        LocalDate start = range[0].toLocalDate();
+        LocalDate end = range[1].toLocalDate();
+        YearMonth firstMonth = YearMonth.from(start);
+        YearMonth lastMonth = YearMonth.from(end.minusDays(1));
+        List<String> categories = new ArrayList<>();
+        List<BigDecimal> amountData = new ArrayList<>();
+        List<BigDecimal> countData = new ArrayList<>();
+        for (YearMonth month = firstMonth; !month.isAfter(lastMonth); month = month.plusMonths(1)) {
+            List<FranchiseeDayStat> monthStats = statsByMonth.getOrDefault(month, Collections.emptyList());
+            categories.add(month.toString());
+            amountData.add(sum(monthStats, FranchiseeDayStat::getOrderAmountEffective));
+            countData.add(BigDecimal.valueOf(monthStats.stream().mapToLong(stat -> numberValue(stat.getOrderCount())).sum()));
+        }
+        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;
+    }
 
 
 
@@ -206,12 +862,233 @@
     }
 
     
+    @RequiresPermissions(value = {"/chargingUserAnalysis"}, logical = Logical.OR)
+    @ResponseBody
+    @PostMapping(value = "/enterprise/charging/analysis")
+    @ApiOperation(value = "企业用户充电分析", tags = {"管理后台-数据分析-企业用户充电分析"})
+    public R<PageInfo<EnterpriseChargingAnalysisVO>> enterpriseChargingAnalysis(@RequestBody EnterpriseChargingAnalysisQuery query) {
+        return chargingOrderService.enterpriseChargingAnalysis(query);
+    }
+
+    @RequiresPermissions(value = {"/chargingUserAnalysis"}, logical = Logical.OR)
+    @ResponseBody
+    @PostMapping(value = "/enterprise/charging/detail")
+    @ApiOperation(value = "企业用户充电明细", tags = {"管理后台-数据分析-企业用户充电分析"})
+    public R<PageInfo<EnterpriseChargingDetailVO>> enterpriseChargingDetail(@RequestBody EnterpriseChargingAnalysisQuery query) {
+        return chargingOrderService.enterpriseChargingDetail(query);
+    }
+
+    @RequiresPermissions(value = {"/chargingUserAnalysis"}, logical = Logical.OR)
+    @ResponseBody
+    @PutMapping(value = "/enterprise/charging/detail/export")
+    @ApiOperation(value = "企业用户充电明细导出", tags = {"管理后台-数据分析-企业用户充电分析"})
+    public void exportEnterpriseChargingDetail(@RequestBody EnterpriseChargingAnalysisQuery query) {
+        List<EnterpriseChargingDetailVO> records = chargingOrderService.enterpriseChargingDetailExport(query);
+        List<EnterpriseChargingDetailExport> exports = records.stream().map(this::buildEnterpriseChargingDetailExport).collect(Collectors.toList());
+        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), EnterpriseChargingDetailExport.class, exports);
+        HttpServletResponse response = WebUtils.response();
+        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
+        response.setCharacterEncoding("utf-8");
+        response.setHeader("Pragma", "no-cache");
+        response.setHeader("Cache-Control", "no-cache");
+        try {
+            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("企业用户充电明细.xls", "utf-8"));
+            try (ServletOutputStream outputStream = response.getOutputStream()) {
+                workbook.write(outputStream);
+            }
+            workbook.close();
+        } catch (IOException e) {
+            log.error("导出企业用户充电明细失败", e);
+        }
+    }
+
+    private EnterpriseChargingDetailExport buildEnterpriseChargingDetailExport(EnterpriseChargingDetailVO dto) {
+        EnterpriseChargingDetailExport export = new EnterpriseChargingDetailExport();
+        export.setCode(dto.getCode());
+        export.setOrderType(formatEnterpriseOrderType(dto.getOrderType()));
+        export.setOrderClassification(formatOrderClassification(dto.getOrderClassification()));
+        export.setSiteName(dto.getSiteName());
+        export.setTerminalName(dto.getTerminalName());
+        export.setStatus(formatPayOrderStatus(1, dto.getStatus()));
+        export.setChargingSecond(dto.getChargingSecond());
+        export.setTotalAmount(dto.getTotalAmount());
+        export.setCouponDiscountAmount(dto.getCouponDiscountAmount());
+        export.setVipDiscountAmount(dto.getVipDiscountAmount());
+        export.setPaymentAmount(dto.getPaymentAmount());
+        export.setRefundAmount(dto.getRefundAmount());
+        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) {
+        if (type == null) {
+            return "-";
+        }
+        if (type == 1) {
+            return "充电订单(小程序)";
+        }
+        if (type == 2) {
+            return "充电订单(刷卡)";
+        }
+        return "充电订单";
+    }
+
+    private String formatOrderClassification(Integer type) {
+        if (type == null) {
+            return "-";
+        }
+        return type == 1 ? "线上订单" : "线下订单";
+    }
+
+    private String formatOrderSource(Integer source) {
+        if (source == null) {
+            return "-";
+        }
+        if (source == 0) {
+            return "自有平台";
+        }
+        if (source == 1) {
+            return "第三方平台";
+        }
+        if (source == 2) {
+            return "引流平台";
+        }
+        return "其他";
+    }
+
     @RequiresPermissions(value = {"/invoiceManagement/select_order", "/paymentOrder/order"}, logical = Logical.OR)
     @ResponseBody
     @PostMapping(value = "/pay/order/list")
     @ApiOperation(value = "列表", tags = {"管理后台-支付订单-订单信息"})
     public R<PageInfo<PayOrderDto>> payOrderList(@RequestBody PayOrderQueryDto payOrderQueryDto) {
+        resolveInvoiceOrderIds(payOrderQueryDto);
         return chargingOrderService.payOrderQuery(payOrderQueryDto);
+    }
+
+    @RequiresPermissions(value = {"/invoiceManagement/select_order", "/invoiceManagement/export", "/paymentOrder/order"}, logical = Logical.OR)
+    @ResponseBody
+    @PutMapping(value = "/pay/order/export")
+    @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);
+        List<PayOrderDto> records = result.getData() == null || result.getData().getRecords() == null
+                ? Collections.emptyList() : result.getData().getRecords();
+        List<PayOrderExport> exports = records.stream().map(this::buildPayOrderExport).collect(Collectors.toList());
+        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), PayOrderExport.class, exports);
+        HttpServletResponse response = WebUtils.response();
+        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
+        response.setCharacterEncoding("utf-8");
+        response.setHeader("Pragma", "no-cache");
+        response.setHeader("Cache-Control", "no-cache");
+        try {
+            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单列表.xls", "utf-8"));
+            try (ServletOutputStream outputStream = response.getOutputStream()) {
+                workbook.write(outputStream);
+            }
+            workbook.close();
+        } 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) {
+        PayOrderExport export = new PayOrderExport();
+        export.setCode(dto.getCode());
+        export.setType(formatPayOrderType(dto.getType()));
+        export.setTitle(dto.getTitle());
+        export.setPhone(dto.getPhone());
+        export.setOrderStatus(dto.getPayTime() != null ? "订单支付成功" : "订单完成");
+        export.setStatus(formatPayOrderStatus(dto.getType(), dto.getStatus()));
+        export.setRefundStatus(dto.getRefundStatus() != null && dto.getRefundStatus() > 0 ? "有退款" : "无退款");
+        export.setRechargeAmount(dto.getRechargeAmount());
+        export.setPaymentAmount(dto.getPaymentAmount());
+        export.setFinalAmount(dto.getFinalAmount());
+        export.setCreateTime(dto.getCreateTime() == null ? null : DateUtils.localDateTimeToString(dto.getCreateTime()));
+        export.setEndTime(dto.getEndTime() == null ? null : DateUtils.localDateTimeToString(dto.getEndTime()));
+        export.setPayTime(dto.getPayTime() == null ? null : DateUtils.localDateTimeToString(dto.getPayTime()));
+        return export;
+    }
+
+    private String formatPayOrderType(Integer type) {
+        if (type == null || type < 1 || type > 4) {
+            return "-";
+        }
+        return new String[]{"充电订单", "购物订单", "vip订单", "停车订单"}[type - 1];
+    }
+
+    private String formatPayOrderStatus(Integer type, Integer status) {
+        if (type == null) {
+            return "-";
+        }
+        if (type == 3) {
+            return "支付成功";
+        }
+        if (status == null) {
+            return "-";
+        }
+        if (type == 1 && status >= 0 && status <= 5) {
+            return new String[]{"未知", "等待中", "启动中", "充电中", "停止中", "已结束"}[status];
+        }
+        if (type == 2 && status >= 1 && status <= 4) {
+            return new String[]{"待发货", "待收货", "已完成", "已取消"}[status - 1];
+        }
+        if (type == 4 && status >= 1 && status <= 3) {
+            return new String[]{"已进场", "已出场", "已缴费出场"}[status - 1];
+        }
+        return "-";
     }
 
 
@@ -246,6 +1123,22 @@
     public R refund(@RequestBody PayOrderRefundDto payOrderQueryDto) {
         return chargingOrderService.payRefund(payOrderQueryDto);
     }
+
+    @ResponseBody
+    @PostMapping(value = "/pay/order/special/refund/query")
+    @RequiresPermissions(value = {"/paymentOrder/specialRefund", "/paymentOrder/specialRefund/refund"}, logical = Logical.OR)
+    @ApiOperation(value = "特殊退款查询", tags = {"管理后台-支付订单-特殊退款处理"})
+    public R<PayOrderInfoDto> specialRefundQuery(@RequestBody PayOrderRefundDto payOrderQueryDto) {
+        return chargingOrderService.getSpecialRefundOrder(payOrderQueryDto);
+    }
+
+    @ResponseBody
+    @PostMapping(value = "/pay/order/special/refund")
+    @RequiresPermissions(value = {"/paymentOrder/specialRefund/refund"}, logical = Logical.OR)
+    @ApiOperation(value = "特殊退款", tags = {"管理后台-支付订单-特殊退款处理"})
+    public R specialRefund(@RequestBody PayOrderRefundDto payOrderQueryDto) {
+        return chargingOrderService.specialRefund(payOrderQueryDto);
+    }
     
     
     @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR)
@@ -266,6 +1159,12 @@
                 payOrderInfoDto.setRefundAmount(byId.getRefundAmount());
                 payOrderInfoDto.setRechargeAmount(byId.getRechargeAmount());
                 payOrderInfoDto.setFinalAmount(byId.getRechargeAmount().subtract(byId.getRefundAmount()));
+                payOrderInfoDto.setPayMethod(byId.getPayMethod());
+                payOrderInfoDto.setBalancePayAmount(byId.getBalancePayAmount());
+                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);
@@ -406,59 +1305,24 @@
     
     
     
-    @RequiresPermissions(value = {"/paymentOrder/refund"}, logical = Logical.OR)
+    @RequiresPermissions(value = {"/paymentOrder/refund", "/paymentOrder/order", "/paymentOrder/specialRefund"}, logical = Logical.OR)
     @ResponseBody
     @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);
     }
     
     
@@ -507,9 +1371,35 @@
     @PostMapping(value = "/chargingOrder")
     @ApiOperation(value = "充电桩订单列表", tags = {"管理后台-订单管理"})
     public AjaxResult<TCharingOrderVO> chargingOrder(@RequestBody ChargingOrderQuery dto) {
-        List<Long> data = appUserClient.getUserIdsByPhone(dto.getPhone()).getData();
-        dto.setUserIds(data);
         TCharingOrderVO res = chargingOrderService.chargingOrder(dto);
+        return AjaxResult.success(res);
+    }
+
+    @RequiresPermissions(value = {"/chargingPileOrder"}, logical = Logical.OR)
+    @ResponseBody
+    @PostMapping(value = "/chargingOrder/list")
+    @ApiOperation(value = "充电桩订单分页列表", tags = {"管理后台-订单管理"})
+    public AjaxResult<PageInfo<ChargingOrderVO>> chargingOrderList(@RequestBody ChargingOrderQuery dto) {
+        PageInfo<ChargingOrderVO> res = chargingOrderService.chargingOrderList(dto);
+        return AjaxResult.success(res);
+    }
+
+    @RequiresPermissions(value = {"/chargingPileOrder"}, logical = Logical.OR)
+    @ResponseBody
+    @PostMapping(value = "/chargingOrder/summary")
+    @ApiOperation(value = "充电桩订单汇总", tags = {"管理后台-订单管理"})
+    public AjaxResult<TCharingOrderVO> chargingOrderSummary(@RequestBody ChargingOrderQuery dto) {
+        TCharingOrderVO res = chargingOrderService.chargingOrderSummary(dto);
+        return AjaxResult.success(res);
+    }
+
+
+    @RequiresPermissions(value = {"/chargingPileOrder"}, logical = Logical.OR)
+    @ResponseBody
+    @PostMapping(value = "/balanceIncomeDetail")
+    @ApiOperation(value = "充电桩订单余额收入明细", tags = {"管理后台-订单管理"})
+    public AjaxResult<List<ChargingOrderBalanceIncomeDetailVO>> balanceIncomeDetail(@RequestBody ChargingOrderQuery dto) {
+        List<ChargingOrderBalanceIncomeDetailVO> res = chargingOrderService.balanceIncomeDetail(dto);
         return AjaxResult.success(res);
     }
 
@@ -645,6 +1535,14 @@
         return R.ok(count);
     }
 
+    /**
+     * 查询指定站点中实际发生过充电的用户ID
+     */
+    @PostMapping(value = "/getAppUserIdsBySiteIds")
+    public R<List<Long>> getAppUserIdsBySiteIds(@RequestBody List<Integer> siteIds) {
+        return R.ok(chargingOrderService.getAppUserIdsBySiteIds(siteIds));
+    }
+
 
 
     //订单详情
@@ -746,6 +1644,55 @@
     @ApiOperation(value = "支付充电充值费用", tags = {"小程序-扫一扫"})
     public AjaxResult paymentChargingOrder(@RequestBody AddChargingOrder addChargingOrder) {
         return chargingOrderService.paymentChargingOrder(addChargingOrder);
+    }
+
+    @ResponseBody
+    @GetMapping(value = "/confirmIcbcPayment")
+    @ApiOperation(value = "主动确认工行充电支付结果", tags = {"小程序-扫一扫"})
+    public AjaxResult confirmIcbcPayment(@RequestParam("orderCode") String orderCode) {
+        return chargingOrderService.confirmIcbcPayment(orderCode);
+    }
+
+    @RequiresPermissions(value = {"/chargingPileOrder", "/paymentOrder/refund"}, logical = Logical.AND)
+    @PostMapping("/icbc/fund/payment-query")
+    @ApiOperation(value = "管理后台查询工行支付订单", tags = {"后台-充电桩订单"})
+    public AjaxResult<IcbcPaymentResp> queryIcbcAdminPayment(@RequestBody IcbcAdminFundOperationReq request) {
+        return AjaxResult.success(chargingOrderService.queryIcbcAdminPayment(request == null ? null : request.getOrderCode()));
+    }
+
+    @RequiresPermissions(value = {"/chargingPileOrder", "/paymentOrder/refund"}, logical = Logical.AND)
+    @PostMapping("/icbc/fund/refund")
+    @ApiOperation(value = "管理后台工行主订单退款", tags = {"后台-充电桩订单"})
+    public AjaxResult<IcbcRefundResp> refundIcbcAdminPayment(@RequestBody IcbcAdminFundOperationReq request) {
+        return AjaxResult.success(chargingOrderService.refundIcbcAdminPayment(request));
+    }
+
+    @RequiresPermissions(value = {"/chargingPileOrder", "/paymentOrder/refund"}, logical = Logical.AND)
+    @PostMapping("/icbc/fund/sub-orders")
+    @ApiOperation(value = "管理后台查询工行分账子订单", tags = {"后台-充电桩订单"})
+    public AjaxResult<List<IcbcAdminSubOrderVO>> queryIcbcAdminSubOrders(@RequestBody IcbcAdminFundOperationReq request) {
+        return AjaxResult.success(chargingOrderService.queryIcbcAdminSubOrders(request == null ? null : request.getOrderCode()));
+    }
+
+    @RequiresPermissions(value = {"/chargingPileOrder", "/paymentOrder/refund"}, logical = Logical.AND)
+    @PostMapping("/icbc/fund/sub-order-refund")
+    @ApiOperation(value = "管理后台工行分账子订单退款", tags = {"后台-充电桩订单"})
+    public AjaxResult<IcbcSubOrderRefundResp> refundIcbcAdminSubOrder(@RequestBody IcbcAdminFundOperationReq request) {
+        return AjaxResult.success(chargingOrderService.refundIcbcAdminSubOrder(request));
+    }
+
+    @ResponseBody
+    @GetMapping("/simulation/current")
+    @ApiOperation(value = "查询当前枪可模拟结算的已支付订单", tags = {"小程序-模拟充电"})
+    public AjaxResult<ChargingSimulationVO> getCurrentSimulationOrder(@RequestParam("gunId") Integer gunId) {
+        return AjaxResult.success(chargingOrderService.getCurrentSimulationOrder(gunId));
+    }
+
+    @ResponseBody
+    @PostMapping("/simulation/complete")
+    @ApiOperation(value = "模拟完成充电并执行真实结算", tags = {"小程序-模拟充电"})
+    public AjaxResult<ChargingSimulationVO> completeSimulation(@RequestBody ChargingSimulationReq request) {
+        return AjaxResult.success(chargingOrderService.completeSimulation(request));
     }
     
     /**
@@ -853,7 +1800,13 @@
     })
     public AjaxResult<PreChargeCheck> preChargeCheck(@PathVariable Integer id) {
         String key = "AQJC_" + id;
-        Object cacheObject = redisService.getCacheObject(key);
+        PreChargeCheck cacheObject = redisService.getCacheObject(key);
+        if(null != cacheObject){
+            if(LocalDateTime.now().minusMinutes(1).isAfter(cacheObject.getAddTime())){
+                redisService.deleteObject(key);
+                cacheObject = null;
+            }
+        }
         return AjaxResult.success(cacheObject);
     }
     
@@ -913,25 +1866,16 @@
     @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();
-        //如果没传siteId,获取当前登陆人所有的siteIds
-        List<Integer> siteIds = new ArrayList<>();
-        if (siteId==null){
-            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
-            for (GetSiteListDTO datum : data) {
-                siteIds.add(datum.getId());
-            }
-        }else {
-            siteIds.add(siteId);
-        }
-        if (siteIds.isEmpty()){
-            siteIds.add(-1);
-        }
+        SysUser sysUser = sysUserClient.getSysUser(userId).getData();
+        boolean partnerView = isPartnerView(sysUser);
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
         LocalDate sixBefore = PreviousSixMonths.get();
         //通过siteIds进行sql查询统计
-        List<SixChargingDto> sixChargingDtos = generateLastSixMonths();
-        List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds);
+        List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds, false);
+        LocalDate statisticsEndMonth = resolveStatisticsEndMonth(LocalDate.now(), chargingDtos);
+        List<SixChargingDto> sixChargingDtos = generateLastSixMonths(statisticsEndMonth);
         for (SixChargingDto sixChargingDto : sixChargingDtos) {
             for (SixChargingDto chargingDto : chargingDtos) {
                 if (sixChargingDto.getMonth().equals(chargingDto.getMonth())){
@@ -947,12 +1891,15 @@
 
 
     public static List<SixChargingDto> generateLastSixMonths() {
-        LocalDate today = LocalDate.now();
+        return generateLastSixMonths(LocalDate.now());
+    }
+
+    static List<SixChargingDto> generateLastSixMonths(LocalDate endMonth) {
         List<SixChargingDto> months = new ArrayList<>();
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
 
         for (int i = 5; i >= 0; i--) {
-            LocalDate date = today.minusMonths(i);
+            LocalDate date = endMonth.minusMonths(i);
             String month = date.format(formatter);
             SixChargingDto sixChargingDto = new SixChargingDto();
             sixChargingDto.setMonth(month);
@@ -961,25 +1908,36 @@
 
         return months;
     }
+
+    static LocalDate resolveStatisticsEndMonth(LocalDate currentDate, List<SixChargingDto> statistics) {
+        if (statistics == null || statistics.isEmpty()) {
+            return currentDate;
+        }
+        int nextMonth = currentDate.plusMonths(1).getMonthValue();
+        boolean hasNextMonthData = statistics.stream()
+                .map(SixChargingDto::getMonth)
+                .filter(Objects::nonNull)
+                .anyMatch(month -> {
+                    try {
+                        return Integer.parseInt(month) == nextMonth;
+                    } catch (NumberFormatException ignored) {
+                        return false;
+                    }
+                });
+        return hasNextMonthData ? currentDate.plusMonths(1) : currentDate;
+    }
     
     @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
     @ResponseBody
     @GetMapping(value = "/six/circle")
     @ApiOperation(value = "电站收入占比", tags = {"后台-数据分析-平台收入分析"})
-    public R<List<SixCircleDto>> circle() {
+    public R<List<SixCircleDto>> circle(Integer siteId, Integer partnerId) {
         Long userId = tokenService.getLoginUser().getUserid();
-        //获取当前登录的siteIds
-        List<Integer> siteIds = new ArrayList<>();
-            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
-            for (GetSiteListDTO datum : data) {
-                siteIds.add(datum.getId());
-            }
-        //进行统计groupBySiteId
+        SysUser sysUser = sysUserClient.getSysUser(userId).getData();
+        boolean partnerView = isPartnerView(sysUser);
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
         LocalDate sixBefore = PreviousSixMonths.get();
-            if (siteIds.isEmpty()){
-                siteIds.add(-1);
-            }
-        List<SixCircleDto> sixCircleDtos = chargingOrderService.circle(siteIds,sixBefore);
+        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());
@@ -1053,31 +2011,28 @@
     
     
     
-    
+    /**
+     * 查询平台收入分析底部数据分类,充电订单金额由数据库聚合,避免全量订单和计费明细加载超时。
+     */
     @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
     @ResponseBody
     @GetMapping(value = "/six/total")
     @ApiOperation(value = "底部数据分类", tags = {"后台-数据分析-平台收入分析"})
-    public R<Map<String,Object>> total() {
+    public R<Map<String,Object>> total(Integer siteId, Integer partnerId) {
         //count近6个月的数据
         Long userId = tokenService.getLoginUser().getUserid();
         SysUser sysUser = sysUserClient.getSysUser(userId).getData();
-        //获取当前登录的siteIds
-        List<Integer> siteIds = new ArrayList<>();
-        List<GetSiteListDTO> data9 = siteClient.getSiteListByUserId(userId).getData();
-        for (GetSiteListDTO datum : data9) {
-            siteIds.add(datum.getId());
+        boolean partnerView = isPartnerView(sysUser);
+        List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId);
+        Map<String,Object>  map = chargingOrderService.countAll(siteIds, false);
+        if (map == null) {
+            map = new HashMap<String,Object>();
         }
-        //进行统计groupBySiteId
-        if (siteIds.isEmpty()){
-            siteIds.add(-1);
-        }
-        Map<String,Object>  map = chargingOrderService.countAll(siteIds);
-        if(1 == sysUser.getObjectId()){
-            BigDecimal data = parkingLotClient.getRecordAmount().getData();
-            if (map ==null){
-                map = new HashMap<String,Object>();
-            }
+        boolean platformVisible = !partnerView;
+        if(platformVisible){
+            R<BigDecimal> parkingAmountResult = parkingLotClient.getRecordAmount(siteIds);
+            BigDecimal data = parkingAmountResult == null || parkingAmountResult.getData() == null
+                    ? BigDecimal.ZERO : parkingAmountResult.getData();
             map.put("parkingAmount",data);
             BigDecimal data1 =   shoppingOrderService.getSumAmount();
             map.put("shopAmount",data1);
@@ -1088,33 +2043,82 @@
             map.put("shopAmount",0);
             map.put("vipAmount",0);
         }
-        List<TChargingOrder> list = chargingOrderService.lambdaQuery().eq(TChargingOrder::getStatus, 5).eq(TChargingOrder::getDelFlag, 0)
-                .eq(TChargingOrder::getRechargePaymentStatus, 2).in(TChargingOrder::getSiteId, siteIds).list();
-        BigDecimal sharingAmount = BigDecimal.ZERO;
-        BigDecimal commissionAmount = BigDecimal.ZERO;
-        //计算list中electrovalence的总和
-        BigDecimal totalElectrovalence = BigDecimal.ZERO;
-        //计算list中serviceCharge的总和
-        BigDecimal totalServiceCharge = BigDecimal.ZERO;
-        List<TChargingOrderAccountingStrategy> accountingStrategyList = chargingOrderAccountingStrategyService.list();
-        for (TChargingOrder order : list) {
-            List<TChargingOrderAccountingStrategy> collect = accountingStrategyList.stream().filter(s -> s.getChargingOrderId().equals(order.getId())).collect(Collectors.toList());
-            BigDecimal periodElectricPrice = collect.stream().map(TChargingOrderAccountingStrategy::getPeriodElectricPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-            BigDecimal periodServicePrice = collect.stream().map(TChargingOrderAccountingStrategy::getPeriodServicePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-            totalElectrovalence = totalElectrovalence.add(periodElectricPrice);
-            if(2 != order.getOrderSource()){
-                totalServiceCharge = totalServiceCharge.add(periodServicePrice);
-                commissionAmount = commissionAmount.add((periodElectricPrice.add(periodServicePrice)).multiply(new BigDecimal("0.006")));
-            }else{
-                totalServiceCharge = totalServiceCharge.add(periodServicePrice.multiply(new BigDecimal("0.8")));
-                sharingAmount = sharingAmount.add(periodServicePrice.multiply(new BigDecimal("0.2")));
+        map.put("platformIncomeVisible", platformVisible);
+        return R.ok(map);
+    }
+
+    @RequiresPermissions(value = {"/platformRevenueAnalysis"}, logical = Logical.OR)
+    @ResponseBody
+    @GetMapping(value = "/six/pay-type-circle")
+    @ApiOperation(value = "收入类型占比", tags = {"后台-数据分析-平台收入分析"})
+    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, partnerId);
+        LocalDate sixBefore = PreviousSixMonths.get();
+        return R.ok(chargingOrderService.payTypeCircle(sixBefore, siteIds, false));
+    }
+
+    private boolean isPartnerView(SysUser sysUser) {
+        return sysUser != null && Integer.valueOf(2).equals(sysUser.getRoleType());
+    }
+
+    /**
+     * 解析平台收入分析页面允许查看的站点范围。
+     * 合作商使用授权站点,其他后台账号沿用用户站点列表;传入站点时需做授权校验。
+     */
+    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();
+            if (authSiteIds != null) {
+                siteIds.addAll(authSiteIds);
+            }
+        } else {
+            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
+            if (data != null) {
+                for (GetSiteListDTO datum : data) {
+                    siteIds.add(datum.getId());
+                }
             }
         }
-        map.put("service_charge",totalServiceCharge.setScale(2, BigDecimal.ROUND_HALF_EVEN));
-        map.put("electrovalence",totalElectrovalence.setScale(2, BigDecimal.ROUND_HALF_EVEN));
-        map.put("commission_amount",commissionAmount.setScale(2, BigDecimal.ROUND_HALF_EVEN));
-        map.put("sharing_amount",sharingAmount.setScale(2, BigDecimal.ROUND_HALF_EVEN));
-        return R.ok(map);
+        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;
     }
 
     
@@ -1850,13 +2854,19 @@
             Long userId = tokenService.getLoginUser().getUserid();
             //获取当前登录的siteIds
             List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
-            for (GetSiteListDTO datum : data) {
-                siteIds.add(datum.getId());
+            if (data != null) {
+                for (GetSiteListDTO datum : data) {
+                    siteIds.add(datum.getId());
+                }
             }
         } else {
             siteIds.add(statisticsQueryDto.getSiteId());
         }
-        String format = statisticsQueryDto.getSelectDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+        if (siteIds.isEmpty()) {
+            siteIds.add(-1);
+        }
+        LocalDateTime selectDate = statisticsQueryDto.getSelectDate() == null ? LocalDateTime.now() : statisticsQueryDto.getSelectDate();
+        String format = selectDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
         Map<String, Object> stringObjectMap = chargingOrderService.getChargingOrderCount(siteIds, format);
         //当日的订单总数
         int size = 0;
@@ -1869,10 +2879,10 @@
         //计算list中charging_capacity的总和
         BigDecimal totalChargingCapacity = BigDecimal.ZERO;
         if(null != stringObjectMap){
-            size = Integer.parseInt(stringObjectMap.get("num").toString());
-            totalElectrovalence = new BigDecimal(stringObjectMap.get("electrovalence").toString());
-            totalServiceCharge = new BigDecimal(stringObjectMap.get("servicecharge").toString());
-            totalChargingCapacity = new BigDecimal(stringObjectMap.get("electricity").toString());
+            size = getWorkChargeInt(stringObjectMap, "num");
+            totalElectrovalence = getWorkChargeDecimal(stringObjectMap, "electrovalence");
+            totalServiceCharge = getWorkChargeDecimal(stringObjectMap, "servicecharge");
+            totalChargingCapacity = getWorkChargeDecimal(stringObjectMap, "electricity");
             totalPaymentAmount = totalElectrovalence.add(totalServiceCharge);
         }
         
@@ -1883,6 +2893,31 @@
         tCharingWorkVO.setTotalServiceCharge(totalServiceCharge);
         tCharingWorkVO.setTotalChargingCapacity(totalChargingCapacity);
         return R.ok(tCharingWorkVO);
+    }
+
+    private int getWorkChargeInt(Map<String, Object> map, String key) {
+        Object value = map.get(key);
+        if (value == null) {
+            return 0;
+        }
+        if (value instanceof Number) {
+            return ((Number) value).intValue();
+        }
+        return Integer.parseInt(value.toString());
+    }
+
+    private BigDecimal getWorkChargeDecimal(Map<String, Object> map, String key) {
+        Object value = map.get(key);
+        if (value == null) {
+            return BigDecimal.ZERO;
+        }
+        if (value instanceof BigDecimal) {
+            return (BigDecimal) value;
+        }
+        if (value instanceof Number) {
+            return BigDecimal.valueOf(((Number) value).doubleValue());
+        }
+        return new BigDecimal(value.toString());
     }
     
     
@@ -2315,9 +3350,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);
     }
 
     /**
@@ -2330,6 +3366,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