ThreadJobService.java 53.7 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 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
package com.ruoyi.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
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.DriverScheduling;
import com.ruoyi.domain.RuleAttendanceMain;
import com.ruoyi.domain.driver.NewDriver;
import com.ruoyi.domain.scheduling.LinggangScheduling;
import com.ruoyi.domain.sign.in.exception.report.EquipmentExceptionReport;
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.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.in.domain.SignIn;
import com.ruoyi.job.DriverJob;
import com.ruoyi.pojo.GlobalIndex;
import com.ruoyi.pojo.response.ResponseSchedulingDto;
import com.ruoyi.service.carinfo.LingangCarInfoService;
import com.ruoyi.service.driver.NewDriverService;
import com.ruoyi.service.key.location.LinggangKeyWorkLocationService;
import com.ruoyi.service.scheduling.LinggangSchedulingService;
import com.ruoyi.service.sign.in.exception.report.EquipmentExceptionReportService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.utils.ConstDateUtil;
import com.ruoyi.utils.DateUtil;
import com.ruoyi.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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.support.DefaultTransactionDefinition;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
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 LinggangSchedulingService schedulingService;


    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private EquipmentExceptionMapper exceptionMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private EquipmentExceptionReportService equipmentExceptionReportService;

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

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LinggangKeyWorkLocationService keyWorkLocationService;
    @Autowired
    private LinggangSchedulingService linggangSchedulingService;
    @Autowired
    private NewDriverService newDriverService;
    @Autowired
    private LingangCarInfoService lingangCarInfoService;

    @Value("${bsth.process.sign.url}")
    private String processSignExceptionURL;
    @Value("${bsth.audit-jobs}")
    private String auditJobs;


    /**
     * 异步上传图片
     *
     * @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, DriverScheduling scheduling) {
        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());
            exception.setSignId(signIn.getId());
            exception.setCreateTime(signIn.getCreateTime());
            exception.setCreateBy(signIn.getCreateBy());
            if (Objects.nonNull(scheduling)) {
                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);

            EquipmentExceptionReport exceptionReport = new EquipmentExceptionReport();
            BeanUtils.copyProperties(exception, exceptionReport);
            exceptionReport.setSignId(signIn.getId());
            exceptionReport.setSignIn(signIn.getSingnIn());
            exceptionReport.setStatus(1);
            equipmentExceptionReportService.save(exceptionReport);

            if (Objects.isNull(signIn.getExceptionId())) {
                // 发送通知
                sendNotice(signIn, driver, scheduling);
            }
        }
    }

    @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());
            exception.setSignId(signIn.getId());
            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);


            EquipmentExceptionReport exceptionReport = new EquipmentExceptionReport();
            BeanUtils.copyProperties(exception, exceptionReport);
            exceptionReport.setSignId(signIn.getId());
            equipmentExceptionReportService.save(exceptionReport);
        }
    }

    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 void sendNotice(SignIn signIn, Driver driver, DriverScheduling item) {
        if (SIGN_ALCOHOL_EX_NUM.equals(signIn.getExType())) {
            SysNotice notice = new SysNotice();
            notice.setCreateBy("system");
            notice.setUpdateBy("system");
            notice.setNoticeTitle("酒精测试异常通知");

            if (Objects.isNull(item)) {
                item = new DriverScheduling();
                handlerNoScheduling(item, signIn, driver);
            }
            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);
        }

        sendNoice(signIn, driver, item);
    }

    private void sendNoice(SignIn signIn, Driver driver, DriverScheduling item) {
        if (SIGN_ALCOHOL_EX_NUM.equals(signIn.getExType())) {
            LinggangScheduling linggangScheduling = new LinggangScheduling();
            linggangScheduling.setQdzcode(item.getQdzCode());
            linggangScheduling.setBcType("out");
            linggangScheduling.setStartScheduleDate(DateUtils.addDays(signIn.getCreateTime(), -1));
            linggangScheduling.setEndScheduleDate(DateUtils.addDays(signIn.getCreateTime(), 1));
            linggangScheduling.setSchedulingType(1);
            List<LinggangScheduling> linggangSchedulings = linggangSchedulingService.list(linggangScheduling);

            Set<String> qdznames = new HashSet<>();

            List<NewDriver> newDrivers = null;
            if (CollectionUtils.isNotEmpty(linggangSchedulings)) {
                qdznames = linggangSchedulings.stream().map(LinggangScheduling::getQdzname).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).collect(Collectors.toSet());

                newDrivers = newDriverService.listByQdzName(qdznames);
            }

            if (StringUtils.isNotEmpty(auditJobs)) {
                String[] jobCodes1 = auditJobs.split(";");
                Set<String> jobCodes = new HashSet<>();
                for (String code : jobCodes1) {
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(code)) {
                        jobCodes.add(code);
                    }
                }
                if (CollectionUtils.isNotEmpty(jobCodes)) {
                    NewDriver newDriver = new NewDriver();
                    newDriver.setJobCodes(jobCodes);
                    List<NewDriver> newDrivers1 = newDriverService.list(qdznames);
                    if (Objects.isNull(newDrivers) && CollectionUtils.isNotEmpty(newDrivers1)) {
                        newDrivers = newDrivers1;
                    } else if (CollectionUtils.isNotEmpty(newDrivers) && CollectionUtils.isNotEmpty(newDrivers1)) {
                        newDrivers.addAll(newDrivers1);
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(newDrivers)) {
                for (NewDriver newDriver : newDrivers) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("noticeIssuer", "运控中心");
                    map.put("noticeRecipient", "05-" + newDriver.getJobCode());
                    map.put("noticeTitle", "异常通知");
                    map.put("noticeSubtitle", "");

                    StringBuilder builder = new StringBuilder();
                    builder
                            .append("工号:").append(item.getJobCode()).append(",姓名:").append(item.getName()).append(",工种:")
                            .append(item.getPosts()).append(",排班:")
                            .append((Objects.isNull(item.getScheduleDate()) ? "无排班" : "有排班")).append(",打卡时间:")
                            .append(ConstDateUtil.formatDate("yyyy-MM-dd HH:mm:ss", signIn.getCreateTime()))
                            .append(",酒精测试超标,当前测试值达到").append(signIn.getAlcoholIntake()).append("mg/100ml。属于").append(getResultString(signIn.getAlcoholIntake()));

                    map.put("noticeContent", builder.toString());
                    map.put("phone", newDriver.getTelphone());
                    map.put("smscontent", builder.toString());
                    map.put("noticeType", "岗前检查");
                    map.put("remark", "schedulingId=" + item.getId() + "&signId=" + signIn.getId());
                    map.put("signId", signIn.getId());
                    map.put("associatedId", item.getId());

                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("schedulingId", item.getId());
                    map.put("params", paramMap);

                    String key = SignatureUtils.generateSignature(map, "your_secret_key_here");
                    map.put("signature", key);
                    String result = null;
                    try {
                        result = HttpUtil.get(processSignExceptionURL, map, 10000);
                        log.info("processSignExceptionURL:[{}],paramMap:[{}],result:[{}]", processSignExceptionURL, JSONUtil.toJsonStr(map), result);
                    } catch (Exception e) {
                        log.error("processSignExceptionURL:[{}],paramMap:[{}],result:[{}]", processSignExceptionURL, JSONUtil.toJsonStr(map), result, e);
                    }

                }

            }
        }
    }

    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());
        }

    }

    /**
     * 异步发送邮件
     *
     * @param scheduling
     * @param signIn
     * @param driver
     */
    @Async
    public void asyncSendEmail(DriverScheduling scheduling, SignIn signIn, Driver driver) {
        DriverScheduling item = null;
        if (Objects.isNull(scheduling)) {
            item = new DriverScheduling();
            handlerNoScheduling(item, signIn, driver);
            // 无排班
            emailService.sendWarningEmail(item, signIn.getCreateTime(), signIn.getAlcoholIntake());
        } else {
            // 有排班
            emailService.sendWarningEmail(scheduling, 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
    public synchronized void asyncComputedScheduling(Map<String, List<ResponseSchedulingDto>> originSchedulingMap, String timeOut, Date date, int type, Set<Long> idSets, String requestId) {
        JwtAuthenticationTokenFilter.putMDC("job", requestId);
//        //查询当天是否保存过考情表  如果不存在则保存
//        List<DriverScheduling> bcList = schedulingMapper.queryToDay(DateUtil.YYYY_MM_DD_LINK.format(date), DateUtil.YYYY_MM_DD_LINK.format(org.apache.commons.lang3.time.DateUtils.addDays(date, 1)), null, null, null);
//        Map<String, List<DriverScheduling>> dto = nowSchedulingCache.getCacheScheduling(ConstDateUtil.formatDate(date));
//        if (CollectionUtils.isNotEmpty(bcList) && MapUtils.isEmpty(dto) && Objects.equals(1, type)) {
//            String dateStr = DateUtil.YYYY_MM_DD.format(date);
//            Map<String, List<DriverScheduling>> resultMap = new HashMap<>(800);
//            NowSchedulingCache.handlerResultMap(resultMap, bcList);
//            // 更新缓存
//            nowSchedulingCache.setCacheScheduling(dateStr, resultMap);
//        }

//        // 当天已有记录则不在保存  或者 调度记录为空则不在保存
//        if ((CollectionUtil.isNotEmpty(dto) && CollectionUtil.isNotEmpty(bcList)) || originSchedulingMap.size() == 0) {
//            log.info("调度最新数据:{},当天获取数据:{},时间:[{}]", originSchedulingMap.size(), bcList.size(), date);
//            return;
//        }

        if (Objects.equals(1, type)) {
            TempCache.resetMapStatus();
        }
        List<DriverScheduling> bcList = getBcList(originSchedulingMap, type);

        lingangCarInfoService.insert(bcList);

        // 处理非司售人员的排班明细
        bcList.addAll(handleOtherPostsScheduling(type));
        // 插入排班
        List<LinggangScheduling> schedulings = bcList.stream().map(b -> {
            LinggangScheduling scheduling = new LinggangScheduling();
            scheduling.setJobCode(b.getJobCode());
            scheduling.setName(b.getName());
            scheduling.setPosts(b.getPosts());
            scheduling.setScheduleDate(b.getScheduleDate());
            scheduling.setLineName(b.getLineName());
            scheduling.setLpName(b.getLpName());
            scheduling.setNbbm(b.getNbbm());
            scheduling.setBcType(b.getBcType());
            scheduling.setFcsjT(b.getFcsjT());
            scheduling.setZdsjT(b.getZdsjT());
            scheduling.setSignInId(b.getSignInId());
            scheduling.setExType(b.getExType());
            scheduling.setSignType(b.getSignType());
            scheduling.setSignTime(b.getSignTime());
            scheduling.setAlcoholFlag(b.getAlcoholFlag());
            scheduling.setAlcoholIntake(b.getAlcoholIntake());
            scheduling.setRemark(b.getRemark());

            scheduling.setUpdown(b.getUpDown());
            scheduling.setQdzcode(b.getQdzCode());
            scheduling.setQdzname(b.getQdzName());
            scheduling.setZdzcode(b.getZdzCode());
            scheduling.setZdzname(b.getZdzName());
            scheduling.setType(b.getType());

            return scheduling;
        }).filter(s -> !StringUtils.isBlank(s.getJobCode()) && !StringUtils.isBlank(s.getName()) && !StringUtils.equalsAnyIgnoreCase(s.getJobCode(), "null")
                && !StringUtils.equalsAnyIgnoreCase(s.getName(), "null")).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(schedulings)) {
            Map<String, List<LinggangScheduling>> distinctMap = new HashMap<>();
            schedulings.stream().forEach(s -> {
                String key = org.apache.commons.lang3.StringUtils.join(s.getJobCode(), "-", s.getBcType(), "-", s.getFcsjT(), "-", s.getScheduleDate());
                List<LinggangScheduling> linggangSchedulings = distinctMap.get(key);
                if (Objects.isNull(linggangSchedulings)) {
                    linggangSchedulings = new ArrayList<>();
                    distinctMap.put(key, linggangSchedulings);
                }
                linggangSchedulings.add(s);
            });

            schedulings.clear();
            for (Map.Entry<String, List<LinggangScheduling>> entry : distinctMap.entrySet()) {
                int size = CollectionUtils.size(entry.getValue());
                if (size == 1) {
                    schedulings.add(entry.getValue().get(0));
                } else if (size > 1) {
                    List<LinggangScheduling> values = entry.getValue().stream().filter(s -> !Objects.equals(s.getZdsjT(), s.getFcsjT())).collect(Collectors.toList());
                    size = CollectionUtils.size(values);
                    if (size == 0) {
                        schedulings.add(entry.getValue().get(0));
                    } else if (size == 1) {
                        schedulings.add(values.get(0));
                    } else {
                        values = values.stream().sorted(Comparator.comparing(LinggangScheduling::getZdsjT)).collect(Collectors.toList());
                        schedulings.add(values.get(size - 1));
                    }
                }
            }

            LinggangScheduling scheduling = new LinggangScheduling();
            scheduling.setStartScheduleDate(DateUtil.shortDate(date));
            scheduling.setEndScheduleDate(org.apache.commons.lang3.time.DateUtils.addDays(scheduling.getStartScheduleDate(), 1));

            scheduling.setType(type);

            List<LinggangScheduling> sourceList = schedulingService.list(scheduling);
            if (CollectionUtils.isNotEmpty(sourceList)) {

                List<LinggangScheduling> schedulings1 = schedulings;
                List<LinggangScheduling> removeSchedulings = sourceList.stream().filter(s -> {
                    Optional<LinggangScheduling> opt = schedulings1.stream().filter(s1 -> s1.importEqus(s) && Objects.isNull(s1.getSignInId())).findFirst();
                    if (!opt.isPresent()) {
                        log.debug("需要删除的排班数据:[{}]", s);
                    }
                    return !opt.isPresent() && Objects.isNull(s.getSignInId());
                }).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(removeSchedulings)) {
                    Set<Long> ids = removeSchedulings.stream().map(LinggangScheduling::getId).collect(Collectors.toSet());
                    schedulingService.removeByIds(ids);
                    schedulings = schedulings1.stream().filter(s -> {
                        Optional<LinggangScheduling> opt = removeSchedulings.stream().filter(s1 -> s1.importEqus(s)).findFirst();
                        return !opt.isPresent();
                    }).collect(Collectors.toList());
                }

                schedulings = schedulings.stream().filter(s -> {
                    Optional<LinggangScheduling> opt = sourceList.stream().filter(s1 -> s1.importEqus(s)).findFirst();
                    if (opt.isPresent()) {
                        log.debug("排班数据已经存在:[{}]", s);
                    }
                    return !opt.isPresent();
                }).filter(s -> Objects.nonNull(s)).collect(Collectors.toList());
            }

            if (CollectionUtils.isNotEmpty(schedulings)) {
                List<LinggangScheduling> schedulings1 = schedulings.stream().filter(s -> StringUtils.isBlank(s.getJobCode()) || StringUtils.isBlank(s.getName())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(schedulings1)) {
                    System.out.println("bbbbbbbbbbb");
                }
                for (LinggangScheduling linggangScheduling : schedulings) {
                    schedulingService.save(linggangScheduling);
                }

            }
        }
        String dateStr1 = DateUtil.YYYY_MM_DD_LINK.format(date);
        // 异常数据过多,不通过自增获取id再次查询获取
        bcList = schedulingMapper.queryToDay(dateStr1, DateUtil.YYYY_MM_DD_LINK.format(org.apache.commons.lang3.time.DateUtils.addDays(date, 1)), null, null, null);
        // 处理缓存和错误排班
        String dateStr = DateUtil.YYYY_MM_DD.format(date);
        if (!CollectionUtil.isEmpty(bcList) && Objects.equals(1, type)) {
            Map<String, List<DriverScheduling>> resultMap = new HashMap<>(800);
            NowSchedulingCache.handlerResultMap(resultMap, bcList);
            // 更新缓存
            nowSchedulingCache.setCacheScheduling(dateStr, resultMap);
            // 获取错误排班
            List<ErrorJobcode> errorScheduling = getErrorScheduling(resultMap);
            // 插入错误排班
            errorJobcodeService.insertBatchErrorJobcode(errorScheduling);
        }
        if (CollectionUtils.isNotEmpty(idSets)) {
            keyWorkLocationService.removeBySchedulingId(idSets);
            schedulingService.removeByIds(idSets);
        }

        LinggangScheduling linggangScheduling = new LinggangScheduling();
        linggangScheduling.setStartScheduleDate(date);
        linggangScheduling.setEndScheduleDate(org.apache.commons.lang3.time.DateUtils.addDays(date, 1));


        if (CollectionUtils.isNotEmpty(schedulings)) {
            keyWorkLocationService.insertJob(dateStr1, schedulings, null);
        }
        log.info("当天排班数据获取完毕,共:{}条", bcList.size());

        log.info("排班信息同步完毕");
    }

    private <T> String combitionKey(T s1) {
        LinggangScheduling s = (LinggangScheduling) s1;
        return (s.getScheduleDate() + "-" + s.getBcType() + "-" + s.getFcsjT() + "-" + s.getScheduleDate());
    }

    private List<DriverScheduling> handleOtherPostsScheduling(int type) {
        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());
            scheduling.setType(type);
            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());
            scheduling1.setType(type);
            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());
                scheduling2.setType(type);
                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());
                scheduling3.setType(type);
                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, int type) {
        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");
                        scheduling.setUpDown(Convert.toInt(item.getUpDown()));
                        scheduling.setType(type);
                        if (Objects.isNull(scheduling.getFcsjT()) || Objects.equals(0L, scheduling.getFcsjT())) {
                            scheduling.setFcsjT(item.getfcsjTValue());
                        }

                        if (Objects.nonNull(scheduling.getZdsjT()) || Objects.equals(0L, scheduling.getZdsjT())) {
                            scheduling.setZdsjT(item.getzdsjTTValue());
                        }
                        return scheduling;
                    })
                    .sorted(Comparator.comparing(DriverScheduling::getFcsjT))
                    .collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(nowScheduling)) {
                // 配置处理
                nowScheduling = handlerScheduler(configMap, schedulingList, nowScheduling, type);
                //  ------|特殊处理|------
                try {
                    DriverScheduling scheduling = nowScheduling.get(nowScheduling.size() - 1);
                    scheduling.setZdsjT(scheduling.getFcsjT());
                } catch (Exception e) {
                    log.error("特殊处理失败:{}", e.getMessage());
                }
                // 处理青蒸线区间 区间删除注意特殊情况放到最后可能没有全部都是区间倒是nowScheduling 为0 然后get报错
                if (CollectionUtil.isNotEmpty(nowScheduling) && 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, int type) {
        // 处理错误班次
        if (nowScheduling.size() % 2 == 1 && nowScheduling.size() > 2) {
            nowScheduling = handleErrorBc(schedulingList, type);
        }

        // 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, int type) {
        // 处理两个进场
        return handlerTowIn(nowScheduling, type);
    }

    private List<DriverScheduling> handlerTowIn(List<ResponseSchedulingDto> nowScheduling, int type) {
        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);
            scheduling.setType(type);
            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;
    }


}