StrategyDetailService.java 11.3 KB
package cn.com.glsx.dj.strategy.service;

import cn.com.glsx.dj.mindworkplate.dto.monitoring.MonitorBaseRequest;
import cn.com.glsx.dj.mindworkplate.enums.CommonErrorEnum;
import cn.com.glsx.dj.mindworkplate.model.warning.MonitoringMsgDTO;
import cn.com.glsx.dj.mindworkplate.remote.MonitoringRemote;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantListOperatorDTO;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantOperatorDetailDTO;
import cn.com.glsx.dj.peanalysis.enums.BusinessTypeEnum;
import cn.com.glsx.dj.peanalysis.remote.BiAnalyseBackgroundRemote;
import cn.com.glsx.dj.riskmanage.dto.MerchantServiceAndBrandDTO;
import cn.com.glsx.dj.riskmanage.remote.CommonRemote;
import cn.com.glsx.dj.smartcarlife.enums.SceneTypeEnum;
import cn.com.glsx.dj.strategy.dto.MerchantStrategyStatisticsReqDTO;
import cn.com.glsx.dj.strategy.dto.MerchantStrategyStatisticsRespDTO;
import cn.com.glsx.dj.strategy.dto.OperatorResponse;
import cn.com.glsx.dj.strategy.remote.StrategyDetailRemote;
import cn.com.glsx.dj.strategy.request.StrategyEffectAnalysisRequest;
import cn.com.glsx.dj.strategy.request.validation.StrategyEffectAnalysisValidation;
import cn.com.glsx.dj.strategy.response.MerchantDetailResponse;
import cn.com.glsx.dj.strategy.response.StrategyEffectAnalysisResponse;
import cn.com.glsx.dj.strategy.uitl.validation.BeanValidationUtils;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yangwei
 * @version 1.0
 * @since 2026/01/19 14:15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StrategyDetailService {

    private final CommonRemote commonRemote;
    private final MonitoringRemote monitoringRemote;
    private final StrategyDetailRemote strategyDetailRemote;
    private final BiAnalyseBackgroundRemote biAnalyseBackgroundRemote;



    /**
     * 根据4s店商户号查询商户详情
     * @author yangwei
     * @since 2026/1/19 14:19
     * @param merchantNos 商户号
     * @param businessType 业务类型
     * @return java.util.List<cn.com.glsx.dj.strategy.response.MerchantDetailResponse> 商户详情
     */
    public List<MerchantDetailResponse> findMerchantDetail(List<Integer> merchantNos, String businessType) {
        Optional.ofNullable(merchantNos).filter(CollUtil::isNotEmpty).orElseThrow(() -> new RpcServiceException(CommonErrorEnum.VALIDATION_ERROR, "商户号不能为空"));
        Optional.ofNullable(businessType).orElseThrow(() -> new RpcServiceException(CommonErrorEnum.VALIDATION_ERROR, "业务类型不能为空"));

        // 获取运营人员
        MerchantListOperatorDTO merchantListOperatorDTO = new MerchantListOperatorDTO()
                .setStoreNos(merchantNos.stream().filter(ObjectUtil::isNotNull).map(String::valueOf).collect(Collectors.toList()))
                .setBusinessType(businessType);
        RpcResponse<List<MerchantOperatorDetailDTO>> merchantListOperatorResp = biAnalyseBackgroundRemote.findMerchantListOperator(merchantListOperatorDTO);
        if (merchantListOperatorResp.isFailed()) {
            log.error("查询商户运营人员失败: {}", merchantListOperatorResp.getMessage());
            throw new RpcServiceException(merchantListOperatorResp.getError(), merchantListOperatorResp.getMessage());
        }
        Map<String, MerchantOperatorDetailDTO> merchantNoMapOperator = Optional.ofNullable(merchantListOperatorResp.getResult())
                .orElseGet(Lists::newArrayList)
                .stream()
                .collect(Collectors.toMap(MerchantOperatorDetailDTO::getStoreNo, Function.identity(), (existing, replacement) -> existing));

        // 获取主营品牌和服务商
        SceneTypeEnum sceneTypeEnum = Lists.newArrayList(BusinessTypeEnum.BUSINESS_TYPE_1.getCode(), BusinessTypeEnum.BUSINESS_TYPE_3.getCode()).contains(businessType)
                ? SceneTypeEnum.SCENE1_0 : SceneTypeEnum.SCENE1_1;
        RpcResponse<List<MerchantServiceAndBrandDTO>> merchantListServiceAndBrand = commonRemote.findMerchantListServiceAndBrand(
                merchantNos, ObjectUtil.toString(sceneTypeEnum.getValue()));
        if (merchantListServiceAndBrand.isFailed()) {
            log.error("查询商户主营品牌和服务商失败: {}", merchantListServiceAndBrand.getMessage());
            throw new RpcServiceException(merchantListServiceAndBrand.getError(), merchantListServiceAndBrand.getMessage());
        }
        Map<Integer, MerchantServiceAndBrandDTO> merchantNoMapServiceAndBrand = Optional.ofNullable(merchantListServiceAndBrand.getResult())
                .orElseGet(Lists::newArrayList)
                .stream()
                .collect(Collectors.toMap(MerchantServiceAndBrandDTO::getMerchantNo, Function.identity(), (existing, replacement) -> existing));

        // 组装详情返回
        return merchantNos.stream()
                .map(merchantNo -> {
                    MerchantOperatorDetailDTO merchantOperatorDetailDTO = Optional.ofNullable(merchantNoMapOperator.get(ObjectUtil.toString(merchantNo)))
                            .orElseGet(MerchantOperatorDetailDTO::new);
                    MerchantServiceAndBrandDTO merchantServiceAndBrandDTO = Optional.ofNullable(merchantNoMapServiceAndBrand.get(merchantNo))
                            .orElseGet(MerchantServiceAndBrandDTO::new);
                    return MerchantDetailResponse.builder()
                            .merchantNo(merchantNo)
                            .directSalesFlag(merchantServiceAndBrandDTO.getDirectSaleFlag())
                            .mainServiceMerchantNo(merchantServiceAndBrandDTO.getMainServiceMerchantNo())
                            .mainServiceMerchantName(merchantServiceAndBrandDTO.getMainServiceName())
                            .carBrandResponses(merchantServiceAndBrandDTO.getBrands())
                            .onlineOperator(BeanUtil.copyToList(merchantOperatorDetailDTO.getOnlineOperator(), OperatorResponse.class))
                            .areaOperator(BeanUtil.copyToList(merchantOperatorDetailDTO.getAreaOperator(), OperatorResponse.class))
                            .build();
                }).collect(Collectors.toList());
    }


    /**
     * 根据策略ID查询策略效果分析
     * @author yangwei
     * @since 2026/1/22 14:19
     * @param request 策略效果分析请求
     * @return java.util.List<cn.com.glsx.dj.strategy.response.StrategyEffectAnalysisResponse> 策略效果分析
     */
    public List<StrategyEffectAnalysisResponse> findStrategyEffectAnalysis(StrategyEffectAnalysisRequest request) {
        StrategyEffectAnalysisValidation validation = BeanUtil.copyProperties(request, StrategyEffectAnalysisValidation.class);
        BeanValidationUtils.validateAndThrow(validation);

        MonitorBaseRequest monitorBaseRequest = new MonitorBaseRequest()
                .setBusinessType(Integer.valueOf(request.getBusinessType()))
                .setMonitorType(request.getMonitorType())
                .setMetricTypeId(request.getMetricTypeId())
                .setPeriodType(request.getPeriodType())
                .setStartDate(DateUtil.format(request.getStartDate(), DatePattern.NORM_DATE_PATTERN))
                .setEndDate(DateUtil.format(request.getEndDate(), DatePattern.NORM_DATE_PATTERN));
        RpcResponse<List<MonitoringMsgDTO>> monitorListByCondition = monitoringRemote.getMonitorListByCondition(monitorBaseRequest);
        if (monitorListByCondition.isFailed()) {
            log.error("查询策略效果分析失败: {}", monitorListByCondition.getMessage());
            throw new RpcServiceException(monitorListByCondition.getError(), monitorListByCondition.getMessage());
        }
        List<MonitoringMsgDTO> monitoringMsgDTOList = Optional.ofNullable(monitorListByCondition.getResult()).orElseGet(Lists::newArrayList);
        if (CollUtil.isEmpty(monitoringMsgDTOList)) {
            return Lists.newArrayList();
        }

        // 获取商户详情
        Map<Integer, MerchantDetailResponse> merchantIdMapInfo = MapUtil.newHashMap();
        List<Integer> merchantIds = monitoringMsgDTOList.stream().map(MonitoringMsgDTO::getMerchantId4s).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(merchantIds)) {
            merchantIdMapInfo = Optional.ofNullable(findMerchantDetail(merchantIds, request.getBusinessType()))
                    .orElseGet(Lists::newArrayList)
                    .stream()
                    .collect(Collectors.toMap(MerchantDetailResponse::getMerchantNo, Function.identity(), (existing, replacement) -> existing));
        }

        // 获取策略数
        RpcResponse<List<MerchantStrategyStatisticsRespDTO>> strategyStatisticsGroupMerchantNo = strategyDetailRemote.findStrategyStatisticsGroupMerchantNo(
                MerchantStrategyStatisticsReqDTO
                        .builder()
                        .businessType(request.getBusinessType())
                        .startDate(request.getStartDate())
                        .endDate(request.getEndDate())
                        .merchantNos(merchantIds)
                        .build());
        if (strategyStatisticsGroupMerchantNo.isFailed()) {
            log.error("查询策略数失败: {}", strategyStatisticsGroupMerchantNo.getMessage());
            throw new RpcServiceException(strategyStatisticsGroupMerchantNo.getError(), strategyStatisticsGroupMerchantNo.getMessage());
        }
        Map<Integer, Integer> strategyCountMap = Optional.ofNullable(strategyStatisticsGroupMerchantNo.getResult())
                .orElseGet(Lists::newArrayList)
                .stream()
                .collect(Collectors.toMap(
                        MerchantStrategyStatisticsRespDTO::getMerchantNo,
                        MerchantStrategyStatisticsRespDTO::getStrategyCount,
                        (existing, replacement) -> existing
                ));

        Map<Integer, MerchantDetailResponse> finalMerchantIdMapInfo = merchantIdMapInfo;
        return monitoringMsgDTOList.stream().map(monitoringMsgDTO -> {
            StrategyEffectAnalysisResponse strategyEffectAnalysisResponse = BeanUtil.copyProperties(monitoringMsgDTO, StrategyEffectAnalysisResponse.class);

            // 运营人员主营品牌
            Optional.ofNullable(finalMerchantIdMapInfo.get(monitoringMsgDTO.getMerchantId4s()))
                    .ifPresent(detailResponse -> {
                        strategyEffectAnalysisResponse.setOnlineOperator(detailResponse.getOnlineOperator());
                        strategyEffectAnalysisResponse.setAreaOperator(detailResponse.getAreaOperator());
                        strategyEffectAnalysisResponse.setMainBrands(detailResponse.getCarBrandResponses());
                    });

            // 策略总数
            strategyEffectAnalysisResponse.setStrategyTotalCount(Optional.ofNullable(strategyCountMap.get(monitoringMsgDTO.getMerchantId4s())).orElse(0));
            return strategyEffectAnalysisResponse;
        }).collect(Collectors.toList());
    }
}