ThreadJobService.java 35.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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
package com.ruoyi.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.cache.NowSchedulingCache;
import com.ruoyi.common.cache.TempCache;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.file.FileUploadException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.config.domain.LineConfig;
import com.ruoyi.config.service.ILineConfigService;
import com.ruoyi.domain.RuleAttendanceMain;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.mapper.DriverMapper;
import com.ruoyi.driver.mapper.DriverSchedulingMapper;
import com.ruoyi.eexception.domain.EquipmentException;
import com.ruoyi.eexception.mapper.EquipmentExceptionMapper;
import com.ruoyi.equipment.domain.Equipment;
import com.ruoyi.equipment.domain.EquipmentLog;
import com.ruoyi.equipment.mapper.EquipmentMapper;
import com.ruoyi.errorScheduling.domain.ErrorJobcode;
import com.ruoyi.errorScheduling.service.IErrorJobcodeService;
import com.ruoyi.in.domain.SignIn;
import com.ruoyi.job.DriverJob;
import com.ruoyi.domain.DriverScheduling;
import com.ruoyi.pojo.GlobalIndex;
import com.ruoyi.pojo.response.ResponseSchedulingDto;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.utils.ConstDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.ConstDriverProperties.BC_TYPE_IN;
import static com.ruoyi.common.ConstDriverProperties.BC_TYPE_OUT;
import static com.ruoyi.common.ConstEquipmentProperties.*;
import static com.ruoyi.common.ConstSignInConstSignInProperties.SIGN_ALCOHOL_EX_NUM;
import static com.ruoyi.common.ConstSignInConstSignInProperties.SIGN_NO_EX_NUM;
import static com.ruoyi.common.RuleSchedulingProperties.*;


/**
 * 多线程任务
 *
 * @author 20412
 */
@EnableAsync
@Component
@Slf4j
public class ThreadJobService {

    @Autowired
    private IErrorJobcodeService errorJobcodeService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private ILineConfigService lineConfigService;

    @Resource
    private EmailService emailService;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private DriverSchedulingMapper schedulingMapper;

    @Resource
    private NowSchedulingCache nowSchedulingCache;

    @Autowired
    private RuleAttendanceMainService attendanceMainService;


    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private EquipmentExceptionMapper exceptionMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Value("${api.headImage}")
    private String headImagePre;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 异步上传图片
     *
     * @param url
     * @param base64
     * @throws FileUploadException
     * @throws IOException
     */
    @Async
    public void asyncStartUploadBase64Image(String url, String base64) {
        FileOutputStream outputStream = null;
        base64 = base64.replaceAll(" ", "");
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] photoBase64 = decoder.decodeBuffer(base64);
            for (int i = 0; i < photoBase64.length; ++i) {
                //调整异常数据
                if (photoBase64[i] < 0) {
                    photoBase64[i] += 256;
                }
            }
            outputStream = new FileOutputStream(url);
            outputStream.write(photoBase64);
            outputStream.flush();
            log.info("异步文件上传完毕");
        } catch (Exception e) {
            log.error("文件上传异常:{}", e.getMessage());
        } finally {
            try {
                if (!Objects.isNull(outputStream)) {
                    outputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 签到人员与签到设备绑定
     *
     * @param deviceId
     * @param jobCodes
     */
    @Async
    public void asyncInsertSignInContactEquipment(String deviceId, List<String> jobCodes) {
        Integer result = driverMapper.insertDriverFace(deviceId, jobCodes);
        log.info("注册设备与员工关联完毕:{}", result);
    }

    @Async
    public void asyncInsertExceptionRecord(SignIn signIn, Driver driver, List<DriverScheduling> dto, GlobalIndex globalIndex) {
        if (!SIGN_NO_EX_NUM.equals(signIn.getExType())) {
            EquipmentException exception = new EquipmentException();
            exception.setExType(signIn.getExType());
            exception.setDeviceId(signIn.getDeviceId());
            exception.setJobCode(signIn.getJobCode());
            exception.setStatus(EQUIPMENT_PROCESS_FLOW_COMMIT);
            exception.setImage(signIn.getImage());
            exception.setTitle("打卡异常");
            exception.setRemark(signIn.getRemark());
            exception.setCreateTime(signIn.getCreateTime());
            exception.setFleetName(driver.getFleetName());
            if (CollectionUtil.isNotEmpty(dto) && dto.size() > 0) {
                DriverScheduling scheduling = dto.get(globalIndex.getIndex());
                exception.setNbbm(scheduling.getNbbm());
                exception.setLineName(scheduling.getLineName());
                exception.setPlanTime(scheduling.getBcType().equals(BC_TYPE_IN) ? new Date(scheduling.getZdsjT()) : new Date(scheduling.getFcsjT()));
            }
            exception.setSignType(signIn.getType());
            exceptionMapper.insertEquipmentException(exception);
            // 发送通知
            sendNotice(signIn, driver, dto, globalIndex);
        }
    }

    private void sendNotice(SignIn signIn, Driver driver, List<DriverScheduling> dto, GlobalIndex globalIndex) {
        if (SIGN_ALCOHOL_EX_NUM.equals(signIn.getExType())) {
            SysNotice notice = new SysNotice();
            notice.setCreateBy("system");
            notice.setUpdateBy("system");
            notice.setNoticeTitle("酒精测试异常通知");
            DriverScheduling item = null;
            if (CollectionUtil.isEmpty(dto)) {
                item = new DriverScheduling();
                handlerNoScheduling(item, signIn, driver);
            } else {
                item = dto.get(globalIndex.getIndex());
            }
            String jobCode = "工号:" + item.getJobCode() + "\n";
            String name = "姓名:" + item.getName() + "\n";
            String posts = "工种:" + item.getPosts() + "\n";
            String fleetName = "车队:" + item.getFleetName() + "\n";
            String scheduling = "排班:" + (Objects.isNull(item.getScheduleDate()) ? "无排班" : "有排班") + "\n";
            String signDate = "打卡时间:" + ConstDateUtil.formatDate("yyyy-MM-dd HH:mm:ss", signIn.getCreateTime()) + "\n";
            String cause = "原因:酒精测试超标,当前测试值达到" + signIn.getAlcoholIntake() + "mg/100ml。属于" + getResultString(signIn.getAlcoholIntake());
            String content = jobCode + name + posts + fleetName + scheduling + signDate + cause;
            notice.setNoticeContent(content);
            notice.setNoticeType("1");
            notice.setStatus("0");
            notice.setCreateTime(DateUtils.getNowDate());
            notice.setUpdateTime(DateUtils.getNowDate());
            noticeService.insertNotice(notice);
        }
    }

    private String getResultString(BigDecimal alcoholIntake) {
        if (alcoholIntake.compareTo(new BigDecimal(20)) >= 0 && alcoholIntake.compareTo(new BigDecimal(80)) < 0) {
            return "饮酒后驾驶机动车";
        } else {
            return "醉酒后驾驶机动车";
        }

    }

    @Async
    public void asyncUploadDriverWithUpdateImageUrl(List<Driver> drivers, String token) {
        // 插入数据
        for (Driver driver : drivers) {
            // 开启事务
            TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionDefinition());
            try {
                // 插入数据
                insertDriverInfo(token, driver);
                // 提交事务
                transactionManager.commit(transaction);
            } catch (Exception e) {
                // 回滚事务
                transactionManager.rollback(transaction);
                log.error("保存数据是出现了异常:{}", e.getMessage());
            }
        }
    }

    /**
     * 异步发送邮件
     *
     * @param dto
     * @param signIn
     * @param driver
     */
    @Async
    public void asyncSendEmail(List<DriverScheduling> dto, Integer index, SignIn signIn, Driver driver) {
        DriverScheduling item = null;
        if (CollectionUtil.isEmpty(dto)) {
            item = new DriverScheduling();
            handlerNoScheduling(item, signIn, driver);
            // 无排班
            emailService.sendWarningEmail(item, signIn.getCreateTime(), signIn.getAlcoholIntake());
        } else {
            // 有排班
            emailService.sendWarningEmail(dto.get(index), signIn.getCreateTime(), signIn.getAlcoholIntake());
        }

    }

    private void handlerNoScheduling(DriverScheduling item, SignIn signIn, Driver driver) {
        BeanUtils.copyProperties(signIn, item);
        item.setName(driver.getPersonnelName());
        item.setFleetName(driver.getFleetName());
        item.setPosts(driver.getPosts());
    }

    private void insertDriverInfo(String token, Driver driver) {
        String headImageUrl = driver.getImage();
        // 生成文件路径
        String fileName = driver.getJobCode() + ".png";
        String filePath = RuoYiConfig.getUploadPath() + headImagePre + "/" + fileName;
        try {
            fileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath() + headImagePre, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        driver.setImage(fileName);
        // 插入数据  如果员工已经存在在不在下载图片
        String imageUrl = DriverJob.getDownloadImageUrl(token, headImageUrl);
        // 获取图片请求地址
        if (StringUtils.isEmpty(imageUrl)) {
            log.error("工号:{},图片缺失,放弃保存员工信息,等待员工图片手动上传。", driver.getJobCode());
        }
        int result = driverMapper.insertDriver(driver);
        log.debug("插入完毕");
        if (result != 0 && StringUtils.isNotEmpty(imageUrl)) {
            log.info("图片开始上传");
            // 获取图片数据
            InputStream is = getImageInputStreamByUrl(imageUrl);
            // 上传图片
            try {
                uploadImage(is, filePath);
            } catch (IOException e) {
                log.error("工号:{}的人脸图像,上传失败:{}", driver.getJobCode(), e.getMessage());
                is = getImageInputStreamByUrl(imageUrl);
                try {
                    uploadImage(is, filePath);
                } catch (IOException ex) {
                    log.error("工号:{}的人脸图像,再次上传失败:{}", driver.getJobCode(), e.getMessage());
                    throw new RuntimeException(ex);
                }
            }
            log.info("图片上传完毕");
        }

    }

    private InputStream getImageInputStreamByUrl(String imageUrl) {
        return HttpUtil.createGet(imageUrl).execute().bodyStream();
    }

    public static void uploadImage(InputStream is, String filePath) throws IOException {
        if (Objects.isNull(is)) {
            throw new IOException("图片数据不存在");
        }
        File file = new File(filePath + File.separator);
        log.info("文件路径:{}", file.getPath());
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
        }
        // 保存图片到本地文件
        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(file);
            byte[] cbuf = new byte[1024];
            int len;
            while ((len = is.read(cbuf)) != -1) {
                fos.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 检查文件类型
     *
     * @param b
     * @return
     */
    public static String checkImageBase64Format(byte[] b) {
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".png";
        } else {
            type = ".jpg";
        }
//        else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
//            type = "jpg";
//        }
        return type;
    }


    /**
     * 保存当天的调度信息
     *
     * @param originSchedulingMap
     * @param timeOut
     */
    @Async
    @Transactional(rollbackFor = {Exception.class})
    public void asyncComputedScheduling(Map<String, List<ResponseSchedulingDto>> originSchedulingMap, String timeOut) {
        if (StringUtils.isNotEmpty(timeOut)) {
            LocalDate date = LocalDate.now();
            Date date2 = ConstDateUtil.dateAddition(date.toString(), timeOut);
            Date date1 = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 如果当前日期小于设定时间就不获取固定排班
            log.info("当前时间:{},设定时间:{}", simpleDateFormat.format(date1), simpleDateFormat.format(date2));
            if (date1.compareTo(date2) < 0) {
                log.info("当前日期小于设定时间就不获取排班,当前时间:{},设定时间:{}", simpleDateFormat.format(date1), simpleDateFormat.format(date2));
                return;
            }
        }
        //查询当天是否保存过考情表  如果不存在则保存
        Map<String, List<DriverScheduling>> dto = nowSchedulingCache.getCacheScheduling(ConstDateUtil.formatDate(new Date()));
        if (!CollectionUtil.isEmpty(dto) || originSchedulingMap.size() == 0) {
            log.info("已有数据,当天排班数据长度:{}", originSchedulingMap.size());
            return;
        }
        // TODO maybe delete
        TempCache.resetMapStatus();
        List<DriverScheduling> bcList = getBcList(originSchedulingMap);

        // 处理非司售人员的排班明细
        bcList.addAll(handleOtherPostsScheduling());
        // 插入排班
        schedulingMapper.insertRoster(bcList);
        // 异常数据过多,不通过自增获取id再次查询获取
        bcList = schedulingMapper.queryToDay(ConstDateUtil.formatDate("yyyy-MM-dd"), null, null, null);
        // 处理缓存和错误排班
        String date = ConstDateUtil.formatDate(new Date());
        if (!CollectionUtil.isEmpty(bcList)) {
            Map<String, List<DriverScheduling>> resultMap = new HashMap<>(800);
            NowSchedulingCache.handlerResultMap(resultMap, bcList);
            // 更新缓存
            nowSchedulingCache.setCacheScheduling(date, resultMap);
            // 获取错误排班
            List<ErrorJobcode> errorScheduling = getErrorScheduling(resultMap);
            // 插入错误排班
            errorJobcodeService.insertBatchErrorJobcode(errorScheduling);
        }
    }

    private List<DriverScheduling> handleOtherPostsScheduling() {
        QueryWrapper<RuleAttendanceMain> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(RuleAttendanceMain::getWorkFlag, WORK_FLAG)
                .eq(RuleAttendanceMain::getSchedulingDate, LocalDate.now());
        List<RuleAttendanceMain> mainList = attendanceMainService.list(qw);
        List<DriverScheduling> bcList = new ArrayList<>(mainList.size() * 2);
        for (RuleAttendanceMain ruleAttendanceMain : mainList) {
            // 第一段
            DriverScheduling scheduling = getDriverScheduling(ruleAttendanceMain);
            scheduling.setFcsjT(ruleAttendanceMain.getFirstWorkSignInTime().getTime());
            scheduling.setBcType(BC_TYPE_OUT);
            scheduling.setZdsjT(ruleAttendanceMain.getFirstWorkSignInTime().getTime());
            scheduling.setScheduleDate(ruleAttendanceMain.getSchedulingDate());
            bcList.add(scheduling);

            DriverScheduling scheduling1 = getDriverScheduling(ruleAttendanceMain);
            scheduling1.setBcType(BC_TYPE_IN);
            scheduling1.setZdsjT(ruleAttendanceMain.getFirstQuittingSignInTime().getTime());
            scheduling1.setFcsjT(ruleAttendanceMain.getFirstQuittingSignInTime().getTime());
            scheduling1.setScheduleDate(ruleAttendanceMain.getSchedulingDate());
            bcList.add(scheduling1);
            // 第二段
            if (!Objects.isNull(ruleAttendanceMain.getSecondWorkSignInTime())) {
                DriverScheduling scheduling2 = getDriverScheduling(ruleAttendanceMain);
                scheduling2.setBcType(BC_TYPE_OUT);
                scheduling2.setFcsjT(ruleAttendanceMain.getSecondWorkSignInTime().getTime());
                scheduling2.setZdsjT(ruleAttendanceMain.getSecondWorkSignInTime().getTime());
                scheduling2.setScheduleDate(ruleAttendanceMain.getSchedulingDate());
                bcList.add(scheduling2);

                DriverScheduling scheduling3 = getDriverScheduling(ruleAttendanceMain);
                scheduling3.setBcType(BC_TYPE_IN);
                scheduling3.setFcsjT(ruleAttendanceMain.getSecondQuittingSignInTime().getTime());
                scheduling3.setZdsjT(ruleAttendanceMain.getSecondQuittingSignInTime().getTime());
                scheduling3.setScheduleDate(ruleAttendanceMain.getSchedulingDate());
                bcList.add(scheduling3);
            }
        }
        // 测试用例
//        bcList.add(getDriverSchedulingTest("2023-09-26 03:20:00","2023-09-26 09:30:00","out"));
//        bcList.add(getDriverSchedulingTest("2023-09-26 03:20:00","2023-09-26 09:30:00","in"));
        return bcList;
    }

    private DriverScheduling getDriverSchedulingTest(String startTime, String endTime, String bcType) {
        DriverScheduling scheduling = new DriverScheduling();
        scheduling.setJobCode("700001");
        scheduling.setName("测试");
        scheduling.setPosts("测试");
        scheduling.setScheduleDate(new Date());
        scheduling.setLineName("");
        scheduling.setLpName("");
        scheduling.setNbbm("");
        scheduling.setFcsjT(ConstDateUtil.parseDate(startTime).getTime());
        scheduling.setZdsjT(ConstDateUtil.parseDate(endTime).getTime());
        scheduling.setFleetName("");
        scheduling.setBcType(bcType);
        return scheduling;
    }

    private static DriverScheduling getDriverScheduling(RuleAttendanceMain ruleAttendanceMain) {
        DriverScheduling scheduling = new DriverScheduling();
        scheduling.setPosts(ruleAttendanceMain.getPosts());
        scheduling.setJobCode(ruleAttendanceMain.getJobCode());
        scheduling.setName(ruleAttendanceMain.getName());
        scheduling.setFleetName(ruleAttendanceMain.getFleetName());
        return scheduling;
    }

    private List<DriverScheduling> getBcList(Map<String, List<ResponseSchedulingDto>> originSchedulingMap) {
        List<DriverScheduling> bcList = new ArrayList<>(1000);
        Map<String, LineConfig> configMap = lineConfigService.selectLineConfigList(null).stream().collect(Collectors.toMap(item -> item.getLineName() + item.getLpName(), item -> item));
        for (String key : originSchedulingMap.keySet()) {
            List<ResponseSchedulingDto> schedulingList = originSchedulingMap.get(key);
            List<DriverScheduling> nowScheduling = schedulingList.stream()
                    .filter(item -> BC_TYPE_IN.equals(item.getBcType()) || BC_TYPE_OUT.equals(item.getBcType()))
                    .map(item -> {
                        DriverScheduling scheduling = new DriverScheduling();
                        BeanUtils.copyProperties(item, scheduling, "id");
                        return scheduling;
                    })
                    .sorted(Comparator.comparing(DriverScheduling::getFcsjT))
                    .collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(nowScheduling)) {
                // 配置处理
                nowScheduling = handlerScheduler(configMap, schedulingList, nowScheduling);
                //  ------|特殊处理|------
                try {
                    DriverScheduling scheduling = nowScheduling.get(nowScheduling.size() - 1);
                    scheduling.setZdsjT(scheduling.getFcsjT());
                } catch (Exception e) {
                    log.error("特殊处理失败:{}", e.getMessage());
                }
                // 处理青蒸线区间 区间删除注意特殊情况放到最后可能没有全部都是区间倒是nowScheduling 为0 然后get报错
                if (nowScheduling.get(0).getLineName().startsWith("青蒸线")) {
                    nowScheduling = handleQinZhengLine(nowScheduling);
                }
                //  ------|结束处理|------
                bcList.addAll(nowScheduling);
            } else {
                // 处理无进出场
                log.error("无进出场驾驶员工号:{}", schedulingList.get(0).getJobCode());
            }
        }
        return bcList;
    }

    /**
     * 处理特殊班次  TODO 获取配置表修改
     *
     * @param configMap
     * @param schedulingList
     * @param nowScheduling
     * @return
     */
    private List<DriverScheduling> handlerScheduler(Map<String, LineConfig> configMap, List<ResponseSchedulingDto> schedulingList, List<DriverScheduling> nowScheduling) {
        // 处理错误班次
        if (nowScheduling.size() % 2 == 1 && nowScheduling.size() > 2) {
            nowScheduling = handleErrorBc(schedulingList);
        }

        // TODO 遍历配置表数据
        updateSchedulerByConfig(nowScheduling, configMap);


        // 处理松青线
        // 松1路牌 签到时间 07:20 |松2路牌 签到时间 07:40 |松3路牌 签到时间 08:35 |松4路牌 签到时间 10:30
//        if (nowScheduling.get(0).getLineName().equals("松青线") && checkLpName(nowScheduling.get(0))) {
//            updateScheduling(nowScheduling);
//        }
        if (nowScheduling.get(0).getLineName().equals("虹桥枢纽6路") && nowScheduling.get(0).getLpName().equals("9") && nowScheduling.size() == 5) {
            nowScheduling.remove(3);
        }
        // 处理青浦20路 2号路牌 签到时间调整为07:20  | 5号路牌 签到时间调整为07:05
        if (nowScheduling.get(0).getLineName().equals("青浦20路")) {
            updateQinpu2With5(nowScheduling);
        }
        return nowScheduling;
    }

    private void updateSchedulerByConfig(List<DriverScheduling> nowScheduling, Map<String, LineConfig> configMap) {
        try {
            String key = nowScheduling.get(0).getLineName() + nowScheduling.get(0).getLpName();
            // TODO 判断是否存在配置
            LineConfig config = configMap.get(key);
            if (!Objects.isNull(config)) {
                // TODO 判断是否分班
                // TODO 判断是否隔天
                // TODO 判断排班是否正常
                // TODO 获取配置修改排班
                if (config.getSecondFlag().equals(NO_SEGMENTATION) && nowScheduling.size() == 2) {
                    handlerFirstSignConfig(config, nowScheduling);
                }
                // 分段
                else if (config.getSecondFlag().equals(HAVE_SEGMENTATION) && nowScheduling.size() == 4) {
                    handlerFirstSignConfig(config, nowScheduling);
                    handlerSecondSignConfig(config, nowScheduling);
                }
            }
        } catch (Exception e) {
            log.error("配置修改失败,原因为:" + e.getMessage());
            log.error("排班数据为:{}", nowScheduling);
        }
    }

    private void handlerSecondSignConfig(LineConfig config, List<DriverScheduling> nowScheduling) {
        LocalDate localDate1 = LocalDate.now();
        LocalDate localDate2 = config.getSecondSignTodayTomorrow().equals(TOMORROW_YES) ? LocalDate.now().plusDays(1) : LocalDate.now();

        Date date1 = ConstDateUtil.parseDate(localDate1 + " " + config.getSecondSignInTime() + ":00");
        Date date2 = ConstDateUtil.parseDate(localDate2 + " " + config.getSecondSignOutTime() + ":00");
        nowScheduling.get(2).setFcsjT(date1.getTime());
        nowScheduling.get(2).setZdsjT(date1.getTime());
        nowScheduling.get(3).setFcsjT(date2.getTime());
        nowScheduling.get(3).setZdsjT(date2.getTime());
    }

    private void handlerFirstSignConfig(LineConfig config, List<DriverScheduling> nowScheduling) {
        LocalDate localDate1 = LocalDate.now();
        LocalDate localDate2 = config.getFirstSignTodayTomorrow().equals(TOMORROW_YES) ? LocalDate.now().plusDays(1) : LocalDate.now();
        Date date1 = ConstDateUtil.parseDate(localDate1 + " " + config.getFirstSignInTime() + ":00");
        Date date2 = ConstDateUtil.parseDate(localDate2 + " " + config.getFirstSignOutTime() + ":00");
        nowScheduling.get(0).setFcsjT(date1.getTime());
        nowScheduling.get(0).setZdsjT(date1.getTime());
        nowScheduling.get(1).setFcsjT(date2.getTime());
        nowScheduling.get(1).setZdsjT(date2.getTime());
    }

    private void updateQinpu2With5(List<DriverScheduling> nowScheduling) {
        if ("2".equals(nowScheduling.get(0).getLpName())) {
            nowScheduling.get(0).setFcsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(0).getFcsjT())), "07:20:00").getTime());
        }
        if ("5".equals(nowScheduling.get(0).getLpName())) {
            nowScheduling.get(0).setFcsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(0).getFcsjT())), "07:05:00").getTime());
        }
    }

    private List<DriverScheduling> handleQinZhengLine(List<DriverScheduling> nowScheduling) {
        return nowScheduling.stream().filter(item -> !item.getLineName().contains("区间")).collect(Collectors.toList());
    }

    private void updateScheduling(List<DriverScheduling> nowScheduling) {
        switch (nowScheduling.get(0).getLpName()) {
            case "松1":
                nowScheduling.get(0).setFcsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(0).getFcsjT())), "07:20:00").getTime());
                nowScheduling.get(nowScheduling.size() - 1).setZdsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(nowScheduling.size() - 1).getFcsjT())), "15:30:00").getTime());
                break;
            case "松2":
                nowScheduling.get(0).setFcsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(0).getFcsjT())), "07:40:00").getTime());
                nowScheduling.get(nowScheduling.size() - 1).setZdsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(nowScheduling.size() - 1).getFcsjT())), "19:00:00").getTime());
                break;
            case "松3":
                nowScheduling.get(0).setFcsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(0).getFcsjT())), "08:35:00").getTime());
                nowScheduling.get(nowScheduling.size() - 1).setZdsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(nowScheduling.size() - 1).getFcsjT())), "18:10:00").getTime());
                break;
            case "松4":
                nowScheduling.get(0).setFcsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(0).getFcsjT())), "10:30:00").getTime());
                nowScheduling.get(nowScheduling.size() - 1).setZdsjT(ConstDateUtil.dateAddition(ConstDateUtil.formatDate("yyyy-MM-dd", new Date(nowScheduling.get(nowScheduling.size() - 1).getFcsjT())), "18:35:00").getTime());
                break;
        }
    }

    private boolean checkLpName(DriverScheduling driverScheduling) {
        switch (driverScheduling.getLpName()) {
            case "松1":
            case "松2":
            case "松3":
            case "松4":
                return true;
            default:
                return false;
        }
    }

    public static List<ErrorJobcode> getErrorScheduling(Map<String, List<DriverScheduling>> resultMap) {
        List<ErrorJobcode> errorList = new ArrayList<>();
        // 循环处理
        for (String key : resultMap.keySet()) {
            List<DriverScheduling> schedulingList = resultMap.get(key);
            schedulingList.sort(Comparator.comparing(DriverScheduling::getFcsjT));
            // 处理单进|出场
            if (resultMap.get(key).size() == 1) {
                errorList.add(handlerSingleBc(schedulingList));
            } else {
                // 处理进出场不匹配
                ErrorJobcode errorJobcode = handlerBcNoMatch(schedulingList);
                if (errorJobcode != null) errorList.add(errorJobcode);
            }
        }
        return errorList;
    }

    public static ErrorJobcode handlerBcNoMatch(List<DriverScheduling> driverSchedulingList) {

        ErrorJobcode er = new ErrorJobcode();
        BeanUtils.copyProperties(driverSchedulingList.get(0), er);
        er.setCreateTime(driverSchedulingList.get(0).getScheduleDate());
        // 出场次数
        int bcOutCount = 0;
        // 进场次数
        int bcInCount = 0;
        // 连续进场场次
        boolean inContinuousFlag = false;
        // 连续出场场次
        boolean outContinuousFlag = false;
        int length = driverSchedulingList.size();
        for (int i = 0; i < length; i++) {
            // 当前位置+1 当前与后面的一位元素比较是否一致
            if (i < length - 1) {
                // 判断是否出现连续
                if (driverSchedulingList.get(i).getBcType().equals(driverSchedulingList.get(i + 1).getBcType())) {
                    if (BC_TYPE_IN.equals(driverSchedulingList.get(i).getBcType())) inContinuousFlag = true;
                    else outContinuousFlag = true;
                }
            }
            if (BC_TYPE_IN.equals(driverSchedulingList.get(i).getBcType())) bcInCount++;
            else bcOutCount++;
        }
        if (inContinuousFlag || outContinuousFlag) {
            er.setRemark(inContinuousFlag ? "连续进场" : "连续出场");
            return er;
        }
        // 匹配进出场顺序
        if (bcOutCount != bcInCount) {
            er.setRemark(bcOutCount > bcInCount ? "出场次数与进场次数不匹配,多于进场" : "进场次数与进场次数不匹配,多于出场");
            return er;
        }

        return null;

    }

    public static ErrorJobcode handlerSingleBc(List<DriverScheduling> driverSchedulingList) {
        ErrorJobcode errorJobcode = new ErrorJobcode();
        BeanUtils.copyProperties(driverSchedulingList.get(0), errorJobcode);
        errorJobcode.setCreateTime(driverSchedulingList.get(0).getScheduleDate());
        errorJobcode.setRemark(BC_TYPE_IN.equals(driverSchedulingList.get(0).getBcType()) ? "单个场次,没有出场" : "单个场次,没有进场");
        return errorJobcode;
    }

    private List<DriverScheduling> handleErrorBc(List<ResponseSchedulingDto> nowScheduling) {
        // 处理两个进场
        return handlerTowIn(nowScheduling);
    }

    private List<DriverScheduling> handlerTowIn(List<ResponseSchedulingDto> nowScheduling) {
        nowScheduling = nowScheduling.stream().filter(item -> BC_TYPE_IN.equals(item.getBcType()) || BC_TYPE_OUT.equals(item.getBcType())).collect(Collectors.toList());
        if (nowScheduling.get(nowScheduling.size() - 1).getBcType().equals(BC_TYPE_IN)) {
            // 连续的进场 判断哪个适配
            ResponseSchedulingDto scheduling1 = nowScheduling.get(nowScheduling.size() - 1);
            ResponseSchedulingDto scheduling2 = nowScheduling.get(nowScheduling.size() - 2);
            // 判断后移除
            if ("秀沁路汽车站".equals(scheduling1.getZdzName())) {
                nowScheduling.remove(nowScheduling.size() - 2);
            }
            if ("秀沁路汽车站".equals(scheduling2.getZdzName())) {
                nowScheduling.remove(nowScheduling.size() - 1);
            }
        }

        return nowScheduling.stream().map(item -> {
            DriverScheduling scheduling = new DriverScheduling();
            BeanUtils.copyProperties(item, scheduling);
            return scheduling;
        }).collect(Collectors.toList());
    }

    @Async
    public void asyncInsertEquipmentLog(List<Equipment> list, List<Equipment> original) {
        // 插入离线日志
        List<Equipment> offline = handleOffLine(list);
        if (CollectionUtil.isNotEmpty(offline)) {
            equipmentMapper.insertEquipmentOffLineLog(offline);
        }

        // 更新恢复日志
        List<EquipmentLog> recoveryList = handlerEquipmentRecovery(list, original);
        if (CollectionUtil.isNotEmpty(recoveryList)) {
            equipmentMapper.updateEquipmentLog(recoveryList);
        }
    }

    private List<Equipment> handleOffLine(List<Equipment> list) {
        return list.stream().filter(item -> "脱机".equals(item.getOnlineClient())).collect(Collectors.toList());
    }

    private List<EquipmentLog> handlerEquipmentRecovery(List<Equipment> list, List<Equipment> original) {
        if (CollectionUtil.isEmpty(original)) {
            return new ArrayList<>();
        }
        List<EquipmentLog> recoveryList = new ArrayList<>(12);
        Map<String, Equipment> originalMap = original.stream().collect(Collectors.toMap(Equipment::getDeviceId, equipment -> equipment));
        for (Equipment nowItem : list) {
            Equipment eqOr = originalMap.get(nowItem.getDeviceId());
            if (!nowItem.getOnlineClient().equals(eqOr.getOnlineClient()) && DEVICE_OFFLINE.equals(eqOr.getOnlineClient())) {
                EquipmentLog eqLog = new EquipmentLog();
                eqLog.setRecoveryFlag(DEVICE_ONLINE_NUM);
                eqLog.setRecoveryTime(nowItem.getLastHeartRes());
                eqLog.setDeviceId(eqOr.getDeviceId());
                recoveryList.add(eqLog);
            }
        }
        return recoveryList;
    }


}