DriverServiceImpl.java 29.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
package com.ruoyi.driver.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.cache.NowSchedulingCache;
import com.ruoyi.common.cache.SchedulingCache;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.global.Result;
import com.ruoyi.common.global.ResultCode;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.domain.RuleAttendanceMain;
import com.ruoyi.equipment.mapper.EquipmentMapper;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.job.DriverJob;
import com.ruoyi.pojo.DriverSignInRecommendation;
import com.ruoyi.domain.EquipmentDriverExpand;
import com.ruoyi.domain.DriverScheduling;
import com.ruoyi.pojo.request.DriverRequestVo;
import com.ruoyi.pojo.request.DriverSignInRequestVo;
import com.ruoyi.pojo.request.FaceUpdateReqVo;
import com.ruoyi.pojo.response.DriverResponseVo;
import com.ruoyi.pojo.response.ResponseSchedulingDto;
import com.ruoyi.pojo.response.personnel.PersonnelResultResponseVo;
import com.ruoyi.pojo.response.personnel.TokenResponseVo;
import com.ruoyi.service.AttendanceService;
import com.ruoyi.service.RuleAttendanceMainService;
import com.ruoyi.service.SchedulingService;
import com.ruoyi.service.ThreadJobService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.utils.ConstDateUtil;
import com.ruoyi.utils.ListUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.driver.mapper.DriverMapper;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.service.IDriverService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.ApiProperties.PERSONNEL_API_KEY;
import static com.ruoyi.common.ConstDriverProperties.*;
import static com.ruoyi.common.ConstSignInConstSignInProperties.*;
import static com.ruoyi.common.RuleSchedulingProperties.WORK_FLAG;
import static com.ruoyi.common.redispre.GlobalRedisPreName.DRIVER_SCHEDULING_PRE;
import static com.ruoyi.common.redispre.GlobalRedisPreName.REDIS_SIGN_IN_DRIVER_ALCOHOL_OVERFLOW;

/**
 * 驾驶员信息Service业务层处理
 *
 * @author 古自健
 * @date 2023-07-04
 */
@Service
public class DriverServiceImpl implements IDriverService {

    private Logger log = LoggerFactory.getLogger(DriverServiceImpl.class);

    @Value("${api.personnel.token.tokenUrl}")
    private String tokenUrl;

    @Resource
    private NowSchedulingCache cache;

    @Autowired
    private SchedulingService schedulingService;

    @Autowired
    private ISysNoticeService noticeService;

    @Value("${api.url.getSchedulingInfo}")
    private String schedulingInfoUrl;
    @Value("${api.config.password}")
    private String password;
    @Value("${api.config.nonce}")
    private String nonce;
    @Resource
    private SchedulingCache schedulingCache;

    @Resource
    private NowSchedulingCache nowSchedulingCache;
    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private ThreadJobService threadJobService;

    @Autowired
    private RedisCache redisCache;

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

    @Autowired
    private RuleAttendanceMainService attendanceMainService;

    /**
     * 查询驾驶员信息
     *
     * @param id 驾驶员信息主键
     * @return 驾驶员信息
     */
    @Override
    public Driver selectDriverById(Long id) {
        return driverMapper.selectDriverById(id);
    }

    /**
     * 查询驾驶员信息列表
     *
     * @param driver 驾驶员信息
     * @return 驾驶员信息
     */
    @Override
    public List<Driver> selectDriverList(DriverRequestVo driver) {
        List<Driver> drivers = driverMapper.selectDriverList(driver);
        List<EquipmentDriverExpand> list = equipmentMapper.querySignListByJobCode(drivers);
        for (Driver item : drivers) {
            // 查询对应工号的注册设备号 然后用,拼接展示在前端
            List<String> collect = list.stream().filter(todo -> item.getJobCode().equals(todo.getJobCode())).map(EquipmentDriverExpand::getDeviceId).collect(Collectors.toList());
            item.setSignInEquipment(StringUtils.join(collect));
        }
        return drivers;
    }

    private DriverSignInRecommendation checkTime(List<DriverScheduling> dto, Long now) {
        Integer index = 0;
        Map<Integer, DriverSignInRecommendation> timeMap = new HashMap<>();
        index = handleSchedulingMap(dto, now, timeMap);

        LocalDateTime nowTime = ConstDateUtil.getLocalDateTimeByLongTime(now);
        LocalDateTime signTime = ConstDateUtil.getLocalDateTimeByLongTime(timeMap.get(index).getTimestamps());
        long range = ChronoUnit.MINUTES.between(signTime, nowTime);
        // 如果当前记录靠近签退,但是未到签退小于合法范围 上一次记录未签到,则返回签到记录
        if (dto.size() > 1
                && BC_TYPE_IN.equals(timeMap.get(index).getBcType())
                && range < -60L
                && Objects.isNull(timeMap.get(index).getSignInId())
                && Objects.isNull(timeMap.get(index - 1).getSignInId())) {
            // 定位上次操作
            index = index - 1;
        }

        // 如果当前记录是异常的记录且还在目前还在签到范围内
        if (!Objects.isNull(timeMap.get(index).getSignInId()) && dto.size() > 1) {
            LocalDateTime endTime = ConstDateUtil.getLocalDateTimeByLongTime(timeMap.get(index).getTimestamps());
            long nowBetween = ChronoUnit.MINUTES.between(endTime, nowTime);
            // 如果当前有效范围内签
            if ((Math.abs(nowBetween) <= 60)) {
                return timeMap.get(index);
            } else if (nowBetween > 60L) {
                index = index < timeMap.size() - 1 ? index + 1 : index;
            }
        }
        return timeMap.get(index);
    }

    private static Integer handleSchedulingMap(List<DriverScheduling> dto, Long now, Map<Integer, DriverSignInRecommendation> timeMap) {
        Integer index = 0;
        for (int i = 0; i < dto.size(); i++) {
            timeMap.put(i, new DriverSignInRecommendation(dto.get(i), i));
        }
        long minDiff = Long.MAX_VALUE;
        // 迭代比较每个时间戳与当前时间戳的差值
        for (Integer i : timeMap.keySet()) {
            long diff = Math.abs(now - timeMap.get(i).getTimestamps());
            if (diff < minDiff) {
                minDiff = diff;
                index = i;
            }
        }
        return index;
    }


    /**
     * 新增驾驶员信息
     *
     * @param driver 驾驶员信息
     * @return 结果
     */
    @Override
    public int insertDriver(Driver driver) {
        driver.setUpdateTime(new Date());
        return driverMapper.insertDriver(driver);
    }

    /**
     * 修改驾驶员信息
     *
     * @param driver 驾驶员信息
     * @return 结果
     */
    @Override
    public int updateDriver(Driver driver) {
        driver.setUpdateTime(new Date());
        // 修改排班表scheduling  以及缓存信息
        List<DriverScheduling> driverSchedulings = cache.getCacheScheduling(ConstDateUtil.getStringNowLocalDate("-")).get(driver.getJobCode());
        // 只改变车队信息 其他信息由调度接口 和 人事系统决定  本来是不修改的但是人事数据有问题
        for (DriverScheduling scheduling : driverSchedulings) {
            if (StringUtil.isNotEmpty(driver.getFleetName())) {
                scheduling.setFleetName(driver.getFleetName());
            }
        }
        return driverMapper.updateDriver(driver);
    }

    /**
     * 批量删除驾驶员信息
     *
     * @param ids 需要删除的驾驶员信息主键
     * @return 结果
     */
    @Override
    public int deleteDriverByIds(Long[] ids) {
        return driverMapper.deleteDriverByIds(ids);
    }

    /**
     * 删除驾驶员信息信息
     *
     * @param id 驾驶员信息主键
     * @return 结果
     */
    @Override
    public int deleteDriverById(Long id) {
        return driverMapper.deleteDriverById(id);
    }

    @Override
    public void insertDrivers(List<Driver> driverList) {
        driverMapper.saveDrivers(driverList);
    }

    @Override
    public AjaxResult getDriverSchedulingInfo(String schedulingDate, String jobCode) {
        String key = DRIVER_SCHEDULING_PRE + schedulingDate;
        long now = System.currentTimeMillis();
        List<ResponseSchedulingDto> cacheMapValue = schedulingCache.getCacheSchedulingMapValueByHKey(key, jobCode);
        // 获取考勤表进行比对,因为排班数据是会变化的
        List<DriverScheduling> dto = schedulingService.queryScheduling(jobCode, now);
        log.info("获取到排班数据:{}", cacheMapValue);
        if (jobCode.equals("700001")) {
            return AjaxResult.success("");
        }
        // 优先从缓存中读取
        if (!CollectionUtil.isEmpty(cacheMapValue) && !CollectionUtil.isEmpty(dto)) {
            return AjaxResult.success(cacheMapValue);
        }
        // 获取昨天的排班数据
        String yesterdayKey = DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate(ConstDateUtil.getTheSpecifiedNumberOfDaysOfTime(-1));
        cacheMapValue = schedulingCache.getCacheSchedulingMapValueByHKey(yesterdayKey, jobCode);
        if (!CollectionUtil.isEmpty(cacheMapValue) && !CollectionUtil.isEmpty(dto)) {
            LocalDateTime zdsjT = ConstDateUtil.getLocalDateTimeByLongTime(cacheMapValue.get(cacheMapValue.size() - 1).getZdsjT());
            LocalDateTime nowTime = ConstDateUtil.getLocalDateTimeByLongTime(now);
            long range = ChronoUnit.MINUTES.between(zdsjT, nowTime);
            if (range <= 0L) {
                return AjaxResult.success(cacheMapValue);
            } else if (range <= 120L) {
                return AjaxResult.success();
            }
        }
        return AjaxResult.success();

    }


    @Override
    public AjaxResult getDriverSchedulingAll() {
//        return AjaxResult.success(redisCache.getHashKeys(DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate("yyyyMMdd")));
        return AjaxResult.success(schedulingCache.getHKeysByKey(DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate("yyyyMMdd")));
    }

    @Override
    public AjaxResult checkJobCode(Driver driver) {
        Integer result = driverMapper.jobCodeIsEmpty(driver.getJobCode());
        Map<String, Boolean> resultMap = new HashMap<>();
        if (result > 0) {
            resultMap.put("result", true);
        } else {
            resultMap.put("result", false);
        }
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult uploadImage(MultipartFile file) throws InvalidExtensionException, IOException {
        // 上传并返回新文件名称
        // 上传文件路径
        String baseUrl = RuoYiConfig.getUploadPath() + headImagePre;
        // 校验文件格式
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        // 后期可以通过请求头拿到对应的工号
        String fileName = FilenameUtils.getBaseName(file.getOriginalFilename()) + "." + FileUploadUtils.getExtension(file);
        String absPath = FileUploadUtils.getAbsoluteFile(baseUrl, fileName).getAbsolutePath();
        fileName = FileUploadUtils.getPathFileName(baseUrl, fileName);
        file.transferTo(Paths.get(absPath));
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", file.getOriginalFilename());
        return ajax;
    }

    @Override
    public void downloadHeadImage(String jobCode, HttpServletResponse response) {
        File file = getLocationFile(jobCode);
        ServletOutputStream ops = null;
        try {
            if (file.exists()) {
                byte[] bytes = com.alibaba.excel.util.FileUtils.readFileToByteArray(file);
                ops = response.getOutputStream();
                ops.write(bytes);
                ops.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException("download fail cause:" + e.getMessage());
        } finally {
            try {
                if (ops != null) {
                    ops.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public List<DriverResponseVo> getDrivers(DriverRequestVo driver) {
        List<Driver> drivers = driverMapper.getDrivers(driver);
        Long now = System.currentTimeMillis();
        List<DriverResponseVo> vos = new ArrayList<>(drivers.size());
        List<DriverScheduling> dto = null;
        Boolean schedulingFlag = true;
        Boolean alcoholFlag = true;
        boolean needCheckAlcoholDevice = doCheckDevice(driver.getDeviceId());
        // 更新信息
        for (Driver item : drivers) {
            dto = schedulingService.queryScheduling(item.getJobCode(), now);
            DriverResponseVo vo = handlerRecommendation(item, now, dto, schedulingFlag, alcoholFlag);
            // 针对指定用户操作
            if (item.getJobCode().equals("722717") || item.getJobCode().equals("700001")) {
                if (!CollectionUtil.isEmpty(dto) && vo.getPlanAction().equals(SIGN_IN_STRING)) {
                    vos.add(DriverResponseVo.createDriverResponseVo(null, item, SIGN_IN_STRING, needCheckAlcoholDevice, true, "测试", "测试", "测试"));
                } else if (!CollectionUtil.isEmpty(dto)) {
                    vos.add(vo);
                } else {
                    vos.add(DriverResponseVo.createDriverResponseVo(null, item, SIGN_IN_STRING, needCheckAlcoholDevice, true, "测试", "测试", "测试"));
                }
            } else {
                // 无排班 工种是驾驶员需要酒测
                if (Objects.isNull(vo)) {
                    vos.add(DriverResponseVo.createDriverResponseVo(null, item, null, "驾驶员".equals(item.getPosts()), false, "", "", ""));
                } else {
                    // 特定设备是无需酒精测试的
                    vo.setCheckAlcohol(needCheckAlcoholDevice ? vo.getCheckAlcohol() : false);
                    vos.add(vo);
                }
            }
        }
        return vos;
    }

    /**
     * 100以下的都设置为有酒精测试的设备
     *
     * @param deviceId
     * @return
     */
    public static boolean doCheckDevice(String deviceId) {
        if (StringUtil.isEmpty(deviceId)) {
            return true;
        }
        int num = Integer.parseInt(deviceId);
        if (num < 101) {
            return true;
        }
        return false;
    }

    private DriverResponseVo handlerRecommendation(Driver driver, Long now, List<DriverScheduling> dto, Boolean schedulingFlag, Boolean alcoholFlag) {
        DriverResponseVo vo = null;
        // 给出计划操作
        if (!CollectionUtil.isEmpty(dto)) {
            DriverSignInRecommendation recommendation = checkTime(dto, now);
            if (BC_TYPE_OUT.equals(recommendation.getBcType())) {
                // 售票员无需酒精测试
                if (recommendation.getPosts().contains(PERSONNEL_POSTS_DRIVER))
                    vo = DriverResponseVo.createDriverResponseVo(recommendation.getTimestamps(), driver, SIGN_IN_STRING, alcoholFlag, schedulingFlag, recommendation.getNbbm(), recommendation.getLpName(), recommendation.getLineName());
                else
                    vo = DriverResponseVo.createDriverResponseVo(recommendation.getTimestamps(), driver, SIGN_IN_STRING, !alcoholFlag, schedulingFlag, recommendation.getNbbm(), recommendation.getLpName(), recommendation.getLineName());
            } else if (BC_TYPE_IN.equals(recommendation.getBcType())) {
                vo = DriverResponseVo.createDriverResponseVo(recommendation.getTimestamps(), driver, SIGN_IN_OUT_STRING, !alcoholFlag, schedulingFlag, recommendation.getNbbm(), recommendation.getLpName(), recommendation.getLineName());
            }

            // 如果驾驶员酒精测试在之前不合格 必须重测
            if ("驾驶员".equals(driver.getPosts())) {
                String key = REDIS_SIGN_IN_DRIVER_ALCOHOL_OVERFLOW + ConstDateUtil.formatDate("yyyyMMdd") + ":" + driver.getJobCode();
                Integer count = redisCache.getCacheObject(key);
                if (!Objects.isNull(count) && !Objects.isNull(vo)) {
                    vo.setCheckAlcohol(alcoholFlag);
                }
            }

        }
        return vo;
    }


    @Override
    public AjaxResult faceRegistrationFeedback(String deviceId, List<String> jobCodes) {
        threadJobService.asyncInsertSignInContactEquipment(deviceId, jobCodes);
        return AjaxResult.success("注册成功");
    }

    @Override
    public void updateDriverByComputed() {
        Integer count = equipmentMapper.count();
        // 更新人脸认证状态
        driverMapper.updateDriverByComputed(count);
    }

    @Override
    public Result<?> updateFaceByJob(HttpServletRequest request, FaceUpdateReqVo vo) {
        log.info("接收到人事数据:{}", vo);
        // 获取校验
        String header = request.getHeader("X-TOKEN-AUTHORIZATION");
        if (!PERSONNEL_API_KEY.equals(header)) {
            return Result.ERROR(ResultCode.CODE_401, "X-TOKEN-AUTHORIZATION value error");
        }
        Date date = new Date();
        // 查询当前人员信息库是否存在对应员工数据
        List<String> jobCodes = vo.getFaceDataList().stream().map(FaceUpdateReqVo.FaceData::getJobCode).collect(Collectors.toList());
        Map<String, String> existsSet = driverMapper.queryJobCodesIsExists(jobCodes).stream().collect(Collectors.toMap(item -> item, s -> s));
        jobCodes = new ArrayList<>(existsSet.values());
        List<Driver> updateDrivers = getDriversByJobCode(vo, date, existsSet, true);
        List<Driver> insertDrivers = getDriversByJobCode(vo, date, existsSet, false);
        List<List<Driver>> lists = ListUtils.splitList(updateDrivers, 400);
        log.info("开始人员数据更新");
        // 数据更新 更新人脸注册标识 更新基本数据
        for (List<Driver> list : lists) {
            driverMapper.updateDriverBaseInfoByJobCodes(list, 0);
            attendanceMainService.updateAttendanceMainByJobCode(list);
        }
        if (insertDrivers.size() > 0) driverMapper.saveDrivers(insertDrivers);

        log.info("完成人员数据更新");
        log.info("开始删除注册表中对应工号的数据");
        List<String> updateImageJobCodes = new ArrayList<>();
        for (Driver driver : updateDrivers) {
            if (StringUtil.isNotEmpty(driver.getImage())) {
                updateImageJobCodes.add(driver.getJobCode());
            }
        }
        if (updateImageJobCodes.size() > 0) {
            driverMapper.deleteDeviceIdAssociatedJobCode(updateImageJobCodes);
        }
        log.info("删除注册表中对应工号的数据结束");
        return Result.OK("共更新:" + updateDrivers.size() + "条数据," + "共存入:" + insertDrivers.size() + "条数据。");
    }

    private ArrayList<Driver> getDriversByJobCode(FaceUpdateReqVo vo, Date date, Map<String, String> existsSet, Boolean updateFlag) {
        if (updateFlag)
            return vo.getFaceDataList().stream().map(item -> {
                Driver driver = new Driver();
                driver.setPosts(item.getPosts());
                driver.setJobCode(item.getJobCode());
                driver.setFleetName(item.getFleetName());
                driver.setLineName(item.getLineName());
                try {
                    if (StringUtil.isNotEmpty(item.getImageUrl())) {
                        driver.setImage(getNewImageUrl(item.getJobCode(), item.getImageUrl()));
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());
                    throw new RuntimeException(e);
                }
                driver.setPersonnelName(item.getName());
                driver.setUpdateTime(date);
                return driver;
            }).filter(item -> !Objects.isNull(existsSet.get(item.getJobCode()))).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getJobCode()))), ArrayList::new));
        else
            return vo.getFaceDataList().stream().map(item -> {
                Driver driver = new Driver();
                driver.setPosts(item.getPosts());
                driver.setJobCode(item.getJobCode());
                driver.setFleetName(item.getFleetName());
                driver.setLineName(item.getLineName());
                driver.setFaceSignIn(SIGN_FACE_ACTIVE);
                try {
                    if (StringUtil.isNotEmpty(item.getImageUrl())) {
                        driver.setImage(getNewImageUrl(item.getJobCode(), item.getImageUrl()));
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());
                    throw new RuntimeException(e);
                }
                driver.setPersonnelName(item.getName());
                driver.setUpdateTime(date);
                return driver;
            }).filter(item -> Objects.isNull(existsSet.get(item.getJobCode()))).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getJobCode()))), ArrayList::new));

    }

    @Override
    public void updateDriverSignInfo(DriverSignInRequestVo vo) {
        log.info("开始进行人员数据更新");
        Driver driver = new Driver();
        driver.setJobCode(vo.getJobCode());
        driver.setPersonnelName(vo.getName());
        driver.setPosts(vo.getPosts());
        String base64 = vo.getImage();
        String fileName = vo.getJobCode() + ".png";
        String filePath = new File(RuoYiConfig.getUploadPath() + headImagePre + "/" + fileName + File.separator).getAbsolutePath();
        try {
            fileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath() + headImagePre, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        driver.setImage(fileName);
        driver.setUpdateTime(new Date());
        driverMapper.updateSignStatusDriversByJobCodes(new ArrayList<>(Arrays.asList(driver)));
        driverMapper.deleteDeviceIdAssociatedJobCode(new ArrayList<>(Arrays.asList(driver.getJobCode())));
        log.info("进行人员数据更新完毕");
        log.info("开始上传人脸图片");
        // 异步上传文件
        threadJobService.asyncStartUploadBase64Image(filePath, base64);
    }

    @Override
    public void updateDrivers(List<Driver> drivers) {
        driverMapper.updateDriverInfoByJobCodes(drivers);
    }


    @Override
    public void deleteNotEmptyJob(List<String> jobList) {
        driverMapper.deleteNotEmptyJob(jobList);
    }

    @Override
    public void computedExceptionScheduling() {
        // 从当前缓存种读取所有的签到数据 遍历每个工号的打卡集合
        Map<String, List<DriverScheduling>> map = nowSchedulingCache.getCacheScheduling(ConstDateUtil.formatDate(new Date()));
        List<DriverSignInRecommendation> nowTimerList = new ArrayList<>();
        Long now = System.currentTimeMillis();
        for (Map.Entry<String, List<DriverScheduling>> entry : map.entrySet()) {
            List<DriverScheduling> value = entry.getValue();
            // 匹配
            Map<Integer, DriverSignInRecommendation> timeMap = new HashMap<>();
            Integer index = handleSchedulingMap(value, now, timeMap);
            nowTimerList.add(timeMap.get(index));
        }
        // 处理当前时间段未签人员
        nowTimerList = handleTimeOutPerson(nowTimerList, now);
        sendNotice(nowTimerList);
    }

    @Override
    public List<String> queryEmptyJob(List<String> jobList) {
        return driverMapper.queryEmptyJob(jobList);
    }

    @Override
    public void updateDriverBaseInfoByJobCodes(List<Driver> drivers, int filterImage) {
        driverMapper.updateDriverBaseInfoByJobCodes(drivers, filterImage);
    }

    @Override
    public AjaxResult allUpdateDriverInfo(HttpServletRequest request) {
        String header = request.getHeader("X-TOKEN-AUTH");
        if (!"gzjUse".equals(header)) {
            throw new RuntimeException("错误的认证");
        }
        Date date = new Date();
        int pageSize = 100;
        TokenResponseVo tokenVo = DriverJob.getToken(tokenUrl);
        PersonnelResultResponseVo vo = DriverJob.getPersonInfo(tokenVo.getAccessToken(), pageSize, 1);
        int countPage = vo.getTotalCount() / pageSize;
        countPage = vo.getTotalCount() % pageSize == 0 ? countPage : countPage + 1;
        List<Driver> drivers = DriverJob.getDrivers(date, vo);
        for (int i = 2; i <= countPage; i++) {
            drivers.addAll(DriverJob.getDrivers(date, DriverJob.getPersonInfo(tokenVo.getAccessToken(), 100, i)));
        }
        if (CollectionUtil.isNotEmpty(drivers)) {
            driverMapper.updateDriverBaseInfoByJobCodes(drivers, 1);
            attendanceMainService.updateAttendanceMainByJobCode(drivers);
        }
        return AjaxResult.success();
    }

    private void sendNotice(List<DriverSignInRecommendation> nowTimerList) {
        List<SysNotice> noticeList = new ArrayList<>(nowTimerList.size());
        for (DriverSignInRecommendation item : nowTimerList) {
            SysNotice notice = new SysNotice();
            notice.setCreateBy("system");
            notice.setUpdateBy("system");
            notice.setNoticeTitle("应签未签通知");
            String jobCode = "工号:" + item.getJobCode() + "\n";
            String name = "姓名:" + item.getName() + "\n";
            String posts = "工种:" + item.getPosts() + "\n";
            String fleetName = "车队:" + item.getFleetName() + "\n";
            String scheduling = "排班:" + "有排班" + "\n";
            String signDate = "计划签到时间:" + ConstDateUtil.formatDate("yyyy-MM-dd HH:mm:ss", new Date(item.getTimestamps())) + "\n";
            String content = jobCode + name + posts + fleetName + scheduling + signDate;
            notice.setNoticeContent(content);
            notice.setNoticeType("1");
            notice.setStatus("0");
            notice.setCreateTime(DateUtils.getNowDate());
            notice.setUpdateTime(DateUtils.getNowDate());
            notice.setPlanTime(new Date(item.getTimestamps()));
            notice.setJobCode(item.getJobCode());
            noticeList.add(notice);
        }
        noticeService.saveBatch(noticeList);
    }

    private List<DriverSignInRecommendation> handleTimeOutPerson(List<DriverSignInRecommendation> nowTimerList, Long now) {
        return nowTimerList.stream()
                // 只需要签到
                .filter(item -> BC_TYPE_OUT.equals(item.getBcType()) && checkPosts(item))
                // 给出范围界限 不能未到具体时间的也发送通知
                .filter(item -> now - item.getTimestamps() >= 0)
                // 筛选应签未签人员
                .filter(item -> Objects.isNull(item.getSignTime()) || item.getTimestamps() - item.getSignTime() < 0)
                .collect(Collectors.toList());
    }

    private boolean checkPosts(DriverSignInRecommendation item) {
        switch (item.getPosts()) {
            case "驾驶员":
            case "售票员":
            case "采集员":
            case "调度":
            case "稽查":
            case "集调中心":
            case "票务":
            case "站员":
                return true;
            default:
                return false;
        }
    }

    /**
     * 获取新的imageUrl
     *
     * @param jobCode
     * @param url
     * @return
     */
    private String getNewImageUrl(String jobCode, String url) throws IOException {
        // 生成文件路径
        String fileName = jobCode + ".png";
        String filePath = RuoYiConfig.getUploadPath() + headImagePre + "/" + fileName;
        try {
            fileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath() + headImagePre, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("图片开始上传");
        // 获取图片数据
        InputStream is = HttpUtil.createGet(url).execute().bodyStream();
        // 上传图片
        ThreadJobService.uploadImage(is, filePath);
        log.info("图片上传完毕");
        return fileName;
    }

    private File getLocationFile(String jobCode) {
        String image = driverMapper.getDriverImageByJobCode(jobCode);

        return new File(RuoYiConfig.getProfile() + File.separator + image.replace("/profile", ""));
    }
}