StaffOutputValueService.java 20.3 KB
package cn.com.glsx.busassistant.service;

import cn.com.glsx.busassistant.converter.SellerServeMerchantStatDTOConvert;
import cn.com.glsx.busassistant.converter.StaffOutputValueStatDTOConvert;
import cn.com.glsx.busassistant.converter.StaffPerformanceDTOConvert;
import cn.com.glsx.busassistant.converter.TechnicianServeMerchantStatDTOConvert;
import cn.com.glsx.busassistant.enums.StaffMerchantStatTypeEnum;
import cn.com.glsx.busassistant.request.outputValue.ListStaffOutputValuesRequest;
import cn.com.glsx.busassistant.request.outputValue.ListStaffRequest;
import cn.com.glsx.busassistant.response.outputValue.*;
import cn.com.glsx.dj.smartcarlife.dto.MerchantSubRefDTO;
import cn.com.glsx.dj.smartcarlife.dto.staffStat.SellerServeMerchantStatDTO;
import cn.com.glsx.dj.smartcarlife.dto.staffStat.StaffOutputValueStatDTO;
import cn.com.glsx.dj.smartcarlife.dto.staffStat.StaffPerformanceDTO;
import cn.com.glsx.dj.smartcarlife.dto.staffStat.TechnicianServeMerchantStatDTO;
import cn.com.glsx.dj.smartcarlife.enums.EmployeePerformanceEnum;
import cn.com.glsx.dj.smartcarlife.remote.MerchantSubRefRemote;
import cn.com.glsx.dj.smartcarlife.remote.StaffStatRemote;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.com.glsx.framework.rop.response.RopResponse;
import cn.com.glsx.merchants.enums.StaffBusinessTypeEnum;
import cn.com.glsx.merchants.model.response.MerchantStaffResponse;
import cn.com.glsx.scrm.system.model.wechatapplets.LoginUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.oreframework.boot.autoconfigure.rop.util.RopThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StaffOutputValueService {
    @Autowired
    private MerchantServiceCenterService merchantServiceCenterService;

    @Autowired
    private MerchantStaffService merchantStaffService;

    @Autowired
    private Environment env;

    @Autowired
    private StaffStatRemote staffStatRemote;
    
    @Autowired
    private MerchantSubRefRemote merchantSubRefRemote;

    private List<Byte> UPGRADEGOODS_TYPE_LIST;

    @PostConstruct
    public void init(){
        UPGRADEGOODS_TYPE_LIST = Arrays.stream(env.getProperty("outputvalue.sceneOne.goodsType", "1").split(","))
                .map(Byte::parseByte).collect(Collectors.toList());;
    }
    
    public RopResponse<RpcPagination<ListStaffOutputValuesItemResponse>> listStaffOutputValues(ListStaffOutputValuesRequest request){
        LoginUserInfoResponse loginUser = RopThreadLocal.getLoginUser(LoginUserInfoResponse.class);
        List<Integer> partnerMerchantIds;
        if (!loginUser.getIsSuper()) {
            partnerMerchantIds = new ArrayList<>();
            partnerMerchantIds.add(loginUser.getMerchantId());
        }else{
            partnerMerchantIds = request.getPartnerMerchantIds();
        }
        partnerMerchantIds = getContainSubMerchantIds(partnerMerchantIds);
        log.debug("当前服务商及数字化服务商,partnerMerchantIds:{}", partnerMerchantIds);
        List<Integer> yqMerchantIds = merchantServiceCenterService.listYqMerchantIdsByPartnerMerchantIds(partnerMerchantIds);
        if (CollectionUtils.isEmpty(yqMerchantIds)) {
            log.info("当前服务商及数字化服务商-关联园区店为空,partnerMerchantIds:{}", partnerMerchantIds);
            return RopResponse.success(new RpcPagination<>());
        }
        List<MerchantStaffResponse> merchantStaffs = merchantStaffService.listMerchantStaffsByMerchantIds(yqMerchantIds);
        if (CollectionUtils.isEmpty(merchantStaffs)) {
            log.info("园区店下无员工,yqMerchantIds:{}", yqMerchantIds);
            return RopResponse.success(new RpcPagination<>());
        }
        return listStaffOutputValues(request, merchantStaffs, yqMerchantIds);
    }


    public List<MerchantStaffResponse> listStaff(ListStaffRequest request){
        LoginUserInfoResponse loginUser = RopThreadLocal.getLoginUser(LoginUserInfoResponse.class);
        List<Integer> partnerMerchantIds;
        if (!loginUser.getIsSuper()) {
            partnerMerchantIds = new ArrayList<>();
            partnerMerchantIds.add(loginUser.getMerchantId());
        }else{
            partnerMerchantIds = request.getPartnerMerchantIds();
        }
        partnerMerchantIds = getContainSubMerchantIds(partnerMerchantIds);
        log.debug("当前服务商及数字化服务商,partnerMerchantIds:{}", partnerMerchantIds);
        List<Integer> yqMerchantIds = merchantServiceCenterService.listYqMerchantIdsByPartnerMerchantIds(partnerMerchantIds);
        if (CollectionUtils.isEmpty(yqMerchantIds)) {
            log.info("当前服务商及数字化服务商-关联园区店为空,partnerMerchantIds:{}", partnerMerchantIds);
            return null;
        }
        return merchantStaffService.listMerchantStaffsByMerchantIds(yqMerchantIds);
    }

    private List<Integer> getContainSubMerchantIds(List<Integer> partnerMerchantIds) {
        if (CollectionUtils.isNotEmpty(partnerMerchantIds)) {
            MerchantSubRefDTO condition = MerchantSubRefDTO.builder().merchantIds(partnerMerchantIds).build();
            RpcResponse<List<MerchantSubRefDTO>> res = merchantSubRefRemote.list(condition);
            if(res.hasResult()){
                res.getResult().stream().map(MerchantSubRefDTO::getSubMerchantId).forEach(partnerMerchantIds::add);
            }else{
                log.error("查询服务商下架关系失败,res:{}", res);
            }
        }
        return partnerMerchantIds;
    }

    public RopResponse<RpcPagination<ListStaffOutputValuesItemResponse>> listStaffOutputValues(ListStaffOutputValuesRequest request, List<MerchantStaffResponse> merchantStaffs, List<Integer> yqMerchantIds){
        Map<String, MerchantStaffResponse> outputValueStaffsMap = new HashMap<>();
        Map<String, MerchantStaffResponse> constructionStaffsMap = new HashMap<>();
        initStaffsMap(request, merchantStaffs, outputValueStaffsMap, constructionStaffsMap);
        RpcPagination<ListStaffOutputValuesItemResponse> staffOutputValuesPage = pageStaffOutputValue(outputValueStaffsMap,
                constructionStaffsMap, yqMerchantIds, request);
        if(staffOutputValuesPage != null){
            compileStaffMerchantStatDetail(request, staffOutputValuesPage.getList(), outputValueStaffsMap, constructionStaffsMap);
            return RopResponse.success(staffOutputValuesPage);
        }
        return RopResponse.error("获取员工产值统计失败");

    }

    private void compileStaffMerchantStatDetail(ListStaffOutputValuesRequest request, List<ListStaffOutputValuesItemResponse> list, Map<String, MerchantStaffResponse> outputValueStaffsMap, Map<String, MerchantStaffResponse> constructionStaffsMap) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (ListStaffOutputValuesItemResponse staffOutputValueItemResp : list) {
                MerchantStaffResponse outputValueStaff = outputValueStaffsMap.get(staffOutputValueItemResp.getStaffUUID());
                if (outputValueStaff != null) {
                    compileOutputValueStaffMerchantStatDetail(staffOutputValueItemResp, request, outputValueStaff);
                }else{
                    MerchantStaffResponse constructionStaff = constructionStaffsMap.get(staffOutputValueItemResp.getStaffUUID());
                    compileConstructionStaffMerchantStatDetail(staffOutputValueItemResp, request, constructionStaff);
                }
            }
            compileStaffPerformanceDetail(list);
        }
    }


    private void compileStaffPerformanceDetail(List<ListStaffOutputValuesItemResponse> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (ListStaffOutputValuesItemResponse staffOutputValuesItem : list) {
                Byte staffType = null;
                if (Objects.equals(StaffMerchantStatTypeEnum.OUTPUT_VALUE.getValue(), staffOutputValuesItem.getOutputValueType())) {
                    staffType = EmployeePerformanceEnum.StaffType.RESIDENT.getValue();
                }else if (Objects.equals(StaffMerchantStatTypeEnum.CONSTRUCTION.getValue(), staffOutputValuesItem.getOutputValueType())) {
                    staffType = EmployeePerformanceEnum.StaffType.TECHNICIAN.getValue();
                }
                String performanceMonthStart = env.getProperty("staff.performanceMonth.start", "2023-09");
                if (!performanceMonthStart.matches("^\\d{4}(-)(0[1-9]|1[0-2])$")) {
                    log.warn("staff.performanceMonth.start配置错误, performanceMonthStart:{}", performanceMonthStart);
                    performanceMonthStart = "2023-09";
                }
                StaffPerformanceDTO condition = StaffPerformanceDTO.builder().staffUUID(staffOutputValuesItem.getStaffUUID()).staffType(staffType).performanceMonthStart(performanceMonthStart).build();
                RpcResponse<StaffPerformanceDTO> res = staffStatRemote.getStaffPerformance(condition);
                if(res.hasResult()){
                    StaffPerformanceResponse staffPerformanceResponse = StaffPerformanceDTOConvert.INSTANCE.toStaffPerformanceResponse(res.getResult());
                    compileStaffPerformanceResult(staffPerformanceResponse, performanceMonthStart);
                    staffOutputValuesItem.setPerformance(staffPerformanceResponse);
                }else{
                    log.error("获取员工绩效配置及结果失败, condition:{},res:{}", condition, res);
                }
            }
        }
    }

    private void compileStaffPerformanceResult(StaffPerformanceResponse staffPerformanceResponse, String performanceMonthStart) {
        if (staffPerformanceResponse != null) {
            Map<String, StaffPerformanceResultResponse> performanceResultMap;
            if (CollectionUtils.isNotEmpty(staffPerformanceResponse.getPerformanceResults())) {
                performanceResultMap = staffPerformanceResponse.getPerformanceResults().stream().collect(Collectors.toMap(StaffPerformanceResultResponse::getPerformanceMonth, o -> o, (o1, o2) -> o2));
            }else{
                performanceResultMap = new HashMap<>();
            }
            LocalDate lastPerformanceMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
            // 从performanceMonthStart开始,到当前月份,每个月都要有绩效结果(内有计算结果则结果值为null)
            LocalDate performanceMonth = LocalDate.parse(performanceMonthStart + "-01");
            List<StaffPerformanceResultResponse> list = new ArrayList<>();
            while (lastPerformanceMonth.isAfter(performanceMonth)
                    || lastPerformanceMonth.isEqual(performanceMonth)) {
                String lastPerformanceMonthStr = lastPerformanceMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                StaffPerformanceResultResponse performanceResult = performanceResultMap.get(lastPerformanceMonthStr);
                if (performanceResult == null) {
                    performanceResult = new StaffPerformanceResultResponse();
                    performanceResult.setPerformanceMonth(lastPerformanceMonthStr);
                }
                list.add(performanceResult);
                lastPerformanceMonth = lastPerformanceMonth.minusMonths(1);
            }
            staffPerformanceResponse.setPerformanceResults(list);
        }
    }


    private void compileConstructionStaffMerchantStatDetail(ListStaffOutputValuesItemResponse staffOutputValueItemResp, ListStaffOutputValuesRequest request, MerchantStaffResponse constructionStaff) {
        RpcAssert.assertNotNull(constructionStaff, DefaultErrorEnum.DATA_NULL,"constructionStaff not be null");
        TechnicianServeMerchantStatDTO technicianServeMerchantStatDTO = TechnicianServeMerchantStatDTO.builder()
                .technicianStaffUUID(constructionStaff.getUuid()).shopMerchantIds(request.getShopMerchantIds())
                .startTime(request.getStartTime()).endTime(request.getEndTime()).upgradeGoodsTypes(UPGRADEGOODS_TYPE_LIST).build();
        RpcPagination<TechnicianServeMerchantStatDTO> pagination = new RpcPagination<>();
        pagination.setPages(request.getMerchantOutputValuesPageSize());
        pagination.setCondition(technicianServeMerchantStatDTO);
        RpcPagination<TechnicianServeMerchantStatDTO> technicianServeMerchantStatPage = pageTechnicianServeMerchantStat(pagination);
        if (technicianServeMerchantStatPage != null) {
            List<StaffConstructionStatItemResponse> constructionStats = technicianServeMerchantStatPage.getList().stream()
                    .map(TechnicianServeMerchantStatDTOConvert.INSTANCE::toStaffConstructionStatItemResponse).collect(Collectors.toList());
            staffOutputValueItemResp.setConstructionStats(constructionStats);
        }
        staffOutputValueItemResp.setStaffName(constructionStaff.getStaffName());
        staffOutputValueItemResp.setStaffRoleName(constructionStaff.getRoleName());
        staffOutputValueItemResp.setStaffBusinessType(constructionStaff.getStaffBusinessType());
        staffOutputValueItemResp.setYqMerchantId(constructionStaff.getMerchantNo());
        staffOutputValueItemResp.setYqMerchantName(constructionStaff.getMerchantName());
        staffOutputValueItemResp.setOutputValueType(StaffMerchantStatTypeEnum.CONSTRUCTION.getValue());
    }


    public RpcPagination<TechnicianServeMerchantStatDTO> pageTechnicianServeMerchantStat(RpcPagination<TechnicianServeMerchantStatDTO> pagination){
        RpcResponse<RpcPagination<TechnicianServeMerchantStatDTO>> res = staffStatRemote.pageTechnicianServeMerchantStat(pagination);
        if(res.hasResult()){
            return res.getResult();
        }else{
            log.error("分页获取技师的4s店订单台次统计失败,res:{}", res);
        }
        return null;
    }

    private void compileOutputValueStaffMerchantStatDetail(ListStaffOutputValuesItemResponse staffOutputValueItemResp, ListStaffOutputValuesRequest request, MerchantStaffResponse outputValueStaff) {
        RpcAssert.assertNotNull(outputValueStaff, DefaultErrorEnum.DATA_NULL,"constructionStaff not be null");
        SellerServeMerchantStatDTO sellerServeMerchantStatDTO = SellerServeMerchantStatDTO.builder()
                .sellerStaffUUID(outputValueStaff.getUuid()).shopMerchantIds(request.getShopMerchantIds())
                .startTime(request.getStartTime()).endTime(request.getEndTime()).upgradeGoodsTypes(UPGRADEGOODS_TYPE_LIST).build();
        RpcPagination<SellerServeMerchantStatDTO> pagination = new RpcPagination<>();
        pagination.setPageSize(request.getMerchantOutputValuesPageSize());
        pagination.setCondition(sellerServeMerchantStatDTO);
        RpcPagination<SellerServeMerchantStatDTO> sellerServeMerchantStatPage = pageSellerServeMerchantStat(pagination);
        if (sellerServeMerchantStatPage != null) {
            List<StaffOutputValueStatItemResponse> sellerStats = sellerServeMerchantStatPage.getList().stream()
                    .map(SellerServeMerchantStatDTOConvert.INSTANCE::toStaffOutputValueStatItemResponse).collect(Collectors.toList());
            staffOutputValueItemResp.setOutputValueStats(sellerStats);
        }
        staffOutputValueItemResp.setStaffName(outputValueStaff.getStaffName());
        staffOutputValueItemResp.setStaffRoleName(outputValueStaff.getRoleName());
        staffOutputValueItemResp.setStaffBusinessType(outputValueStaff.getStaffBusinessType());
        staffOutputValueItemResp.setYqMerchantId(outputValueStaff.getMerchantNo());
        staffOutputValueItemResp.setYqMerchantName(outputValueStaff.getMerchantName());
        staffOutputValueItemResp.setOutputValueType(StaffMerchantStatTypeEnum.OUTPUT_VALUE.getValue());
    }


    public RpcPagination<SellerServeMerchantStatDTO> pageSellerServeMerchantStat(RpcPagination<SellerServeMerchantStatDTO> pagination){
        RpcResponse<RpcPagination<SellerServeMerchantStatDTO>> res = staffStatRemote.pageSellerServeMerchantStat(pagination);
        if(res.hasResult()){
            return res.getResult();
        }else{
            log.error("分页获取驻店人员的4s店产值统计失败,res:{}", res);
        }
        return null;
    }


    private RpcPagination<ListStaffOutputValuesItemResponse> pageStaffOutputValue(Map<String, MerchantStaffResponse> outputValueStaffsMap,
                                                                                 Map<String, MerchantStaffResponse> constructionStaffsMap,
                                                                                 List<Integer> yqMerchantIds, ListStaffOutputValuesRequest request){
        StaffOutputValueStatDTO staffOutputValueStatDTO = StaffOutputValueStatDTO.builder()
                .sellerStaffUUIDs(new ArrayList<>(outputValueStaffsMap.keySet()))
                .technicianStaffUUIDs(new ArrayList<>(constructionStaffsMap.keySet()))
                .yqMerchantIds(yqMerchantIds).startTime(request.getStartTime()).endTime(request.getEndTime())
                .shopMerchantIds(request.getShopMerchantIds()).upgradeGoodsTypes(UPGRADEGOODS_TYPE_LIST).build();
        if (CollectionUtils.isEmpty(staffOutputValueStatDTO.getSellerStaffUUIDs())) {
            staffOutputValueStatDTO.setSellerStaffUUIDs(Arrays.asList("-1"));
        }
        if (CollectionUtils.isEmpty(staffOutputValueStatDTO.getTechnicianStaffUUIDs())) {
            staffOutputValueStatDTO.setTechnicianStaffUUIDs(Arrays.asList("-1"));
        }
        RpcPagination<StaffOutputValueStatDTO> pagination = new RpcPagination<>();
        pagination.setPageNum(request.getPageNum());
        pagination.setPageSize(request.getPageSize());
        pagination.setCondition(staffOutputValueStatDTO);
        RpcResponse<RpcPagination<StaffOutputValueStatDTO>> res = staffStatRemote.pageStaffOutputValue(pagination);
        if(res.hasResult()){
            pagination = res.getResult();
            RpcPagination<ListStaffOutputValuesItemResponse> resp = new RpcPagination<>();
            resp.setPageSize(pagination.getPageSize());
            resp.setPageNum(pagination.getPageNum());
            resp.setTotal(pagination.getTotal());
            resp.setPages(pagination.getPages());
            resp.setStartRow(pagination.getStartRow());
            resp.setEndRow(pagination.getEndRow());
            resp.setList(new ArrayList<>());
            if (CollectionUtils.isNotEmpty(pagination.getList())) {
                resp.setList(pagination.getList().parallelStream().map(StaffOutputValueStatDTOConvert.INSTANCE::toListStaffOutputValuesItemResponse)
                        .collect(Collectors.toList()));
            }
            return resp;
        }else{
            log.error("分页获取员工产值统计失败,msg:{}", res.getMessage());
        }
        return null;
    }

    private void initStaffsMap(ListStaffOutputValuesRequest request, List<MerchantStaffResponse> merchantStaffs, Map<String, MerchantStaffResponse> outputValueStaffsMap, Map<String, MerchantStaffResponse> constructionStaffsMap) {
        boolean specificStaff = CollectionUtils.isNotEmpty(request.getStaffUUIDs());
        List<MerchantStaffResponse> outputValueStaffs = new ArrayList<>();
        List<MerchantStaffResponse> constructionStaffs = new ArrayList<>();
        for (MerchantStaffResponse staff : merchantStaffs) {
            if (!specificStaff || request.getStaffUUIDs().contains(staff.getUuid())) {
                if (isTechnician(staff)) {
                    constructionStaffs.add(staff);
                } else {
                    outputValueStaffs.add(staff);
                }
            }
        }
        outputValueStaffsMap.putAll(
                outputValueStaffs.stream().collect(Collectors.toMap(MerchantStaffResponse::getUuid, o -> o, (o1, o2) -> o2))
        );
        constructionStaffsMap.putAll(
                constructionStaffs.stream().collect(Collectors.toMap(MerchantStaffResponse::getUuid, o -> o, (o1, o2) -> o2))
        );
    }


    public Boolean isTechnician(MerchantStaffResponse staff){
        return Objects.equals(StaffBusinessTypeEnum.TECHNICIAN.getCode(), staff.getStaffBusinessType());
    }

}