JudgmentService.java 19.3 KB
package cn.com.glsx.admin.modules.service;

import cn.com.glsx.admin.common.enums.TypeConverseEnum;
import cn.com.glsx.admin.modules.mapper.VehicleMapper;
import cn.com.glsx.admin.modules.model.export.JudgmentExport;
import cn.com.glsx.admin.modules.model.param.JudgmentSearch;
import cn.com.glsx.admin.modules.model.vo.AlarmVehicleVO;
import cn.com.glsx.admin.modules.remote.RemoteStuJudgeAlarmService;
import cn.com.glsx.alarm.services.model.DeviceAlarmCountDto;
import cn.com.glsx.alarm.services.model.StuJudgeAlarmDto;
import cn.com.glsx.usercenter.api.dto.response.Organization;
import cn.com.glsx.usercenter.api.feign.OrganizationService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 大数据研判 service
 *
 * @author yll
 */
@Slf4j
@Service
public class JudgmentService extends AbstractCommonService {

    @Autowired
    private RemoteStuJudgeAlarmService remoteStuJudgeAlarmService;

    @Autowired
    private VehicleMapper vehicleMapper;

    @Autowired
    private OrganizationService organizationService;

    /**
     * 查询大数据研判数据列表
     *
     * @param search
     * 
     * @return
     */
    public PageInfo findJudgmentList(JudgmentSearch search) {
        long allStart = System.currentTimeMillis();
        injectOrgChecked(search);

        List<JudgmentExport> judgmentList = vehicleMapper.findJudgmentList(search);
        if (CollectionUtil.isEmpty(judgmentList)) {
            log.info("judgment.search early-return: baseListEmpty=true, costMs={}", (System.currentTimeMillis() - allStart));
            return new PageInfo<>();
        }
        log.info("judgment.search baseListSize={}", judgmentList.size());
        List<String> snList = judgmentList.stream().map(JudgmentExport::getSn).collect(Collectors.toList());
        long remoteStart = System.currentTimeMillis();
        PageInfo stuJudgeAlarmListByPage;
        try {
            stuJudgeAlarmListByPage = remoteStuJudgeAlarmService.searchStuJudgeAlarmListByPage(snList, search);
        } catch (RuntimeException ex) {
            log.error("judgment.search remote-call-failed: snSize={}, costMs={}, error={}",
                    snList != null ? snList.size() : 0, (System.currentTimeMillis() - remoteStart), ex.toString());
            throw ex;
        }
        log.info("judgment.search remote-call-ok: snSize={}, remoteCount={}, costMs={}",
                snList != null ? snList.size() : 0,
                stuJudgeAlarmListByPage != null && stuJudgeAlarmListByPage.getList() != null ? stuJudgeAlarmListByPage.getList().size() : 0,
                (System.currentTimeMillis() - remoteStart));
        List<StuJudgeAlarmDto> stuJudgeAlarmList = JSON.parseArray(JSON.toJSONString(stuJudgeAlarmListByPage.getList()), StuJudgeAlarmDto.class);
        if (CollectionUtil.isEmpty(stuJudgeAlarmList)) {
            log.info("judgment.search early-return: remoteListEmpty=true, costMs={}", (System.currentTimeMillis() - allStart));
            return new PageInfo<>();
        }

        Map<String, JudgmentExport> judgmentExportMap = judgmentList.stream().filter(judExport -> StringUtils.isNotBlank(judExport.getSn())).collect(Collectors.toMap(JudgmentExport::getSn, Function.identity(), (v1, v2) -> v1));
        List<JudgmentExport> judgmentExportList = Lists.newArrayList();
        stuJudgeAlarmList.forEach(stuJudgeAlarm -> {
            if (StringUtils.isBlank(stuJudgeAlarm.getSn())) {
                return;
            }
            JudgmentExport judgmentExportTemp = judgmentExportMap.get(stuJudgeAlarm.getSn());
            if (judgmentExportTemp != null) {
                JudgmentExport judgmentExport = new JudgmentExport();
                BeanUtils.copyProperties(judgmentExportTemp, judgmentExport);
                judgmentExport.setSourceStr(TypeConverseEnum.SourceEnum.getStrBySourceType(judgmentExport.getSource()));
                judgmentExport.setAlarmType(stuJudgeAlarm.getAlarmType());
                judgmentExport.setAlarmTypeStr(TypeConverseEnum.AlarmTypeEnum.getStrByAlarmType(stuJudgeAlarm.getAlarmType()));
                judgmentExport.setAlarmStatus(stuJudgeAlarm.getAlarmStatus());
                judgmentExport.setAlarmStatusStr(TypeConverseEnum.AlarmStatusEnum.getStrByAlarmStatus(stuJudgeAlarm.getAlarmStatus()));
                judgmentExport.setGeoCode(stuJudgeAlarm.getGeoCode());
                judgmentExport.setAlarmAddress(stuJudgeAlarm.getAlarmAddress());
                judgmentExport.setAlarmBeginTime(stuJudgeAlarm.getAlarmBeginTime());
                judgmentExport.setAlarmEndTime(stuJudgeAlarm.getAlarmEndTime());
                if (TypeConverseEnum.AlarmStatusEnum.TAKE_EFFECT.getAlarmStatus().equals(stuJudgeAlarm.getAlarmStatus())) {
                    // 如果警情为生效警情 则将失效时间设备为 --
                    judgmentExport.setAlarmEndTime("--");
                }
                
                // 计算报警持续时间(驶出-进入):显示规则 <1天按小时;≥1天按X天Y小时;任一时间为"--"时显示"--"
                if ("--".equals(judgmentExport.getAlarmBeginTime()) || "--".equals(judgmentExport.getAlarmEndTime())) {
                    judgmentExport.setAlarmDuration("--");
                } else {
                    try {
                        java.util.Date begin = DateUtil.parse(judgmentExport.getAlarmBeginTime());
                        java.util.Date end = DateUtil.parse(judgmentExport.getAlarmEndTime());
                        long diffMs = end.getTime() - begin.getTime();
                        if (diffMs <= 0) {
                            judgmentExport.setAlarmDuration("0小时");
                        } else {
                            long hours = diffMs / (1000 * 60 * 60);
                            if (hours < 24) {
                                judgmentExport.setAlarmDuration(hours + "小时");
                            } else {
                                long days = hours / 24;
                                long remainHours = hours % 24;
                                judgmentExport.setAlarmDuration(days + "天" + remainHours + "小时");
                            }
                        }
                    } catch (Exception e) {
                        judgmentExport.setAlarmDuration("--");
                    }
                }
                
                judgmentExport.setAlarmLng(stuJudgeAlarm.getAlarmLng());
                judgmentExport.setAlarmLat(stuJudgeAlarm.getAlarmLat());
                judgmentExport.setAlarmAddress(stuJudgeAlarm.getAlarmAddress());
                judgmentExport.setAlarmCount(stuJudgeAlarm.getAlarmCount());
                judgmentExport.setAlarmLevel(stuJudgeAlarm.getAlarmLevel());
                judgmentExportList.add(judgmentExport);
            }
        });
        stuJudgeAlarmListByPage.setList(judgmentExportList);
        if (log.isDebugEnabled() && CollectionUtil.isNotEmpty(judgmentExportList)) {
            JudgmentExport s = judgmentExportList.get(0);
            log.debug("judgment.search sample: sn={}, vin={}, alarmType={}, alarmStatus={}",
                    s.getSn(), s.getVin(), s.getAlarmType(), s.getAlarmStatus());
        }
        log.info("judgment.search assembledCount={}, totalCostMs={}",
                judgmentExportList.size(), (System.currentTimeMillis() - allStart));
        return stuJudgeAlarmListByPage;
    }

    /**
     * 查询警情车辆列表(按车辆ID分组汇总警情次数)
     *
     * @param search 查询参数
     * @return 警情车辆分页列表
     */
    public PageInfo<AlarmVehicleVO> findAlarmVehicleList(JudgmentSearch search) {
        long allStart = System.currentTimeMillis();
        injectOrgChecked(search);

        // 1. 获取权限下的全量车辆设备列表
        List<JudgmentExport> judgmentList = vehicleMapper.findJudgmentList(search);
        if (CollectionUtil.isEmpty(judgmentList)) {
            log.info("judgment.alarmVehicle early-return: baseListEmpty=true, costMs={}", (System.currentTimeMillis() - allStart));
            return new PageInfo<>();
        }
        log.info("judgment.alarmVehicle baseListSize={}", judgmentList.size());

        // 2. 提取所有SN并构建 vehicleId→SNs 映射
        List<String> allSnList = judgmentList.stream()
                .map(JudgmentExport::getSn)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, List<String>> vehicleSnMap = new HashMap<>();
        for (JudgmentExport je : judgmentList) {
            if (je.getVehicleId() != null && StringUtils.isNotBlank(je.getSn())) {
                vehicleSnMap.computeIfAbsent(je.getVehicleId(), k -> new ArrayList<>()).add(je.getSn());
            }
        }

        // 3. 批量查询有警情的设备号及警情次数
        long remoteStart = System.currentTimeMillis();
        List<DeviceAlarmCountDto> alarmCountList;
        try {
            alarmCountList = remoteStuJudgeAlarmService.batchQueryDeviceAlarmCount(allSnList);
        } catch (RuntimeException ex) {
            log.error("judgment.alarmVehicle remote-call-failed: snSize={}, costMs={}, error={}",
                    allSnList.size(), (System.currentTimeMillis() - remoteStart), ex.toString());
            throw ex;
        }
        log.info("judgment.alarmVehicle remote-call-ok: snSize={}, alarmedCount={}, costMs={}",
                allSnList.size(),
                alarmCountList != null ? alarmCountList.size() : 0,
                (System.currentTimeMillis() - remoteStart));

        if (CollectionUtil.isEmpty(alarmCountList)) {
            log.info("judgment.alarmVehicle early-return: noAlarmedDevices, costMs={}", (System.currentTimeMillis() - allStart));
            return new PageInfo<>();
        }

        // 4. 构建 SN→alarmCount 映射
        Map<String, Integer> snAlarmCountMap = alarmCountList.stream()
                .filter(d -> StringUtils.isNotBlank(d.getSn()))
                .collect(Collectors.toMap(
                        DeviceAlarmCountDto::getSn,
                        d -> d.getAlarmCount() != null ? d.getAlarmCount() : 0,
                        (v1, v2) -> v1));

        List<String> alarmedSnList = new ArrayList<>(snAlarmCountMap.keySet());

        List<AlarmVehicleVO> alarmVehicleList = null;

        // 5. 分页查询有警情的车辆列表(按车辆ID分组)
        /*PageHelper.startPage(search.getPageNumber(), search.getPageSize());
        List<AlarmVehicleVO> alarmVehicleList = vehicleMapper.findAlarmVehicleList(alarmedSnList, search);

        // 5.1 批量查询用户组织信息,赋值给 creator 字段
        Set<Long> userIds = alarmVehicleList.stream()
                .filter(vo -> vo.getCreatedBy() != null)
                .map(vo -> vo.getCreatedBy().longValue())
                .collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(userIds)) {
            R<List<Organization>> orgsR = organizationService.getTenantPathsByUserIds(userIds);
            List<Organization> orgList = orgsR.getDataList(new TypeToken<List<Organization>>() {
            }.getType());
            if (CollectionUtil.isNotEmpty(orgList)) {
                log.info("查询组织机构的结果的大小===" + orgList.size());
                alarmVehicleList.forEach(vo -> {
                    if (vo.getCreatedBy() != null) {
                        List<Organization> organizations = orgList.stream()
                                .filter(org -> org.getUserId().equals(vo.getCreatedBy().longValue()))
                                .collect(Collectors.toList());
                        List<String> names = organizations.stream()
                                .map(Organization::getOrgName)
                                .collect(Collectors.toList());
                        vo.setCreator(StringUtils.join(names, "/"));
                    }
                });
            }
        }

        // 6. 汇总每辆车的警情次数
        for (AlarmVehicleVO vo : alarmVehicleList) {
            List<String> vehicleSns = vehicleSnMap.get(vo.getVehicleId());
            if (CollectionUtil.isNotEmpty(vehicleSns)) {
                int totalAlarmCount = vehicleSns.stream()
                        .mapToInt(sn -> snAlarmCountMap.getOrDefault(sn, 0))
                        .sum();
                vo.setAlarmCount(totalAlarmCount);
            }
        }

        if (log.isDebugEnabled() && CollectionUtil.isNotEmpty(alarmVehicleList)) {
            AlarmVehicleVO s = alarmVehicleList.get(0);
            log.debug("judgment.alarmVehicle sample: vehicleId={}, vin={}, alarmCount={}",
                    s.getVehicleId(), s.getVin(), s.getAlarmCount());
        }
        log.info("judgment.alarmVehicle assembledCount={}, totalCostMs={}",
                alarmVehicleList.size(), (System.currentTimeMillis() - allStart));*/
        return new PageInfo<>(alarmVehicleList);
    }

    public List<JudgmentExport> exportJudgmentList(JudgmentSearch search) {
        long allStart = System.currentTimeMillis();
        injectOrgChecked(search);

        List<JudgmentExport> judgmentList = vehicleMapper.findJudgmentList(search);
        if (ObjectUtil.isNull(judgmentList)) {
            log.info("judgment.export early-return: baseListNull=true, costMs={}", (System.currentTimeMillis() - allStart));
            return null;
        }
        log.info("judgment.export baseListSize={}", judgmentList.size());
        List<String> snList = judgmentList.stream().map(JudgmentExport::getSn).collect(Collectors.toList());
        long remoteStart = System.currentTimeMillis();
        List<StuJudgeAlarmDto> stuJudgeAlarmDtoList;
        try {
            stuJudgeAlarmDtoList = remoteStuJudgeAlarmService.searchStuJudgeAlarmDataList(snList, search);
        } catch (RuntimeException ex) {
            log.error("judgment.export remote-call-failed: snSize={}, costMs={}, error={}",
                    snList != null ? snList.size() : 0, (System.currentTimeMillis() - remoteStart), ex.toString());
            throw ex;
        }
        log.info("judgment.export remote-call-ok: snSize={}, remoteCount={}, costMs={}",
                snList != null ? snList.size() : 0,
                stuJudgeAlarmDtoList != null ? stuJudgeAlarmDtoList.size() : 0,
                (System.currentTimeMillis() - remoteStart));
        if (CollectionUtil.isEmpty(stuJudgeAlarmDtoList)) {
            log.info("judgment.export early-return: remoteListEmpty=true, costMs={}", (System.currentTimeMillis() - allStart));
            return null;
        }

        Map<String, JudgmentExport> judgmentExportMap = judgmentList.stream().filter(judgement -> StringUtils.isNotBlank(judgement.getSn())).collect(Collectors.toMap(JudgmentExport::getSn, Function.identity(), (v1, v2) -> v1));
        List<JudgmentExport> judgmentExportList = Lists.newArrayList();
        stuJudgeAlarmDtoList.forEach(stuJudgeAlarm -> {
            if (StringUtils.isBlank(stuJudgeAlarm.getSn())) {
                return;
            }

            JudgmentExport judgmentExportTemp = judgmentExportMap.get(stuJudgeAlarm.getSn());
            if (judgmentExportTemp != null) {
                JudgmentExport judgmentExport = new JudgmentExport();
                BeanUtils.copyProperties(judgmentExportTemp, judgmentExport);
                judgmentExport.setSourceStr(TypeConverseEnum.SourceEnum.getStrBySourceType(judgmentExport.getSource()));
                judgmentExport.setAlarmType(stuJudgeAlarm.getAlarmType());
                judgmentExport.setAlarmTypeStr(TypeConverseEnum.AlarmTypeEnum.getStrByAlarmType(stuJudgeAlarm.getAlarmType()));
                judgmentExport.setAlarmStatus(stuJudgeAlarm.getAlarmStatus());
                judgmentExport.setAlarmStatusStr(TypeConverseEnum.AlarmStatusEnum.getStrByAlarmStatus(stuJudgeAlarm.getAlarmStatus()));
                judgmentExport.setGeoCode(stuJudgeAlarm.getGeoCode());
                judgmentExport.setAlarmAddress(stuJudgeAlarm.getAlarmAddress());
                judgmentExport.setAlarmBeginTime(stuJudgeAlarm.getAlarmBeginTime());
                judgmentExport.setAlarmEndTime(stuJudgeAlarm.getAlarmEndTime());
                if (TypeConverseEnum.AlarmStatusEnum.TAKE_EFFECT.getAlarmStatus().equals(stuJudgeAlarm.getAlarmStatus())) {
                    // 如果警情为生效警情 则将失效时间设备为 --
                    judgmentExport.setAlarmEndTime("--");
                }
                
                // 计算报警持续时间(驶出-进入):显示规则 <1天按小时;≥1天按X天Y小时;任一时间为"--"时显示"--"
                if ("--".equals(judgmentExport.getAlarmBeginTime()) || "--".equals(judgmentExport.getAlarmEndTime())) {
                    judgmentExport.setAlarmDuration("--");
                } else {
                    try {
                        java.util.Date begin = DateUtil.parse(judgmentExport.getAlarmBeginTime());
                        java.util.Date end = DateUtil.parse(judgmentExport.getAlarmEndTime());
                        long diffMs = end.getTime() - begin.getTime();
                        if (diffMs <= 0) {
                            judgmentExport.setAlarmDuration("0小时");
                        } else {
                            long hours = diffMs / (1000 * 60 * 60);
                            if (hours < 24) {
                                judgmentExport.setAlarmDuration(hours + "小时");
                            } else {
                                long days = hours / 24;
                                long remainHours = hours % 24;
                                judgmentExport.setAlarmDuration(days + "天" + remainHours + "小时");
                            }
                        }
                    } catch (Exception e) {
                        judgmentExport.setAlarmDuration("--");
                    }
                }
                
                judgmentExport.setAlarmLng(stuJudgeAlarm.getAlarmLng());
                judgmentExport.setAlarmLat(stuJudgeAlarm.getAlarmLat());
                judgmentExport.setAlarmAddress(stuJudgeAlarm.getAlarmAddress());
                judgmentExport.setAlarmCount(stuJudgeAlarm.getAlarmCount());
                judgmentExport.setAlarmLevel(stuJudgeAlarm.getAlarmLevel());
                judgmentExportList.add(judgmentExport);
            }
        });
        if (log.isDebugEnabled() && CollectionUtil.isNotEmpty(judgmentExportList)) {
            JudgmentExport s = judgmentExportList.get(0);
            log.debug("judgment.export sample: sn={}, vin={}, alarmType={}, alarmStatus={}",
                    s.getSn(), s.getVin(), s.getAlarmType(), s.getAlarmStatus());
        }
        log.info("judgment.export assembledCount={}, totalCostMs={}",
                judgmentExportList.size(), (System.currentTimeMillis() - allStart));
        return judgmentExportList;
    }
}