SchedulingService.java 20.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
package com.ruoyi.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.cache.NowSchedulingCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.DriverScheduling;
import com.ruoyi.domain.scheduling.LinggangScheduling;
import com.ruoyi.driver.mapper.DriverSchedulingMapper;
import com.ruoyi.in.domain.SignIn;
import com.ruoyi.in.mapper.SignInMapper;
import com.ruoyi.in.service.impl.SignInServiceImpl;
import com.ruoyi.pojo.DriverSignInRecommendation;
import com.ruoyi.pojo.GlobalIndex;
import com.ruoyi.pojo.request.ReportViewRequestVo;
import com.ruoyi.pojo.response.ReportViewResponseVo;
import com.ruoyi.service.scheduling.LinggangSchedulingService;
import com.ruoyi.utils.ConstDateUtil;
import com.ruoyi.utils.DateUtil;
import com.ruoyi.utils.ToolUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.ConstDriverProperties.*;
import static com.ruoyi.common.ConstSignInConstSignInProperties.*;
import static com.ruoyi.common.ErrorTypeProperties.*;
import static com.ruoyi.common.ReportProperties.NOW;
import static com.ruoyi.common.SignStatusEnum.SIGN_STATUS_DELAY_ENUM;

/**
 * @author 20412
 */
@Service
public class SchedulingService {

    @Resource
    private NowSchedulingCache nowSchedulingCache;

    @Autowired
    private DriverSchedulingMapper schedulingMapper;

    @Autowired
    private SignInMapper signInMapper;

    @Resource
    private BigViewServiceV1 bigViewServiceV1;

    @Autowired
    private LinggangSchedulingService schedulingService;


    /**
     * 获取排班信息 并排序
     *
     * @param jobCode
     * @param now
     * @return
     */
    public List<DriverScheduling> queryScheduling(String jobCode, Long now) {

        List<DriverScheduling> dto = null;
        for (int i = 0; i > -2; i--) {
            dto = nowSchedulingCache.getCacheSchedulingMapValueByHKey(ConstDateUtil.formatDate(ConstDateUtil.getTheSpecifiedNumberOfDaysOfTime(i)), jobCode);
            if(CollectionUtils.isEmpty(dto)){
                Date date = new Date(now);
                LinggangScheduling linggangScheduling = new LinggangScheduling();
                linggangScheduling.setScheduleDate(DateUtil.shortDate(date));
                linggangScheduling.setJobCode(jobCode);

                List<LinggangScheduling> linggangSchedulings = schedulingService.list(linggangScheduling);
                if(CollectionUtils.isNotEmpty(linggangSchedulings)){
                    dto = linggangSchedulings.stream().map(l->{
                        DriverScheduling driverScheduling = new DriverScheduling();
                        BeanUtils.copyProperties(l,driverScheduling);
                        return driverScheduling;
                    }).collect(Collectors.toList());
                }

            }
            if (!CollectionUtil.isEmpty(dto)) {
                dto.sort(Comparator.comparing(DriverScheduling::getZdsjT));
                if (i == -1) {
                    LocalDateTime zdsjT = ConstDateUtil.getLocalDateTimeByLongTime(dto.get(dto.size() - 1).getZdsjT());
                    LocalDateTime nowTime = ConstDateUtil.getLocalDateTimeByLongTime(now);
                    long range = ChronoUnit.MINUTES.between(zdsjT, nowTime);
                    // 判定存在排班 前天的最后一次打卡时间超过2小时,排班为null
                    if (range > 120L) {
                        dto = null;
                    }
                }
                break;
            }
        }
        return dto;
    }


    /**
     * 计算当前签到签到逻辑
     *
     * @param dto
     * @param now
     * @return
     */
    public DriverSignInRecommendation computedTheCurrentClosestTimestamp(List<DriverScheduling> dto, Long now, Integer result) {
        Map<Integer, DriverSignInRecommendation> timeMap = new HashMap<>();
        for (int i = 0; i < dto.size(); i++) {
            timeMap.put(i, new DriverSignInRecommendation(dto.get(i), i));
        }
        long minDiff = Long.MAX_VALUE;
        Integer index = 0;
        // 迭代比较每个时间戳与当前时间戳的差值
        for (Integer i : timeMap.keySet()) {
            long diff = Math.abs(now - timeMap.get(i).getTimestamps());
            if (diff < minDiff) {
                minDiff = diff;
                index = i;
            }
        }
        if (index + result >= 0 && index + result < timeMap.size()) {
            index = index + result;
        }
        return timeMap.get(index);
    }

    /**
     * 更具最新的签到记录判断是否需要更新考勤。
     *
     * @param signIn
     */
    public void computedSignInBySignIn(DriverScheduling driverScheduling, int index, SignIn signIn, boolean isNew) {
        // 无排班不记录不在考勤表不更新
        if (Objects.isNull(driverScheduling)) {
            return;
        }
        String remark = getRemark(driverScheduling, signIn);
        // 更新最新的签到记录判断是否需要更新考勤
        // 记录为空直接插入记录
        if (Objects.isNull(driverScheduling.getSignInId())) {
            schedulingMapper.updateRoster(driverScheduling, signIn.getId(), signIn.getExType(), signIn.getCreateTime(), remark, signIn.getType(), signIn.getAlcoholFlag(), signIn.getAlcoholIntake());
            // 更新缓存
            nowSchedulingCache.updateCacheByJobCode(remark, ConstDateUtil.formatDate(driverScheduling.getScheduleDate()), index, signIn, isNew, driverScheduling);
        }
        // 之前的无效
        else if (!SIGN_NO_EX_NUM.equals(driverScheduling.getExType())) {
            schedulingMapper.updateRoster(driverScheduling, signIn.getId(), signIn.getExType(), signIn.getCreateTime(), remark, signIn.getType(), signIn.getAlcoholFlag(), signIn.getAlcoholIntake());
            nowSchedulingCache.updateCacheByJobCode(remark, ConstDateUtil.formatDate(driverScheduling.getScheduleDate()), index, signIn, isNew, driverScheduling);
        }
        // 之前的有效
        else {
            handlerRecord(driverScheduling, signIn, index, isNew);
        }

    }

    private String getRemark(DriverScheduling scheduling, SignIn signIn) {
        StringBuilder sb = new StringBuilder();
        if (bigViewServiceV1.isEarly(signIn)) {
            sb.append(EARLY);
        } else if (bigViewServiceV1.isSignStatusDelayEnum(signIn)) {
            sb.append(SIGN_STATUS_DELAY_ENUM.getDescription(scheduling.getBcType()));
        } else if (StringUtils.isNotEmpty(signIn.getRemark())) {
            sb.append(signIn.getRemark());
        }
        if (bigViewServiceV1.isSignStatusWineEnum(signIn) && StringUtils.isNotEmpty(signIn.getRemark())) {
            if (StringUtils.indexOf(scheduling.getRemark(), signIn.getRemark()) > -1) {
                return scheduling.getRemark();
            }

            if (StringUtils.indexOf(sb.toString(), signIn.getRemark()) > -1) {
                return sb.toString();
            }
            int index = signIn.getRemark().indexOf(ALCOHOL_SIGN_IN_ERROR);
            if (index != -1) {
                sb.append("," + signIn.getRemark().substring(index));
            }
        }
        return StringUtils.isEmpty(sb.toString()) ? "正常" : sb.toString();
    }

    private void handlerRecord(DriverScheduling scheduling, SignIn signIn, Integer index, boolean isNew) {
        if (Objects.isNull(scheduling)) {
            return;
        }
        long timer = 1000 * 60 * 3;
        // 有效的在三分钟内重复签到不做修改
        if (signIn.getExType().equals(SIGN_NO_EX_NUM) && (DateUtils.getNowDate().getTime() - scheduling.getSignTime().getTime()) <= timer) {
            signIn.setRemark("您已经打卡过了,请勿在3分钟内重复打卡");
            return;
        }
        //   目前也有效 -》 无需更新 || 目前无效 -》往后更新
        //   TODO 判断时间   之前的有效 但是人员提前打卡且还在上次操作有效范围内需要往后偏移
        //    但是操作一样时间还在有效范围内打卡的话会导致排班表数据不匹配

        if (signIn.getExType().equals(SIGN_NO_EX_NUM)) {
            if (signIn.getType().equals(bcTypeTransform(scheduling.getBcType()))) {
                return;
            }
        }


        String remark = getRemark(scheduling, signIn);
        signInMapper.updateSignIn(signIn);
        schedulingMapper.updateRoster(scheduling, signIn.getId(), signIn.getExType(), signIn.getCreateTime(), remark, signIn.getType(), signIn.getAlcoholFlag(), signIn.getAlcoholIntake());
        nowSchedulingCache.updateCacheByJobCode(remark, ConstDateUtil.formatDate(scheduling.getScheduleDate()), index, signIn, isNew, scheduling);
    }

    /**
     * 更具最新的签到记录判断是否需要更新考勤。
     *
     * @param dto
     * @param signIn
     * @param globalIndex
     */
    public void computedSignInBySignIn(List<DriverScheduling> dto, SignIn signIn, GlobalIndex globalIndex) {
        // 无排班不记录不在考勤表不更新
        if (CollectionUtil.isEmpty(dto)) {
            return;
        }
        String remark = getRemark(dto, signIn, globalIndex.getIndex());
        // 更新最新的签到记录判断是否需要更新考勤
        // 记录为空直接插入记录
        if (Objects.isNull(dto.get(globalIndex.getIndex()).getSignInId()) || dto.size() == 1) {
            schedulingMapper.updateRoster(dto.get(globalIndex.getIndex()), signIn.getId(), signIn.getExType(), signIn.getCreateTime(), remark, signIn.getType(), signIn.getAlcoholFlag(), signIn.getAlcoholIntake());
            // 更新缓存
            nowSchedulingCache.updateCacheByJobCode(remark, ConstDateUtil.formatDate(dto.get(0).getScheduleDate()), globalIndex.getIndex(), signIn);
        }
        // 之前的无效
        else if (!SIGN_NO_EX_NUM.equals(dto.get(globalIndex.getIndex()).getExType())) {
            schedulingMapper.updateRoster(dto.get(globalIndex.getIndex()), signIn.getId(), signIn.getExType(), signIn.getCreateTime(), remark, signIn.getType(), signIn.getAlcoholFlag(), signIn.getAlcoholIntake());
            nowSchedulingCache.updateCacheByJobCode(remark, ConstDateUtil.formatDate(dto.get(0).getScheduleDate()), globalIndex.getIndex(), signIn);
        }
        // 之前的有效
        else {
            handlerRecord(dto, signIn, globalIndex);
        }

    }

    private String getRemark(List<DriverScheduling> dto, SignIn signIn, Integer globalIndex) {
        StringBuilder sb = new StringBuilder();
        DriverScheduling scheduling = dto.get(globalIndex);
        long date = scheduling.getBcType().equals(BC_TYPE_IN) ? scheduling.getZdsjT() : scheduling.getFcsjT();
        long nowBetween = ChronoUnit.MINUTES.between(ConstDateUtil.getLocalDateTimeByLongTime(date), ConstDateUtil.getLocalDateTimeByLongTime(signIn.getCreateTime().getTime()));
        if (SignInServiceImpl.checkTimerSign(nowBetween, scheduling.getBcType())) {
            if (nowBetween < -SIGN_OUT_TIME || (BC_TYPE_IN.equals(scheduling.getBcType()) && nowBetween < 0L)) {
                sb.append(EARLY);
            } else {
                sb.append(SIGN_STATUS_DELAY_ENUM.getDescription(scheduling.getBcType()));
            }
            // 在规定时间就还原remark
        } else {
            sb.append(signIn.getRemark());
        }
        if (SIGN_ALCOHOL_EX_NUM.equals(signIn.getExType())) {
            int index = signIn.getRemark().indexOf(ALCOHOL_SIGN_IN_ERROR);
            if (index != -1) {
                sb.append("," + signIn.getRemark().substring(index));
            }
        }
        return sb.toString();
    }


    private void handlerRecord(List<DriverScheduling> dto, SignIn signIn, GlobalIndex globalIndex) {
        if (globalIndex.getIndex() == dto.size() - 1) {
            return;
        }
        long timer = 1000 * 60 * 3;
        // 有效的在三分钟内重复签到不做修改
        if (signIn.getExType().equals(SIGN_NO_EX_NUM) && (DateUtils.getNowDate().getTime() - dto.get(globalIndex.getIndex()).getSignTime().getTime()) <= timer) {
            signIn.setRemark("您已经打卡过了,请勿在3分钟内重复打卡");
            return;
        }
        //   目前也有效 -》 无需更新 || 目前无效 -》往后更新
        //   TODO 判断时间   之前的有效 但是人员提前打卡且还在上次操作有效范围内需要往后偏移
        //    但是操作一样时间还在有效范围内打卡的话会导致排班表数据不匹配
        int index = dto.size() > globalIndex.getIndex() ? globalIndex.getIndex() + 1 : globalIndex.getIndex();
        if (signIn.getExType().equals(SIGN_NO_EX_NUM)) {
            if (signIn.getType().equals(bcTypeTransform(dto.get(globalIndex.getIndex()).getBcType()))) {
                return;
            }
            // 校验下一次的时间
            DriverSignInRecommendation nextClosestTimestamp = computedTheCurrentClosestTimestamp(dto, signIn.getCreateTime().getTime(), 1);
            LocalDateTime endTime = ConstDateUtil.getLocalDateTimeByLongTime(nextClosestTimestamp.getTimestamps());
            LocalDateTime nowTime = ConstDateUtil.getLocalDateTimeByLongTime(signIn.getCreateTime().getTime());
            long nowBetween = ChronoUnit.MINUTES.between(endTime, nowTime);
            boolean result = SignInServiceImpl.checkTimerSign(nowBetween, nextClosestTimestamp.getBcType());
            // 不在范围内设置异常
            if (result) {
                signIn.setExType(SIGN_TIME_OUT_EX_NUM);
            }
        }
        DriverScheduling scheduling = dto.get(index);
        long date = scheduling.getBcType().equals(BC_TYPE_IN) ? scheduling.getZdsjT() : scheduling.getFcsjT();
        String prompt = getPrompt(new Date(date), scheduling.getBcType());
        signIn.setRemark((scheduling.getBcType().equals(BC_TYPE_IN) ? SIGN_OUT_TIMEOUT : SIGN_IN_TIMEOUT) + prompt);
        signIn.setRemark(signIn.getRemark().replaceFirst(",$", "。"));
        String remark = getRemark(dto, signIn, index);
        signInMapper.updateSignIn(signIn);
        schedulingMapper.updateRoster(scheduling, signIn.getId(), signIn.getExType(), signIn.getCreateTime(), remark, signIn.getType(), signIn.getAlcoholFlag(), signIn.getAlcoholIntake());
        nowSchedulingCache.updateCacheByJobCode(remark, ConstDateUtil.formatDate(dto.get(0).getScheduleDate()), globalIndex.getIndex() + 1, signIn);
    }

    private Integer bcTypeTransform(String bcType) {
        if (BC_TYPE_OUT.equals(bcType)) {
            return 1;
        } else {
            return 2;
        }
    }

    private String getPrompt(Date date, String bcType) {
        if (BC_TYPE_OUT.equals(bcType)) {
            LocalDateTime time = ConstDateUtil.stringTransformLocalDateTime(ConstDateUtil.formatDate("yyyy-MM-dd HH:mm:ss", date), "yyyy-MM-dd HH:mm:ss");
            LocalDateTime subTime = time.plusHours(-1);
            return "请在" + ConstDateUtil.formatDate("HH:mm", subTime) + "到" +
                    ConstDateUtil.formatDate("HH:mm", time) + "之间打卡";
        } else {
            LocalDateTime time = ConstDateUtil.stringTransformLocalDateTime(ConstDateUtil.formatDate("yyyy-MM-dd HH:mm:ss", date), "yyyy-MM-dd HH:mm:ss");
            LocalDateTime addHours = time.plusMinutes(80);
            return "请在" + ConstDateUtil.formatDate("HH:mm", time) + "到" +
                    ConstDateUtil.formatDate("HH:mm", addHours) + "之间打卡";
        }
    }

    public List<ReportViewResponseVo> queryReportTableResponseVo(ReportViewRequestVo requestVo, HttpServletResponse response) {
        // 处理天
        if (requestVo.getExportFlag().equals(NOW)) {
            return getDayReportTableResponseVo(requestVo);
        }
        return null;
    }


    private List<ReportViewResponseVo> getDayReportTableResponseVo(ReportViewRequestVo vo) {
        String endDateStr = null;
        try {
            endDateStr = DateUtil.YYYY_MM_DD_LINK.format(org.apache.commons.lang3.time.DateUtils.addDays(DateUtil.YYYY_MM_DD_LINK.parse(vo.getDate()),1));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        // 签到数据
        List<DriverScheduling> toDay = schedulingMapper.queryToDay(vo.getDate(),endDateStr, vo.getName(), vo.getJobCode(), vo.getLineName());
        toDay.sort(Comparator.comparing(DriverScheduling::getFcsjT));
        // 转换日期 + jobCode为key
        Map<String, List<DriverScheduling>> orangeMap = new HashMap<>(1200);
        transformMapByDriverScheduling(vo, toDay, orangeMap);
        Map<String, ReportViewResponseVo> resultMap = new HashMap<>(1200);
        for (String key : orangeMap.keySet()) {
            List<DriverScheduling> list = orangeMap.get(key);
            // 如果有选超时过滤的话过滤
            if (filterReportVoList(vo.getStage(), list)) {
                continue;
            }
            ReportViewResponseVo vo1 = new ReportViewResponseVo();
            handlerScheduling(list, vo1);
            resultMap.put(key, vo1);
        }
        return new ArrayList<>(resultMap.values());
    }

    private static void transformMapByDriverScheduling(ReportViewRequestVo vo, List<DriverScheduling> toDay, Map<String, List<DriverScheduling>> orangeMap) {
        for (DriverScheduling scheduling : toDay) {
            String key = vo.getDate() + scheduling.getJobCode();
            if (Objects.isNull(orangeMap.get(key))) {
                ToolUtils.updateReport(scheduling);
                orangeMap.put(key, new ArrayList<>(Arrays.asList(scheduling)));
            } else {
                orangeMap.get(key).add(scheduling);
            }
        }
    }

    private boolean filterReportVoList(Integer stage, List<DriverScheduling> list) {
        if (!stage.equals(0)) {
            return handleReportScrollViewTable(stage, list);
        }
        return false;
    }

    private boolean handleReportScrollViewTable(Integer stage, List<DriverScheduling> list) {
        if (list.size() < stage) {
            return true;
        }
        DriverScheduling scheduling = list.get(stage - 1);
        // 获取两个 Date 对象之间的时间差(以毫秒为单位)
        long signTime = scheduling.getSignTime() == null ? System.currentTimeMillis() : scheduling.getSignTime().getTime();
        long timeDifferenceInMillis = signTime - (scheduling.getBcType().equals(BC_TYPE_OUT) ? scheduling.getFcsjT() : scheduling.getZdsjT());
        long diffTime = 60 * 1000 * 15;
        // 相差十五分钟
        if (timeDifferenceInMillis <= diffTime) {
            return true;
        }
        return false;
    }

    private static void handlerScheduling(List<DriverScheduling> list, ReportViewResponseVo vo) {
        int planSignInCount = 0;
        int actualSignInCount = 0;
        int planSignOutCount = 0;
        int actualSignOutCount = 0;
        BeanUtils.copyProperties(list.get(0), vo);
        String exString = NO_EX;
        for (DriverScheduling scheduling : list) {
            // 获取计划签到|签退次数
            if (scheduling.getBcType().equals(BC_TYPE_OUT)) {
                planSignInCount = planSignInCount + 1;
                if (!Objects.isNull(scheduling.getSignInId())) {
                    actualSignInCount = actualSignInCount + 1;
                }

            } else {
                planSignOutCount = planSignOutCount + 1;
                if (!Objects.isNull(scheduling.getSignInId())) {
                    actualSignOutCount = actualSignOutCount + 1;
                }
            }

            // 判断是否异常
            if (!SIGN_NO_EX_NUM.equals(scheduling.getExType())) {
                exString = HAVE_EX;
            }
        }
        vo.setExString(exString);
        vo.setPlanSignInCount(planSignInCount);
        vo.setPlanSignOutCount(planSignOutCount);
        vo.setActualSignInCount(actualSignInCount);
        vo.setActualSignOutCount(actualSignOutCount);
    }

    public List<DriverScheduling> queryToDay(String date) {
        String endDateStr = null;
        try {
            endDateStr = DateUtil.YYYY_MM_DD_LINK.format(org.apache.commons.lang3.time.DateUtils.addDays(DateUtil.YYYY_MM_DD_LINK.parse(date),1));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return schedulingMapper.queryToDay(date,endDateStr, null, null, null);
    }


}