KeyBoxController.java 40.1 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
package com.ruoyi.controller.dss;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.ConstDriverProperties;
import com.ruoyi.common.TipEnum;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ResponseResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.OrderEntity;
import com.ruoyi.domain.caiinfo.CarInfo;
import com.ruoyi.domain.driver.NewDriver;
import com.ruoyi.domain.dss.key.box.dto.*;
import com.ruoyi.domain.dss.key.box.vo.*;
import com.ruoyi.domain.dss.key.location.dto.WorkPlateV2DTO;
import com.ruoyi.domain.dss.key.location.vo.WorkPlateV2Vo;
import com.ruoyi.domain.equipment.linke.log.LingangEquipmentLinkeLog;
import com.ruoyi.domain.key.info.KeyInfo;
import com.ruoyi.domain.key.info.box.dto.KeyBoxQueryDTO;
import com.ruoyi.domain.key.info.box.vo.KeyBoxVo;
import com.ruoyi.domain.key.location.LinggangKeyWorkLocation;
import com.ruoyi.domain.scheduling.LinggangScheduling;
import com.ruoyi.domain.venue.info.LinggangVenueInfo;
import com.ruoyi.equipment.domain.Equipment;
import com.ruoyi.equipment.service.IEquipmentService;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.service.carinfo.CarInfoService;
import com.ruoyi.service.driver.NewDriverService;
import com.ruoyi.service.dss.KeyBoxVoService;
import com.ruoyi.service.equipment.linke.log.LingangEquipmentLinkeLogService;
import com.ruoyi.service.key.info.KeyInfoService;
import com.ruoyi.service.key.location.LinggangKeyWorkLocationService;
import com.ruoyi.service.scheduling.LinggangSchedulingService;
import com.ruoyi.service.venue.info.LinggangVenueInfoService;
import com.ruoyi.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author liujun
 * @date 2024年06月25日 13:04
 */
@Slf4j
@RestController
@RequestMapping("/dss")
@Api(tags = "【蓝斯一期】钥匙信息")
public class KeyBoxController extends BaseController {

    @Autowired
    private LingangEquipmentLinkeLogService lingangEquipmentLinkeLogService;

    @Autowired
    private KeyBoxVoService keyBoxVoService;
    @Autowired
    private LinggangKeyWorkLocationService linggangKeyWorkLocationService;
    @Autowired
    private LinggangSchedulingService schedulingService;
    @Autowired
    private KeyInfoService keyInfoService;
    @Autowired
    private CarInfoService carInfoService;
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private NewDriverService newDriverService;
    @Autowired
    private LinggangVenueInfoService venueInfoService;

    @PostMapping(value = "/keybox/findKey")
    @ApiOperation("钥匙信息查询")
    public ResponseResult<KeyBoxVo> listSelect(@Valid @RequestBody KeyBoxQueryDTO request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(request.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }

        LingangEquipmentLinkeLog linkeLog = saveLog(request);

        return keyBoxVoService.listSelect(request, linkeLog);
    }

    @PostMapping(value = "/Driver/workPlateV2")
    @ApiOperation("司机获取当前工作的车辆钥匙信息")
    public ResponseResult<WorkPlateV2Vo> workPlateV2(@Valid @RequestBody WorkPlateV2DTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }


        try {
            LinggangScheduling scheduling = queryScheduling(dto);
            if (Objects.isNull(scheduling)) {
                return ResponseResult.error(TipEnum.TIP_3.getCode(), TipEnum.TIP_3.getMsg());
            }
            LinggangKeyWorkLocation workLocation = queryKeyWorkLocation(scheduling, dto);
            if (Objects.isNull(workLocation)) {
                return ResponseResult.error(TipEnum.TIP_4.getCode(), TipEnum.TIP_4.getMsg());
            }

            KeyInfo keyInfo = queryKeyInfo(workLocation.getKeyInfoId());
            if (Objects.isNull(keyInfo)) {
                return ResponseResult.error404();
            }

            CarInfo carInfo = queryCarInfo(scheduling.getNbbm());
            if (Objects.isNull(carInfo)) {
                return ResponseResult.error404();
            }

            Equipment equipment = queryEquipment(dto.getDevice());
            LinggangVenueInfo venueInfo = null;
            if (Objects.nonNull(equipment)) {
                venueInfo = venueInfoService.getById(equipment.getYardId());
            }
            WorkPlateV2Vo vo = convertWorkPlateV2Vo(scheduling, workLocation, keyInfo, carInfo, equipment, venueInfo);
            return ResponseResult.success(vo);
        } catch (ParseException e) {
            logger.error("司机获取当前工作的车辆钥匙信息异常:[{}]", dto, e);
        }

        return ResponseResult.error();

    }

    @ApiOperation(value = "18.钥匙柜基础信息同步")
    @PostMapping(value = "/Device/BasicSync")
    public ResponseResult<BasicSyncVo> basicSync(@Valid @RequestBody KeyBasicSyncDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }

        try {

            Equipment equipment = queryEquipment(dto.getDevice());
            if (Objects.isNull(equipment)) {
                logger.info("根据DTO的数据无法查询设备信息:[{}]", dto);
                return ResponseResult.error404();
            }

            Equipment eq = new Equipment();
            eq.setYardId(equipment.getYardId());


            List<Equipment> equipmentList = equipmentService.list(eq);
            LinggangVenueInfo venueInfo = venueInfoService.getById(equipment.getYardId());
            if (Objects.isNull(venueInfo)) {
                logger.info("根据DTO的数据无法查询场站信息:[{}]", dto);
                return ResponseResult.error404();
            }

            List<LinggangKeyWorkLocation> workLocations = queryKeyWorkLocation(dto);
            Set<Integer> keyInfoIds = null;
            if (CollectionUtils.isNotEmpty(workLocations)) {
                keyInfoIds = workLocations.stream().map(LinggangKeyWorkLocation::getKeyInfoId).collect(Collectors.toSet());
            }

            List<KeyInfo> keyInfos = queryKeyInfos(keyInfoIds);

            LinggangScheduling scheduling = new LinggangScheduling();
            scheduling.setCzCode(venueInfo.getParkCode());
            scheduling.setStartScheduleDate(DateUtil.shortDate(dto.getTime()));
            scheduling.setType(1);

            List<LinggangScheduling> schedulings = schedulingService.listByCZ(scheduling);
            Set<String> jobCodes = null;
            Set<String> nbbms = null;
            Set<String> nbbms1 = null;
            if (CollectionUtils.isNotEmpty(schedulings)) {
                jobCodes = schedulings.stream().map(LinggangScheduling::getJobCode).collect(Collectors.toSet());
                nbbms = schedulings.stream().map(LinggangScheduling::getNbbm).collect(Collectors.toSet());
            }

            scheduling.setEndScheduleDate(scheduling.getStartScheduleDate());
            List<LinggangScheduling> schedulings1 = schedulingService.listByCZ(scheduling);
            if (CollectionUtils.isNotEmpty(schedulings1)) {
                nbbms1 = schedulings1.stream().map(LinggangScheduling::getNbbm).collect(Collectors.toSet());
            }

            List<NewDriver> drivers = queryDrive(jobCodes);
            if (CollectionUtils.isEmpty(drivers)) {
                logger.info("根据DTO的数据无法查询司机信息:[{}]", dto);
            }
            List<CarInfo> carInfos = queryCarInfo(nbbms);
            if (CollectionUtils.isEmpty(carInfos)) {
                logger.info("根据DTO的数据无法查询车辆信息:[{}]", dto);
            }

            List<CarInfo> carInfos1 = queryCarInfo(nbbms1);
            if (CollectionUtils.isEmpty(carInfos)) {
                logger.info("根据DTO的数据无法查询车辆信息(carInfos1):[{}]", dto);
            }

            BasicSyncVo vo = convertBasicSyncVo(workLocations, schedulings, keyInfos, drivers, carInfos, equipment, venueInfo, equipmentList, schedulings1, carInfos1);
            return ResponseResult.success(vo);
        } catch (ParseException e) {
            logger.error("钥匙柜基础信息同步异常:[{}]", dto, e);
        }
        return ResponseResult.error();
    }

    @PostMapping(value = "/Driver/SkipOperation")
    @ApiOperation(value = "19.人员跳过钥匙柜操作")
    public ResponseResult<SkipOperationVo> skipOperation(@Valid @RequestBody SkipOperationDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }

        Equipment equipment = queryEquipment(dto.getDevice());
        if (Objects.isNull(equipment)) {
            logger.info("根据DTO的数据无法查询设备信息:[{}]", dto);
            return ResponseResult.error404();
        }

        SkipOperationVo vo = convertSkipOperationVo(equipment);
        return ResponseResult.success(vo);
    }

    @PostMapping(value = "Driver/TakeKey")
    @ApiOperation(value = "20.人员领取钥匙")
    public ResponseResult<TakeKeyVo> takeKey(@Valid @RequestBody TakeKeyDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }



        LinggangKeyWorkLocation entity = new LinggangKeyWorkLocation();
        entity.setDevice(dto.getDevice());
        List<LinggangKeyWorkLocation> schedulings = linggangKeyWorkLocationService.list(entity);

        List<KeyInfo> keyInfos = null;
        if(CollectionUtils.isNotEmpty(dto.getKeyItem())){
            Set<String> codes = dto.getKeyItem().stream().map(TakeKeyKeyItemDTO::getKeyCode).filter(obj->Objects.nonNull(obj)).collect(Collectors.toSet());
            keyInfos = keyInfoService.list(codes);
        }

        NewDriver driver = newDriverService.getOne(dto.getStaffCode());
//        if (Objects.isNull(driver)) {
//            logger.info("[{}]没有找到driver", dto);
//            return ResponseResult.error404();
//        }

        List<LinggangKeyWorkLocation> locations = convert(dto, schedulings, driver,keyInfos);
        ResponseResult<Boolean> responseResult = linggangKeyWorkLocationService.updateTakeKey(locations, LinggangKeyWorkLocation.LinggangKeyWorkLocationTypeEnum.TAKE_OUT);
        if (Objects.isNull(responseResult)) {
            return ResponseResult.error();
        }
        Equipment equipment = equipmentService.getOneByDeviceId(dto.getDevice());

        TakeKeyVo vo = convertTakeKeyVo(dto, responseResult, equipment);

        return new ResponseResult<>(responseResult.getCode(), responseResult.getMsg(), vo);
    }

    @PostMapping(value = "Driver/TurnKey")
    @ApiOperation(value = "21.人员归还钥匙")
    public ResponseResult<TakeKeyVo> turnKey(@Valid @RequestBody TakeKeyDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }


        LinggangKeyWorkLocation entity = new LinggangKeyWorkLocation();
        entity.setDevice(dto.getDevice());
        entity.setType(2);
        entity.setStartScheduleDate(dto.getTime());
        List<LinggangKeyWorkLocation> schedulings = linggangKeyWorkLocationService.list(entity);

        NewDriver driver = newDriverService.getOne(dto.getStaffCode());
        if (Objects.isNull(driver)) {
            logger.info("[{}]没有找到driver", dto);
            return ResponseResult.error404();
        }

        List<KeyInfo> keyInfos = null;
        if(CollectionUtils.isNotEmpty(dto.getKeyItem())){
            Set<String> codes = dto.getKeyItem().stream().map(TakeKeyKeyItemDTO::getKeyCode).filter(obj->Objects.nonNull(obj)).collect(Collectors.toSet());
            keyInfos = keyInfoService.list(codes);

            if(CollectionUtils.isEmpty(keyInfos)){
                codes = dto.getKeyItem().stream().map(TakeKeyKeyItemDTO::getPlate).filter(obj->Objects.nonNull(obj)).collect(Collectors.toSet());
                keyInfos = keyInfoService.list(null,codes);
            }
        }



        List<LinggangKeyWorkLocation> locations = convert(dto, schedulings, driver,keyInfos);
//        List<LinggangKeyWorkLocation> errorLocations = locations.stream().filter(l -> Objects.isNull(l.getKeyInfoId())).collect(Collectors.toList());
//        locations = locations.stream().filter(l -> Objects.nonNull(l.getKeyInfoId())).collect(Collectors.toList());
        ResponseResult<Boolean> responseResult = linggangKeyWorkLocationService.updateTakeKey(locations, LinggangKeyWorkLocation.LinggangKeyWorkLocationTypeEnum.REPAY);
        if (Objects.isNull(responseResult)) {
            return ResponseResult.error();
        }

        if (!responseResult.isSuccess()) {
            return ResponseResult.error(responseResult.getCode(), responseResult.getMsg());
        }

//        if (CollectionUtils.isNotEmpty(errorLocations)) {
//
//            Set<String> errorCode = errorLocations.stream().map(LinggangKeyWorkLocation::getKey).collect(Collectors.toSet());
//            return ResponseResult.error(responseResult.getCode(), JSON.toJSONString(errorCode) + "归还失败,请归还到指定位置");
//        }


        Equipment equipment = equipmentService.getOneByDeviceId(dto.getDevice());
        TakeKeyVo vo = convertTakeKeyVo(dto, responseResult, equipment);

        return new ResponseResult<>(responseResult.getCode(), responseResult.getMsg(), vo);
    }

    @PostMapping(value = "Driver/TurnKey/plan")
    @ApiOperation(value = "钥匙归还计划")
    public ResponseResult<List<TakeKeyPlanVo>> getKeyWorkLocaltionPlan(@Valid @RequestBody TakeKeyPlanDTO dto,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }



        LinggangKeyWorkLocation entity = new LinggangKeyWorkLocation();
        entity.setDevice(dto.getDevice());
        entity.setType(2);
        entity.setDelFlag(Boolean.FALSE);
        entity.setStartScheduleDate(dto.getTime());
        entity.setEndScheduleDate(org.apache.commons.lang3.time.DateUtils.addDays(dto.getTime(),1));

        List<LinggangKeyWorkLocation> schedulings = linggangKeyWorkLocationService.list(entity);
        if(CollectionUtils.isEmpty(schedulings)){
            return ResponseResult.success();
        }

        Set<Integer> keyIds = schedulings.stream().map(LinggangKeyWorkLocation::getKeyInfoId).collect(Collectors.toSet());

        List<KeyInfo> tempKeyInfos = null;
        if(CollectionUtils.isNotEmpty(keyIds)){
            tempKeyInfos = keyInfoService.listByIds(keyIds);
        }
        List<KeyInfo> keyInfos = tempKeyInfos;
        int keyInfoSize = CollectionUtils.size(keyInfos);

      List<TakeKeyPlanVo>  vos = schedulings.stream().map(s->{
            TakeKeyPlanVo vo = convert(s);
            if(keyInfoSize  > 0){
                Optional<KeyInfo> optional = keyInfos.stream().filter(k->Objects.equals(k.getId(),s.getKeyInfoId())).findFirst();
                if(optional.isPresent()){
                    vo.setKeyCode(optional.get().getKeyCode());
                }
            }

            return vo;
        }).collect(Collectors.toList());
        return ResponseResult.success(vos);
    }

    @PostMapping(value = "/keybox/yarnCabinetState/page")
    @ApiOperation(value = "24.场站钥匙柜实况信息")
    public ResponseResult<YarnCabinetStatePageVO> yarnCabinetStatePage(@Valid @RequestBody YarnCabinetStatePageDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }

        String msg = JwtAuthenticationTokenFilter.validateDevice(dto.getDevice());
        if(StringUtils.isNotEmpty(msg)){
            log.info(msg);
            return ResponseResult.error(TipEnum.TIP_401.getCode(),TipEnum.TIP_401.getMsg());
        }


        Set<Integer> keyInfoIds = null;
        List<KeyInfo> keyInfos = null;
        LinggangKeyWorkLocation keyWorkLocation = new LinggangKeyWorkLocation();
        if (StringUtils.isNotEmpty(dto.getDevice())) {
            keyWorkLocation.setDevice(dto.getDevice());
        }

        if (StringUtils.isNotEmpty(dto.getPlate())) {
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.setPlateNum(dto.getPlate());
            keyInfos = keyInfoService.list(keyInfo);
            if (CollectionUtils.isNotEmpty(keyInfos)) {
                keyInfoIds = keyInfos.stream().map(KeyInfo::getId).collect(Collectors.toSet());
            }
        }

        LinggangKeyWorkLocation location = new LinggangKeyWorkLocation();
        location.setDevice(dto.getDevice());

        List<LinggangKeyWorkLocation> locations = linggangKeyWorkLocationService.listRecent(location, keyInfoIds, new Date());
        if (CollectionUtils.isEmpty(locations)) {
            return ResponseResult.success();
        }

        location.setType(255);
        location.setStartScheduleDate(locations.get(0).getScheduleDate());
        int errorCount = linggangKeyWorkLocationService.countId(location);

        location.setType(0);
        int depositCount = linggangKeyWorkLocationService.countId(location);

        Equipment equipment = queryEquipment(dto.getDevice());

        Equipment sourceEq = new Equipment();
        sourceEq.setYardId(locations.get(0).getYardId());
        List<Equipment> equipmentList = equipmentService.list(sourceEq);

        LinggangKeyWorkLocation locationEq = new LinggangKeyWorkLocation();
        locationEq.setYardId(sourceEq.getYardId());
        locationEq.setStartScheduleDate(locations.get(0).getScheduleDate());

        List<LinggangKeyWorkLocation> locationsOfEq = linggangKeyWorkLocationService.list(locationEq);

        locationEq = new LinggangKeyWorkLocation();
        locationEq.setYardId(sourceEq.getYardId());
        locationEq.setStartScheduleDate(locations.get(0).getScheduleDate());
        IPage<LinggangKeyWorkLocation> page = linggangKeyWorkLocationService.pageList(new Page<>(dto.getPageNum(), dto.getPageSize()), locationEq, new OrderEntity());

        List<LinggangScheduling> schedulings = Collections.emptyList();
        List<CarInfo> carInfos = Collections.emptyList();
        List<NewDriver> drivers = Collections.emptyList();
        List<Equipment> yarnCabinetStateEqus = Collections.emptyList();

        if (Objects.nonNull(page) && CollectionUtils.isNotEmpty(page.getRecords())) {
            Set<Long> driverIds = page.getRecords().stream().map(LinggangKeyWorkLocation::getCreateBy).collect(Collectors.toSet());
            drivers = newDriverService.listOfIdsLon(driverIds);

            Set<String> deviceCodes = page.getRecords().stream().map(LinggangKeyWorkLocation::getDevice).collect(Collectors.toSet());
            yarnCabinetStateEqus = equipmentService.listNameAndIDBydeviceIds(deviceCodes);

            Set<Long> schedulingIds = page.getRecords().stream().map(LinggangKeyWorkLocation::getSchedulingId).collect(Collectors.toSet());
            schedulings = schedulingService.listByIds(schedulingIds);
            if (CollectionUtils.isNotEmpty(schedulings)) {
                Set<String> nbbm = schedulings.stream().map(LinggangScheduling::getNbbm).collect(Collectors.toSet());
                carInfos = carInfoService.list(nbbm);
            }
        }
        YarnCabinetStatePageVO pageVO = conertYarnCabinetStatePageVO(locations, equipment, errorCount, depositCount, equipmentList, locationsOfEq, page, schedulings, dto, carInfos, drivers, yarnCabinetStateEqus);
        return ResponseResult.success(pageVO);
    }

    /***
     * 查询排班
     * @author liujun
     * @date 2024/7/16 17:05
     * @param dto
     * @return com.ruoyi.domain.scheduling.LinggangScheduling
     */
    private LinggangScheduling queryScheduling(WorkPlateV2DTO dto) throws ParseException {
        LinggangScheduling scheduling = new LinggangScheduling();
        scheduling.setJobCode(dto.getStaffCode());

        scheduling.setStartScheduleDate(DateUtil.shortDate(dto.getTime()));
        scheduling.setEndScheduleDate(org.apache.commons.lang3.time.DateUtils.addDays(scheduling.getStartScheduleDate(),1));
//        String bcType = Objects.equals(0, dto.getEventType()) ? ConstDriverProperties.BC_TYPE_OUT : Objects.equals(1, dto.getEventType()) ? ConstDriverProperties.BC_TYPE_IN : "other";
        String bcType = ConstDriverProperties.BC_TYPE_OUT;
        scheduling.setBcType(bcType);
        scheduling.setType(1);

        List<LinggangScheduling> linggangSchedulings = schedulingService.list(scheduling);
        if (CollectionUtils.isEmpty(linggangSchedulings)) {
            return null;
        }


        Optional<LinggangScheduling> optional = linggangSchedulings.stream().filter(lin -> lin.getZdsjT() >= dto.getTime().getTime()).findFirst();
        if (optional.isPresent()) {
            return optional.get();
        }
        int size = linggangSchedulings.size();
        return linggangSchedulings.get(size - 1);
    }

    private List<LinggangScheduling> queryScheduling(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return schedulingService.listByIds(ids);
    }


    /***
     * 根据排班时间和钥匙ID查询钥匙
     * @author liujun
     * @date 2024/7/16 17:05
     * @param dto
     * @return com.ruoyi.domain.key.location.LinggangKeyWorkLocation
     */
    private LinggangKeyWorkLocation queryKeyWorkLocation(LinggangScheduling scheduling, WorkPlateV2DTO dto) {
        LinggangKeyWorkLocation workLocation = new LinggangKeyWorkLocation();
        workLocation.setKeyInfoId(scheduling.getKeyInfoId());
        workLocation.setSchedulingId(scheduling.getId());
        return linggangKeyWorkLocationService.getOne(workLocation);
    }


    private List<LinggangKeyWorkLocation> queryKeyWorkLocation(KeyBasicSyncDTO dto) throws ParseException {
        LinggangKeyWorkLocation workLocation = new LinggangKeyWorkLocation();

        String dateStr = DateUtils.YYYY_MM_DD.format(dto.getTime());
        workLocation.setScheduleDate(DateUtils.YYYY_MM_DD.parse(dateStr));
        workLocation.setDevice(dto.getDevice());
        workLocation.setDelFlag(Boolean.FALSE);

        return linggangKeyWorkLocationService.list(workLocation);
    }

    private KeyInfo queryKeyInfo(Integer keyId) {
        return keyInfoService.getById(keyId);
    }

    private List<KeyInfo> queryKeyInfos(Collection<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return keyInfoService.listByIds(ids);
    }

    private CarInfo queryCarInfo(String nbbm) {
        CarInfo carInfo = new CarInfo();
        carInfo.setNbbm(nbbm);

        return carInfoService.getOne(carInfo);
    }

    private Equipment queryEquipment(String deviceId) {
        return equipmentService.getOneByDeviceId(deviceId);
    }

    private List<NewDriver> queryDrive(Collection<String> jobCods) {
        if (CollectionUtils.isEmpty(jobCods)) {
            return Collections.emptyList();
        }
        return newDriverService.list(jobCods);
    }

    private List<CarInfo> queryCarInfo(Collection<String> nbbms) {
        if (CollectionUtils.isEmpty(nbbms)) {
            return Collections.emptyList();
        }
        return carInfoService.list(nbbms);
    }


    /***
     * 保存链接日志
     * @author liujun
     * @date 2024/6/25 15:24
     * @param request
     * @return com.ruoyi.domain.equipment.linke.log.LingangEquipmentLinkeLog
     */
    private LingangEquipmentLinkeLog saveLog(KeyBoxQueryDTO request) {
        LingangEquipmentLinkeLog linkeLog = new LingangEquipmentLinkeLog();
        linkeLog.setDevice(request.getDevice());
        linkeLog.setCreateTime(new Date());
        linkeLog.setPassingReferences(JSON.toJSONString(request));
        linkeLog.setUrl("/dss/keybox/findKey");

        lingangEquipmentLinkeLogService.save(linkeLog);
        return linkeLog;
    }

    private WorkPlateV2Vo convertWorkPlateV2Vo(LinggangScheduling scheduling, LinggangKeyWorkLocation workLocation, KeyInfo keyInfo, CarInfo carInfo,
                                               Equipment equipment, LinggangVenueInfo venueInfo) {
        WorkPlateV2Vo vo = new WorkPlateV2Vo();
        if (Objects.nonNull(venueInfo)) {
            vo.setYardId(Convert.toStr(venueInfo.getId()));
            vo.setYardName(venueInfo.getName());
        }

        if (Objects.nonNull(equipment)) {
            vo.setDeviceName(equipment.getName());
        }
//        vo.setYardName(keyInfo.getY)
        vo.setDevice(workLocation.getDevice());
        vo.setCabinetNo(workLocation.getCabinetNo());
        vo.setPlateNum(carInfo.getPlateNum());

        return vo;
    }

    private BasicSyncVo convertBasicSyncVo(List<LinggangKeyWorkLocation> workLocations, List<LinggangScheduling> schedulings,
                                           List<KeyInfo> keyInfos, List<NewDriver> drivers, List<CarInfo> carInfos, Equipment equipment,
                                           LinggangVenueInfo venueInfo, List<Equipment> equipmentList, List<LinggangScheduling> schedulings1, List<CarInfo> carInfos1) {
        BasicSyncVo vo = new BasicSyncVo();

        vo.setDevice(equipment.getDeviceId());
        vo.setDeviceType(equipment.getPromise());
        if (CollectionUtils.isNotEmpty(workLocations)) {
            vo.setTime(workLocations.get(0).getScheduleDate());
        }

        if (Objects.nonNull(venueInfo)) {
            vo.setYardName(venueInfo.getName());
        }
        vo.setKeyboxName(equipment.getName());


        if (CollectionUtils.isNotEmpty(equipmentList)) {
            List<BasicSyncKeyboxVo> keyboxVos = equipmentList.stream().map(eq -> {
                BasicSyncKeyboxVo keyboxVo = new BasicSyncKeyboxVo();
                keyboxVo.setName(eq.getName());
                keyboxVo.setDevice(eq.getDeviceId());
                if (Objects.nonNull(eq.getLatticeNumber()) && eq.getLatticeNumber() > 0) {
                    List<BasicSyncKeyboxKeyItemVo> itemVos = new ArrayList<>(eq.getLatticeNumber());
                    for (int i = 0; i < eq.getLatticeNumber(); i++) {
                        itemVos.add(new BasicSyncKeyboxKeyItemVo(Convert.toStr(i + 1), null));
                    }
                    keyboxVo.setKeyItem(itemVos);
                }
                return keyboxVo;
            }).collect(Collectors.toList());
            vo.setKeybox(keyboxVos);
        }

        List<BasicSyncDriverWorkVo> driverWork = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(schedulings)) {
            Map<Date, List<LinggangScheduling>> schedulingMap = schedulings.stream().collect(Collectors.groupingBy(LinggangScheduling::getScheduleDate));
            schedulingMap.forEach((key, schedulingList) -> {
                BasicSyncDriverWorkVo driverPlanVo = new BasicSyncDriverWorkVo();
                driverPlanVo.setPlanDate(key);
                if (CollectionUtils.isNotEmpty(schedulingList)) {
                    List<BasicSyncDriverWorkDriverPlanVo> planVos = schedulingList.stream().map(sc -> {
                        BasicSyncDriverWorkDriverPlanVo planVo = new BasicSyncDriverWorkDriverPlanVo();
                        Optional<NewDriver> optional = drivers.stream().filter(d -> Objects.equals(d.getJobCode(), sc.getJobCode())).findFirst();
                        if (!optional.isPresent()) {
                            return null;
                        }

                        Optional<CarInfo> carInfoOptional = carInfos.stream().filter(c -> Objects.equals(c.getNbbm(), sc.getNbbm())).findFirst();
                        if (!carInfoOptional.isPresent()) {
                            return null;

                        }
                        planVo.setDriverCode(optional.get().getIcCardCode());
                        planVo.setStaffCode(sc.getJobCode());

                        BasicSyncDriverWorkDriverPlanTimePlateVo planTimePlateVo = new BasicSyncDriverWorkDriverPlanTimePlateVo();
                        planTimePlateVo.setKey(new Date(sc.getFcsjT()));

                        planTimePlateVo.setValue(carInfoOptional.get().getPlateNum());
                        planVo.setTimePlate(planTimePlateVo);

                        return planVo;
                    }).filter(obj -> Objects.nonNull(obj)).collect(Collectors.toList());

                    driverPlanVo.setDriverPlan(planVos);
                }
                driverWork.add(driverPlanVo);
            });
        }
        vo.setDriverWork(driverWork);
        if (CollectionUtils.isNotEmpty(schedulings1) && CollectionUtils.isNotEmpty(carInfos1)) {
            Set<String> nbbms = schedulings1.stream().filter(s -> Objects.equals(s.getQdzcode(), venueInfo.getParkCode()) ||
                    Objects.equals(s.getZdzcode(), venueInfo.getParkCode())).map(LinggangScheduling::getNbbm).collect(Collectors.toSet());
            List<String> plateNums = carInfos1.stream().filter(c -> nbbms.contains(c.getNbbm())).map(CarInfo::getPlateNum).collect(Collectors.toList());
            vo.setYardVehicles(plateNums);

        }

        return vo;
    }

    private SkipOperationVo convertSkipOperationVo(Equipment equipment) {
        SkipOperationVo vo = new SkipOperationVo();
        vo.setDevice(equipment.getDeviceId());
        vo.setTime(new Date());
        vo.setDeviceType(equipment.getPromise());
        vo.setResult(0);

        return vo;
    }

    private List<LinggangKeyWorkLocation> convert(TakeKeyDTO dto, List<LinggangKeyWorkLocation> schedulings, NewDriver driver,List<KeyInfo> keyInfos) {
        if (CollectionUtils.isEmpty(dto.getKeyItem())) {
            return Collections.emptyList();
        }

        return dto.getKeyItem().stream().map(item -> {
            LinggangKeyWorkLocation location = new LinggangKeyWorkLocation();
            location.setDevice(item.getDevice());
            location.setEventType(dto.getOpeType());
            location.setKey(item.getKey());
            location.setScheduleDate(DateUtil.shortDate(dto.getTime()));
            location.setType(item.getState());
            if (CollectionUtils.isNotEmpty(schedulings)) {
                Optional<LinggangKeyWorkLocation> opt = schedulings.stream().filter(s -> Objects.equals(item.getKey(), s.getCabinetNo())).findFirst();
                if (opt.isPresent()) {
                    location.setKeyInfoId(opt.get().getKeyInfoId());
                }
            }
            if(Objects.nonNull(keyInfos)){
               Optional<KeyInfo> optional = keyInfos.stream().filter(k->Objects.equals(k.getKeyCode(),item.getKeyCode())).findFirst();
                if (optional.isPresent()) {
                    location.setKeyInfoId(optional.get().getId());
                }else{
                    optional = keyInfos.stream().filter(k->Objects.equals(k.getPlateNum(),item.getPlate())).findFirst();
                    if (optional.isPresent()) {
                        location.setKeyInfoId(optional.get().getId());
                    }
                }
            }

            if (Objects.nonNull(driver)) {
                location.setCreateBy(Convert.toLong(driver.getId()));
            }
            location.setCreateTime(new Date());

            return location;
        }).collect(Collectors.toList());
    }

    private TakeKeyVo convertTakeKeyVo(TakeKeyDTO dto, ResponseResult<Boolean> result, Equipment equipment) {
        TakeKeyVo vo = new TakeKeyVo();
        vo.setDevice(dto.getDevice());
        vo.setTime(new Date());
        vo.setResult(result.isSuccess() ? 0 : 1);
        vo.setStaffCode(dto.getStaffCode());
        if (Objects.nonNull(equipment)) {
            vo.setDeviceType(equipment.getPromise());
            vo.setDriverCode(equipment.getDeviceId());
        }


        return vo;
    }

    private YarnCabinetStatePageVO conertYarnCabinetStatePageVO(List<LinggangKeyWorkLocation> locations, Equipment equipment,
                                                                int errorCount, int depositCount, List<Equipment> equipmentList,
                                                                List<LinggangKeyWorkLocation> locationsOfEqs,
                                                                IPage<LinggangKeyWorkLocation> page, List<LinggangScheduling> schedulings,
                                                                YarnCabinetStatePageDTO dto, List<CarInfo> carInfos, List<NewDriver> drivers,
                                                                List<Equipment> yarnCabinetStateEqus) {
        if (CollectionUtils.isEmpty(locations)) {
            return null;
        }
        YarnCabinetStatePageVO vo = new YarnCabinetStatePageVO();
        vo.setYarnId(locations.get(0).getYardId());
        vo.setYarnName(locations.get(0).getYardName());
        vo.setEx(errorCount);
        vo.setIn(depositCount);

        if (Objects.nonNull(equipment)) {
            int count = Objects.isNull(equipment.getLatticeNumber()) ? 0 : equipment.getLatticeNumber() - errorCount - depositCount;
            count = count < 0 ? 0 : count;
            vo.setFree(count);
        }


        if (CollectionUtils.isNotEmpty(equipmentList)) {
            List<YarnCabinetStatePageCabinetsVO> cabinets = equipmentList.stream().map(eq -> {
                YarnCabinetStatePageCabinetsVO cabinetsVO = new YarnCabinetStatePageCabinetsVO();
                cabinetsVO.setDeviceId(eq.getDeviceId());
                cabinetsVO.setDevice(eq.getIp());
                cabinetsVO.setDeviceName(eq.getName());

                int count = Objects.isNull(eq.getLatticeNumber()) ? 0 : eq.getLatticeNumber();
                List<YarnCabinetStatePageCabinetsKeysVO> keys = new ArrayList<>(count);
                for (int i = 0; i < count; i++) {
                    YarnCabinetStatePageCabinetsKeysVO keysVO = new YarnCabinetStatePageCabinetsKeysVO();
                    keysVO.setCabinetNo(Convert.toStr(i + 1));
                    keysVO.setState(2);
                    if (CollectionUtils.isNotEmpty(locationsOfEqs)) {
                        Optional<LinggangKeyWorkLocation> optional = locationsOfEqs.stream().filter(l -> Objects.equals(l.getDevice(), eq.getDeviceId()) &&
                                Objects.equals(keysVO.getCabinetNo(), l.getCabinetNo())).findFirst();

                        if (optional.isPresent()) {
                            if (Objects.equals(255, optional.get().getType())) {
                                keysVO.setState(255);
                            } else if ((Objects.equals(0, optional.get().getType()) || Objects.equals(2, optional.get().getType()))) {
                                keysVO.setState(1);
                            }
                        }
                    }
                    keys.add(keysVO);
                }

                cabinetsVO.setKeys(keys);
                return cabinetsVO;

            }).collect(Collectors.toList());
            vo.setCabinets(cabinets);
        }

        if (Objects.nonNull(page)) {
            YarnCabinetStatePageOutKeysVo keysVo = new YarnCabinetStatePageOutKeysVo();
            keysVo.setCurrent(dto.getPageNum());
            keysVo.setSize(dto.getPageSize());
            keysVo.setTotal(page.getTotal());
            keysVo.setPages(Convert.toInt(page.getPages()));
            if (CollectionUtils.isNotEmpty(page.getRecords())) {
                List<YarnCabinetStatePageOutKeysRecordsVo> recordsVos = page.getRecords().stream().map(l -> {
                    YarnCabinetStatePageOutKeysRecordsVo recordsVo = new YarnCabinetStatePageOutKeysRecordsVo();
                    if (CollectionUtils.isNotEmpty(schedulings)) {
                        Optional<LinggangScheduling> optional = schedulings.stream().filter(sc -> Objects.equals(l.getSchedulingId(), sc.getId())).findFirst();
                        if (optional.isPresent()) {
                            recordsVo.setRouteName(optional.get().getLineName());
                            recordsVo.setSelfCode(optional.get().getNbbm());
                            if (CollectionUtils.isNotEmpty(carInfos)) {
                                Optional<CarInfo> optCar = carInfos.stream().filter(c -> Objects.equals(c.getNbbm(), optional.get().getNbbm())).findFirst();
                                if (optCar.isPresent()) {
                                    recordsVo.setPlate(optCar.get().getPlateNum());
                                }
                            }
                        }
                    }

                    if (CollectionUtils.isNotEmpty(drivers)) {
                        Optional<NewDriver> opt = drivers.stream().filter(d -> Objects.equals(Convert.toLong(d.getId()), l.getCreateBy())).findFirst();
                        if (opt.isPresent()) {
                            recordsVo.setStaffName(opt.get().getPersonnelName());
                        }
                    }
                    recordsVo.setTime(l.getCreateTime());

                    if (CollectionUtils.isNotEmpty(yarnCabinetStateEqus)) {
                        Optional<Equipment> opt = yarnCabinetStateEqus.stream().filter(ya -> Objects.equals(ya.getDeviceId(), l.getDevice())).findFirst();
                        if (opt.isPresent()) {
                            recordsVo.setDeviceName(opt.get().getName());
                        }
                    }
                    return recordsVo;
                }).collect(Collectors.toList());
                keysVo.setRecords(recordsVos);
            }
            vo.setOutKeys(keysVo);
        }
        return vo;
    }

    private TakeKeyPlanVo convert(LinggangKeyWorkLocation source) {
        return java.util.Optional.ofNullable(source).map(sc -> {
            TakeKeyPlanVo target = new TakeKeyPlanVo();
            BeanUtils.copyProperties(source, target);
            return target;
        }).orElseGet(null);
    }
}