MerchantAnalysisController.java 19.5 KB
package cn.com.glsx.dj.strategy.controller;

import cn.com.glsx.dj.mindworkplate.dto.monitoring.MonitorFilterRequest;
import cn.com.glsx.dj.mindworkplate.dto.monitoring.StoreItemResponse;
import cn.com.glsx.dj.mindworkplate.dto.warning.EarlyWarningThresholdConfigHistoryDTO;
import cn.com.glsx.dj.mindworkplate.model.EarlyWarningThresholdConfig;
import cn.com.glsx.dj.mindworkplate.model.MonitorTypeDict;
import cn.com.glsx.dj.mindworkplate.remote.EarlyWarningMsgRemote;
import cn.com.glsx.dj.mindworkplate.remote.MonitoringRemote;
import cn.com.glsx.dj.mindworkplate.remote.WarningMsgRemote;
import cn.com.glsx.dj.peanalysis.dto.req.output.SceneBaseReq;
import cn.com.glsx.dj.peanalysis.dto.res.output.EmployeeDetailSummaryResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.GoodsCategorySummaryResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreDetailSummaryResponse;
import cn.com.glsx.dj.peanalysis.dto.strategy.StaffAnalysisDTO;
import cn.com.glsx.dj.peanalysis.remote.BusinessSceneAnalysisRemote;
import cn.com.glsx.dj.smartcarlife.dto.merchant.CarBrandDTO;
import cn.com.glsx.dj.strategy.dto.OperatorResponse;
import cn.com.glsx.dj.strategy.dto.SceneMerchantBaseParam;
import cn.com.glsx.dj.strategy.dto.StaffHistoryRecordDTO;
import cn.com.glsx.dj.strategy.dto.StaffSummaryDTO;
import cn.com.glsx.dj.strategy.remote.StrategyInfoRemote;
import cn.com.glsx.dj.strategy.request.MerchantStaffHistoryRecordRequest;
import cn.com.glsx.dj.strategy.request.MonitorDictRopRequest;
import cn.com.glsx.dj.strategy.request.MonitorFilterRopRequest;
import cn.com.glsx.dj.strategy.request.SceneMerchantBaseRequest;
import cn.com.glsx.dj.strategy.response.MerchantDetailResponse;
import cn.com.glsx.dj.strategy.service.LoginService;
import cn.com.glsx.dj.strategy.service.StrategyDetailService;
import cn.com.glsx.dj.strategy.uitl.CommonUtil;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.com.glsx.framework.rop.response.RopResponse;
import cn.com.glsx.merchants.model.response.merchant.MerchantBasicInfoListResponse;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@ServiceMethodBean(version = "1.0.0", needInSession = NeedInSessionType.YES)
@Api("策略中心-门店看板")
public class MerchantAnalysisController {

    @Autowired
    private BusinessSceneAnalysisRemote businessSceneAnalysisRemote;

    @Autowired
    private StrategyInfoRemote strategyInfoRemote;

    @Autowired
    private MonitoringRemote monitoringRemote;
    @Autowired
    private LoginService loginService;

    @Autowired
    private EarlyWarningMsgRemote earlyWarningMsgRemote;

    @Autowired
    private Environment environment;

    @Autowired
    private StrategyDetailService strategyDetailService;

    @Resource
    private WarningMsgRemote warningMsgRemote;

    @ApiOperation("查询驻店员工列表")
    @ServiceMethod(method = "dj.api.strategy.staff.list.analysis")
    public RopResponse<List<StaffAnalysisDTO>> listStaffAnalysis(SceneMerchantBaseRequest request) {
        try {
            SceneBaseReq req = CommonUtil.convertRequest(SceneBaseReq.class);
            RpcResponse<List<StaffAnalysisDTO>> response = businessSceneAnalysisRemote.listStaffAnalysis(req);
            if (response.hasError()) {
                log.error(response.getMessage());
                return RopResponse.error(response.getError(), response.getMessage());
            }
            return RopResponse.success(response.getResult());
        } catch (RpcServiceException e) {
            log.error("=====dj.api.strategy.staff.list.analysis rpcServiceException:{}", e.getMessage());
            return RopResponse.error(e);
        } catch (Exception e) {
            log.error("=====dj.api.strategy.staff.list.analysis exception:{}", e.getMessage(), e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("查询门店预警信息列表")
    @ServiceMethod(method = "dj.api.strategy.merchant.list.warningInfo")
    public RopResponse<List<String>> listMerchantWarningInfo(SceneMerchantBaseRequest request) {
        try {
            SceneBaseReq req = CommonUtil.convertRequest(SceneBaseReq.class);
            RpcResponse<List<String>> response = businessSceneAnalysisRemote.listMerchantWarningInfo(req);
            if (response.hasError()) {
                log.error(response.getMessage());
                return RopResponse.error(response.getError(), response.getMessage());
            }
            return RopResponse.success(response.getResult());
        } catch (RpcServiceException e) {
            log.error("=====dj.api.strategy.merchant.list.warningInfo rpcServiceException:{}", e.getMessage());
            return RopResponse.error(e);
        } catch (Exception e) {
            log.error("=====dj.api.strategy.merchant.list.warningInfo exception:{}", e.getMessage(), e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("查询驻店员工时长信息")
    @ServiceMethod(method = "dj.api.strategy.staff.summary.duration")
    public RopResponse<StaffSummaryDTO> summaryStaffDuration(SceneMerchantBaseRequest request) {
        try {
            SceneMerchantBaseParam req = CommonUtil.convertRequest(SceneMerchantBaseParam.class);
            RpcResponse<StaffSummaryDTO> response = strategyInfoRemote.summaryStaffDuration(req);
            if (response.hasError()) {
                log.error(response.getMessage());
                return RopResponse.error(response.getError(), response.getMessage());
            }
            return RopResponse.success(response.getResult());
        } catch (RpcServiceException e) {
            log.error("=====dj.api.strategy.staff.list.analysis rpcServiceException:{}", e.getMessage());
            return RopResponse.error(e);
        } catch (Exception e) {
            log.error("=====dj.api.strategy.staff.list.analysis exception:{}", e.getMessage(), e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-门店分析-门店经营概况")
    @ServiceMethod(method = "dj.api.strategy.merchant.analysis.store.detail.summary", needInSession = NeedInSessionType.YES)
    public RopResponse<StoreDetailSummaryResponse> merchantDetailSummary(SceneMerchantBaseRequest request) {
        try {
            SceneBaseReq req = CommonUtil.convertRequest(SceneBaseReq.class);
            RpcResponse<StoreDetailSummaryResponse> response = businessSceneAnalysisRemote.storeDetailSummary(req);
            if (response.isSuccess()) {
                return RopResponse.success(response.getResult());
            }
            return RopResponse.error(response.getMessage());
        } catch (Exception e) {
            log.error("接口异常", e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-门店商品品类分析")
    @ServiceMethod(method = "dj.api.strategy.merchant.analysis.goods.summary.withWarn", needInSession = NeedInSessionType.YES)
    public RopResponse<GoodsCategorySummaryResponse> merchantGoodsSummaryWithWarm(SceneMerchantBaseRequest request) {
        try {
            SceneBaseReq req = CommonUtil.convertRequest(SceneBaseReq.class);
            RpcResponse<GoodsCategorySummaryResponse> response = businessSceneAnalysisRemote.goodsSummary(req);
            if (response.isSuccess()) {
                GoodsCategorySummaryResponse result = Optional.ofNullable(response.getResult()).orElse(new GoodsCategorySummaryResponse());

                // 处理兜底指标
                Optional.ofNullable(req.getMerchantIds())
                        .filter(CollUtil::isNotEmpty)
                        .flatMap(list -> Optional.ofNullable(list.get(0)).map(ObjectUtil::toString))
                        .filter(StrUtil::isNotEmpty)
                        .ifPresent(merchantId -> {
                            RpcResponse<EarlyWarningThresholdConfig> warningConfigRes = warningMsgRemote.findByMerchantNo(merchantId);
                            if (!warningConfigRes.hasResult()) {
                                log.error("兜底预警目标配置查询异常: {}", warningConfigRes);
                                return;
                            }
                            EarlyWarningThresholdConfig warningConfig = warningConfigRes.getResult();
                            // 电池转化率
                            result.setBatteryWarrantyConversionBottomTarget(warningConfig.getBatteryConversionRate());
                            // 电池渗透率
                            result.setBatteryWarrantyPenetrationBottomTarget(warningConfig.getBatteryPenetrationRate());
                            // 延保转化率
                            result.setVehicleWarrantyConversionBottomTarget(warningConfig.getEwConRate());
                            // 延保渗透率
                            result.setVehicleWarrantyPenetrationBottomTarget(warningConfig.getEwPenetrationRate());
                            // 延保安心包转化率
                            result.setSafetyPackageConversionBottomTarget(warningConfig.getEwAxbConRate());
                            // 安心包渗透率
                            result.setSafetyPackagePenetrationBottomTarget(warningConfig.getEwAxbPenetrationRate());
                            // 延保轮胎转化率
                            result.setTireWarrantyConversionBottomTarget(warningConfig.getEwLtConRate());
                            // 轮胎渗透率
                            result.setTireWarrantyPenetrationBottomTarget(warningConfig.getEwLtPenetrationRate());
                        });

                return RopResponse.success(result);
            }
            return RopResponse.error(response.getMessage());
        } catch (Exception e) {
            log.error("接口异常", e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-门店分析-驻店员工分析")
    @ServiceMethod(method = "dj.api.strategy.merchant.analysis.employee.summary", needInSession = NeedInSessionType.YES)
    public RopResponse<EmployeeDetailSummaryResponse> storeEmployeeSummary(SceneMerchantBaseRequest request) {
        try {
            SceneBaseReq req = CommonUtil.convertRequest(SceneBaseReq.class);
            req.setExts("staffIds");
            RpcResponse<EmployeeDetailSummaryResponse> response = businessSceneAnalysisRemote.storeEmployeeSummary(req);
            if (response.isSuccess()) {
                return RopResponse.success(response.getResult());
            }
            return RopResponse.error(response.getMessage());
        } catch (Exception e) {
            log.error("接口异常", e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-预警指标树")
    @ServiceMethod(method = "dj.api.strategy.monitor.findMonitorTypeDictList", needInSession = NeedInSessionType.YES)
    public RopResponse<List<MonitorTypeDict>> findMonitorTypeDictList(MonitorDictRopRequest request) {
        try {
            RpcResponse<List<MonitorTypeDict>> response = monitoringRemote.findMonitorTypeDictList(request.getBusinessType());
            if (response.isSuccess()) {
                return RopResponse.success(response.getResult());
            }
            return RopResponse.error(response.getMessage());
        } catch (Exception e) {
            log.error("接口异常", e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-查询预警信息")
    @ServiceMethod(method = "dj.api.strategy.monitor.findMonitorListPage", needInSession = NeedInSessionType.YES)
    public RopResponse<List<StoreItemResponse>> findMonitorListPage(MonitorFilterRopRequest request) {
        try {
            MonitorFilterRequest req = CommonUtil.convertRequest(MonitorFilterRequest.class);
            RpcResponse<List<StoreItemResponse>> response = monitoringRemote.findMonitorListPage(req);


            if (response.isSuccess()) {
                List<StoreItemResponse> result = response.getResult();
                if (CollectionUtils.isNotEmpty( result)){
                    List<Integer> collect = result.stream().map(StoreItemResponse::getMerchantNo).map(Integer::valueOf)
                        .collect(Collectors.toList());
                    List<MerchantDetailResponse> responses = strategyDetailService.findMerchantDetail(
                        collect, request.getBusinessType()+ "");
                    for (StoreItemResponse itemResponse : result) {
                        MerchantDetailResponse merchantDetailResponse = responses.stream().filter(detailResponse -> (detailResponse.getMerchantNo()+"").equals(itemResponse.getMerchantNo())).findFirst().orElse(null);
                        if (merchantDetailResponse != null) {
                            itemResponse.setMainBrands(
                                merchantDetailResponse.getCarBrandResponses().stream()
                                    // 1. 过滤掉 null 的 CarBrandDTO
                                    .filter(Objects::nonNull)
                                    // 2. 过滤掉 id 为 null 的(避免 toMap 报错)
                                    .filter(carBrand -> carBrand.getId() != null)
                                    .collect(Collectors.toMap(
                                        CarBrandDTO::getId,         // 按 id 去重(唯一标识)
                                        Function.identity(),
                                        (existing, replacement) -> existing, // 保留第一个
                                        LinkedHashMap::new
                                    ))
                                    .values()
                                    .stream()
                                    .flatMap(parent ->
                                        (parent.getChildren() != null && !parent.getChildren().isEmpty())
                                            ? parent.getChildren().stream()
                                            .map(child -> parent.getLabel() + "-" + child.getLabel())
                                            : Stream.of(parent.getLabel())
                                    )
                                    .collect(Collectors.joining("/"))
                            );
                            itemResponse.setOnlineOperators(merchantDetailResponse.getOnlineOperator().stream().map(
                                OperatorResponse::getUsername).collect(
                                Collectors.joining("/")));
                            itemResponse.setRegionalOperators(merchantDetailResponse.getAreaOperator().stream().map(
                                OperatorResponse::getUsername).collect(
                                Collectors.joining("/")));
                        }
                    }
                }

                return RopResponse.success(response.getResult());
            }
            return RopResponse.error(response.getMessage());
        } catch (Exception e) {
            log.error("接口异常", e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-门店分析-历史人员记录")
    @ServiceMethod(method = "dj.api.strategy.merchant.analysis.employee.history", needInSession = NeedInSessionType.YES)
    public RopResponse<List<StaffHistoryRecordDTO>> merchantAnalysisEmployeeHistory(MerchantStaffHistoryRecordRequest request) {
        try {
            RpcResponse<List<StaffHistoryRecordDTO>> response = strategyInfoRemote.listMerchantAnalysisEmployeeHistory(request.getMerchantId(), request.getBizs());
            if (response.isSuccess()) {
                return RopResponse.success(response.getResult());
            }
            return RopResponse.error(response.getMessage());
        } catch (RpcServiceException e) {
            log.error("=====dj.api.strategy.merchant.analysis.employee.history rpcServiceException:{}", e.getMessage());
            return RopResponse.error(e);
        } catch (Exception e) {
            log.error("=====dj.api.strategy.merchant.analysis.employee.history exception:{}", e.getMessage(), e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("策略中心-门店分析-历史兜底指标")
    @ServiceMethod(method = "dj.api.strategy.merchant.analysis.index.history", needInSession = NeedInSessionType.YES)
    public RopResponse<List<EarlyWarningThresholdConfigHistoryDTO>> merchantAnalysisIndexHistory(MerchantStaffHistoryRecordRequest request) {
        try {
            RpcResponse<List<EarlyWarningThresholdConfigHistoryDTO>> response = earlyWarningMsgRemote.listMerchantAnalysisIndexHistory(request.getMerchantId().toString());
            if (response.isSuccess()) {
                return RopResponse.success(response.getResult());
            }
            return RopResponse.error(response.getMessage());
        } catch (RpcServiceException e) {
            log.error("=====dj.api.strategy.merchant.analysis.index.history rpcServiceException:{}", e.getMessage());
            return RopResponse.error(e);
        } catch (Exception e) {
            log.error("=====dj.api.strategy.merchant.analysis.index.history exception:{}", e.getMessage(), e);
            return RopResponse.error(e.getMessage());
        }
    }

    @ApiOperation("延保/权益/轻改-查询门店是否鸿蒙")
    @ServiceMethod(method = "dj.api.strategy.business.analysis.store.special.brand", needInSession = NeedInSessionType.NO)
    public RopResponse<Boolean> isHarmonyStore(SceneMerchantBaseRequest request) {
        try {
            RpcAssert.assertNotNull(request.getMerchantIds(), DefaultErrorEnum.SERVICE_ERROR, "门店参数不能为空");
            List<MerchantBasicInfoListResponse> merchant = loginService.findMerchant(request.getMerchantIds(), null);
            if (CollectionUtils.isEmpty(merchant)) {
                log.warn("查询门店信息返回空");
                return RopResponse.success(false);
            }
            List<Integer> merchantIds = merchant.stream().map(p -> p.getMerchantId()).collect(Collectors.toList());
            List<String> brandIds = merchant.stream()
                    .map(p -> p.getMerchantBrandCars())
                    .filter(StringUtils::isNotBlank)
                    .flatMap(p -> Arrays.stream(p.split(";")))
                    .flatMap(p -> Arrays.stream(p.split(",")))
                    .collect(Collectors.toList());
            log.info("merchant.id: {}, brandIds: {}", merchantIds, brandIds);
            String harmonyBrandId = environment.getProperty("dj.pe.analysis.business.scene.harmony.brandId", String.class, "2978");
            return RopResponse.success(brandIds.contains(harmonyBrandId));
        } catch (Exception e) {
            log.error("接口异常", e);
            return RopResponse.error(e.getMessage());
        }
    }

}