GarOrderServiceImpl.java 61.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 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 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
package com.trash.garbage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trash.common.core.redis.RedisCache;
import com.trash.common.utils.SecurityUtils;
import com.trash.common.utils.ServletUtils;
import com.trash.driver.domain.vo.DriverVo;
import com.trash.driver.service.IDriverService;
import com.trash.enterprise.domain.TransportationEnterprise;
import com.trash.enterprise.service.ITransportationEnterpriseService;
import com.trash.garbage.custom.BizException;
import com.trash.garbage.global.GlobalStatus;
import com.trash.garbage.global.ResultCode;
import com.trash.garbage.mapper.GarOrderMapper;
import com.trash.garbage.pojo.domain.*;
import com.trash.garbage.pojo.dto.*;
import com.trash.garbage.pojo.vo.*;
import com.trash.garbage.service.*;
import com.trash.garbage.utils.SMSUtils;
import com.trash.garbage.utils.ValidateCodeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 20412
 * @description 针对表【gar_order(建筑垃圾—订单表)】的数据库操作Service实现
 * @createDate 2023-11-24 16:26:19
 */
@Service
public class GarOrderServiceImpl extends ServiceImpl<GarOrderMapper, GarOrder>
        implements GarOrderService {


    @Autowired
    private GarUserOrderMessageService orderMessageService;
    @Autowired
    private GarUserOrderMessageHistoryService orderMessageHistoryService;
    @Resource
    private SMSUtils smsUtils;
    @Autowired
    private GarOrderImageService garOrderImageService;
    @Autowired
    private GarOrderMatchAskService askService;
    @Autowired
    private GarAddressService garAddressService;
    @Autowired
    private GarOrderMatchAskService matchAskService;
    @Autowired
    private GarOrderMatchDisposalService disposalService;
    @Autowired
    private ITransportationEnterpriseService transportationEnterpriseService;
    @Autowired
    private GarOrderEvaluateService garOrderEvaluateService;
    @Autowired
    private GarSearchHistoryService garSearchHistoryService;
    @Autowired
    private GarUserService garUserService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private GarOrderMatchHandlerService handlerService;
    @Autowired
    private GarOrderCarService garOrderCarService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private GarOrderMatchDisposalService garOrderMatchDisposalService;
    @Autowired
    private DisposalSiteService disposalSiteService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveOrder(OrderDto dto) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        GarOrder order = new GarOrder();
        // companyId
        BeanUtils.copyProperties(dto, order);
        order.setGarOrderUserId(userId);
        order.setGarOrderHandlerStatus(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue());
        order.setGarCancelFlag(GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
        order.setGarOrderScanHandlerFlag(GlobalStatus.GarOrderStatus.SCAN_HANDLER_NO.getValue());
        // 预估车辆等于用户选择得车辆
        order.setGarRealCarCount(dto.getGarCarInfoList().stream().mapToInt(OrderDto.CarInfo::getGarOrderCarNumber).sum());
        order.setGarTimeOutFlag(GlobalStatus.GarOrderStatus.ORDER_TIME_OUT_FLAG_NO.getValue());
        save(order);

        // 保存车辆信息
        List<OrderDto.CarInfo> garCarInfoList = dto.getGarCarInfoList();
        List<GarOrderCar> garOrderCars = new ArrayList<>();
        for (OrderDto.CarInfo carInfo : garCarInfoList) {
            for (int index = 0; index < carInfo.getGarOrderCarNumber(); index++) {
                GarOrderCar car = new GarOrderCar();
                car.setGarOrderCarType(carInfo.getGarOrderCarType());
                car.setGarOrderId(order.getGarOrderId());
                car.setCarId(carInfo.getId());
                car.setContainerVolume(carInfo.getContainerVolume());
                car.setGarOrderCarUserType(GlobalStatus.GarOrderStatus.PLAN_CAR_TYPE.getValue());
                garOrderCars.add(car);
            }
        }
        garOrderCarService.saveBatch(garOrderCars);

        // 保存图片url
        List<String> imageUrls = dto.getImageUrls();
        List<GarOrderImage> images = new ArrayList<>(imageUrls.size());
        for (String imageUrl : imageUrls) {
            GarOrderImage image = new GarOrderImage();
            image.setGarOrderId(order.getGarOrderId());
            image.setGarOrderImageUrl(imageUrl);
            image.setGarOrderImageType(GlobalStatus.GarOrderStatus.IMAGE_TYPE_CURRENT.getValue());
            images.add(image);
        }
        garOrderImageService.saveBatch(images);
        // TODO 短信提醒 居民下单
        smsUtils.sendMessage(order.getGarOrderCompanyTel(), "企业收单:您有新的清运订单,请及时查看并处理。");
        return order.getGarOrderId();
    }

    @Override
    public OrderDetailVo queryOrderDetail(String id) {

        GarUser user = garUserService.getById(SecurityUtils.getLoginUser().getUser().getUserId());
        OrderDetailVo orderDetailVo = null;
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())
                || user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription())) {
            orderDetailVo = getOrderDetailVoResponsible(id, user);
        }
        //  订单分发获取 驾驶员
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription())) {
            orderDetailVo = getOrderDetailVoDriver(id, user);
        }

        if (Objects.equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription(), user.getGarUserType()) && Objects.nonNull(orderDetailVo)) {
            //查询是否有用户评价
            GarOrderEvaluate evaluate = new GarOrderEvaluate();
            evaluate.setGarOrderId(id);
            int count = garOrderEvaluateService.countId(evaluate);

            orderDetailVo.setHaveEvaluateOfClient(count == 0 ? 0 : 1);
        }

        if (Objects.nonNull(orderDetailVo)) {
            return orderDetailVo;
        }

        throw new BizException(ResultCode.CODE_500, "没有当前角色");
    }

    private OrderDetailVo getOrderDetailVoDriver(String orderId, GarUser user) {
        LambdaQueryWrapper<GarOrderImage> qwi = new LambdaQueryWrapper<>();
        qwi.eq(GarOrderImage::getGarOrderId, orderId)
                .eq(GarOrderImage::getGarCreateBy, user.getGarUserId());
        OrderDetailVo vo = new OrderDetailVo();
        GarOrderDriverVo orderVo = baseMapper.queryOrderByTelWithType(user.getGarUserTel(), orderId, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
        vo.setHandleFlag(true);
        BeanUtils.copyProperties(orderVo, vo);
        // 获取图片
        List<GarOrderImage> imageAll = new ArrayList<>();
        List<GarOrderImage> currentImageList = garOrderImageService.list(new LambdaQueryWrapper<GarOrderImage>()
                .eq(GarOrderImage::getGarOrderId, orderId)
                .eq(GarOrderImage::getGarOrderImageType, GlobalStatus.GarOrderStatus.IMAGE_TYPE_CURRENT.getValue()));
        imageAll.addAll(garOrderImageService.list(qwi));
        imageAll.addAll(currentImageList);
        for (GarOrderImage image : imageAll) {
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_CURRENT.getValue().equals(image.getGarOrderImageType())) {
                vo.getCurrentImages().add(image.getGarOrderImageUrl());
            }
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_PUT_ON.getValue().equals(image.getGarOrderImageType())) {
                vo.getPutOnImages().add(image.getGarOrderImageUrl());
            }
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_PUT_DOWN.getValue().equals(image.getGarOrderImageType())) {
                vo.getPutDownImages().add(image.getGarOrderImageUrl());
            }
        }
        // 获取车辆信息
        LambdaQueryWrapper<GarOrderCar> qwc = new LambdaQueryWrapper<>();
        qwc.eq(GarOrderCar::getGarOrderId, orderVo.getGarOrderId());
        List<GarOrderCar> carList = garOrderCarService.list(qwc);
        vo.setGarCarInfoList(carList);

        List<GarOrderMatchDisposal> disposals = garOrderMatchDisposalService.queryDisposalListByOrderId(orderId);
        if (CollectionUtil.isNotEmpty(disposals)) {
            Set<String> tels = disposals.stream().map(GarOrderMatchDisposal::getGarOrderDisposalTel).collect(Collectors.toSet());
            vo.setDisposalSites(queryDisposalSiteVo(tels));
        }

        return vo;
    }

    /***
     *
     * 根据电话号码查询处置场所信息
     * @author liujun
     * @date 2024/6/18 11:31
     * @param tels
     * @return java.util.List<com.trash.garbage.pojo.vo.DisposalSiteVo>
     */
    private List<DisposalSiteVo> queryDisposalSiteVo(Collection<String> tels) {
        if (CollectionUtils.isEmpty(tels)) {
            return Collections.emptyList();
        }
        List<DisposalSiteEntity> entities = disposalSiteService.queryDisposalSiteByTelPhone(tels);
        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }
        return entities.stream().map(en -> {
            if (Objects.isNull(en)) {
                return null;
            }
            DisposalSiteVo vo = new DisposalSiteVo();
            BeanUtils.copyProperties(en, vo);
           // vo.setLongitude(en.getLongitude());
            return vo;
        }).filter(obj -> Objects.nonNull(obj)).collect(Collectors.toList());
    }

    private OrderDetailVo getOrderDetailVoResponsible(String id, GarUser user) {
        GarOrder order = this.getById(id);
        LambdaQueryWrapper<GarOrderImage> qwi = new LambdaQueryWrapper<>();
        qwi.eq(GarOrderImage::getGarOrderId, id);
        OrderDetailVo vo = new OrderDetailVo();
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())) {
            vo.setHandleFlag(true);
        }
        BeanUtils.copyProperties(order, vo);
        // 获取图片
        List<GarOrderImage> imageList = garOrderImageService.list(qwi);
        for (GarOrderImage image : imageList) {
            if (GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue().equals(image.getGarOrderImageType())) {
                vo.getCurrentImages().add(image.getGarOrderImageUrl());
            }
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_PUT_ON.getValue().equals(image.getGarOrderImageType())) {
                vo.getPutOnImages().add(image.getGarOrderImageUrl());
            }
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_PUT_DOWN.getValue().equals(image.getGarOrderImageType())) {
                vo.getPutDownImages().add(image.getGarOrderImageUrl());
            }
        }
        // 获取车辆信息
        LambdaQueryWrapper<GarOrderCar> qwc = new LambdaQueryWrapper<>();
        qwc.eq(GarOrderCar::getGarOrderId, order.getGarOrderId());
        List<GarOrderCar> carList = garOrderCarService.list(qwc);
        vo.setGarCarInfoList(carList);

        List<GarOrderMatchDisposal> disposals = garOrderMatchDisposalService.queryDisposalListByOrderId(id);
        if (CollectionUtil.isNotEmpty(disposals)) {
            Set<String> tels = disposals.stream().map(GarOrderMatchDisposal::getGarOrderDisposalTel).collect(Collectors.toSet());
            vo.setDisposalSites(queryDisposalSiteVo(tels));
        }


        return vo;
    }

    @Override
    public PageInfo queryOrderList(Integer type, Integer evaluateFlag, Integer pageNo, Integer pageSize) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        GarUser user = garUserService.getById(userId);
        // 用户
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription())) {
            LambdaQueryWrapper<GarOrder> qw = new LambdaQueryWrapper<>();
            qw.orderByDesc(GarOrder::getGarCreateTime, GarOrder::getGarOrderHandlerStatus);
            qw.eq(GarOrder::getGarOrderUserId, userId);
            PageHelper.startPage(pageNo, pageSize);
            // 待清运 || 清运中 || 已完成 || 待评价
            if (GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                qw.eq(GarOrder::getGarCancelFlag, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue())
                        .eq(GarOrder::getGarOrderHandlerStatus, type);
                if (evaluateFlag != null) {
                    qw.eq(GarOrder::getGarEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue())
                            .eq(GarOrder::getGarTimeOutFlag, GlobalStatus.GarOrderStatus.ORDER_TIME_OUT_FLAG_NO.getValue());
                }
                List<GarOrder> orderList = list(qw);
                PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
                return pageInfo;
            }

            // 全部
            if (GlobalStatus.GarOrderStatus.ALL_ORDER.getValue().equals(type)) {
                List<GarOrder> orderList = list(qw);
                PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
                return pageInfo;
            }
        }
        // 驾驶员
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription())) {
            PageHelper.startPage(pageNo, pageSize);
            if (GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                List<GarOrderDriverVo> orderList = baseMapper.queryDriverOrderListByTelWithType(user.getGarUserTel(), type, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                PageInfo<GarOrderDriverVo> pageInfo = new PageInfo<GarOrderDriverVo>(orderList, pageSize);
                return pageInfo;
            }
            // 全部
            if (GlobalStatus.GarOrderStatus.ALL_ORDER.getValue().equals(type)) {
                List<GarOrderDriverVo> orderList = baseMapper.queryDriverOrderListByTelWithType(user.getGarUserTel(), null, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                PageInfo<GarOrderDriverVo> pageInfo = new PageInfo<GarOrderDriverVo>(orderList, pageSize);
                return pageInfo;
            }
        }
        // 企业负责人
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())) {
            PageHelper.startPage(pageNo, pageSize);
            LambdaQueryWrapper<GarOrder> qw = new LambdaQueryWrapper<>();
            qw.orderByDesc(GarOrder::getGarCreateTime, GarOrder::getGarOrderHandlerStatus);
            qw.eq(GarOrder::getGarOrderCompanyTel, user.getGarUserTel());
            // 待清运 || 清运中 || 已完成 || 待评价
            if (GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                qw.eq(GarOrder::getGarCancelFlag, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue())
                        .eq(GarOrder::getGarOrderHandlerStatus, type);
                if (evaluateFlag != null) {
                    qw.eq(GarOrder::getGarHandlerEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue())
                            .eq(GarOrder::getGarTimeOutFlag, GlobalStatus.GarOrderStatus.ORDER_TIME_OUT_FLAG_NO.getValue());
                }
                List<GarOrder> orderList = list(qw);
                orderList=queryHaveEvaluateOfClient(orderList,GlobalStatus.GarOrderStatus.EVALUATE_TYPE_COMPANY.getValue());
                PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
                return pageInfo;
            }
            // 全部
            if (GlobalStatus.GarOrderStatus.ALL_ORDER.getValue().equals(type)) {
                List<GarOrder> orderList = baseMapper.selectList(qw);
                orderList =queryHaveEvaluateOfClient(orderList,GlobalStatus.GarOrderStatus.EVALUATE_TYPE_COMPANY.getValue());
                PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
                return pageInfo;
            }
        }
        // 处置场所
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription())) {
            PageHelper.startPage(pageNo, pageSize);
            if (GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                List<GarOrderDisposalVo> orderList = baseMapper.queryDisposalOrderListByTelWithType(user.getGarUserTel(), type, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                PageInfo<GarOrderDisposalVo> pageInfo = new PageInfo<GarOrderDisposalVo>(orderList, pageSize);
                return pageInfo;
            }
        }
        return null;
    }

    /***
     * 查询有无评价信息
     *
     * @author liujun
     * @date 2024/6/21 9:08
     * @param orders 订单数据
     */
    private List<GarOrder> queryHaveEvaluateOfClient(List<GarOrder> orders, Integer type) {
        if (CollectionUtils.isEmpty(orders)) {
            return orders;
        }
        Set<String> orderIds = orders.stream().map(GarOrder::getGarOrderId).collect(Collectors.toSet());
        List<GarOrderEvaluate> garOrderEvaluates = garOrderEvaluateService.countIdGroupByOrderId(orderIds, type);
        if (CollectionUtils.isEmpty(garOrderEvaluates)) {
            return orders;
        }

        return orders.stream().map(o -> {
            if(Objects.nonNull(o)){
                Optional<GarOrderEvaluate>  optional = garOrderEvaluates.stream().filter(go->Objects.equals(go.getGarOrderId(),o.getGarOrderId())).findFirst();
                if(optional.isPresent()){
                    o.setHaveEvaluateOfClient(optional.get().getCountTheNumber()>0?1:0);
                }
            }
            return o;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateOrder(OrderUpdateDto dto) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        GarUser user = garUserService.getById(userId);
        // 处理用户订单 居民用户 | 企业负责人
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())
                || user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription())) {
            return handlerOrderStatus(dto, user);
        }
        // 处理分发订单 驾驶员
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription())) {
            // TODO 驾驶员
            return handlerDispatchOrderStatus(dto, user);
        }
        //
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription())) {
            // TODO 处理场所负责人
            return handlerDisposalSiteOrderStatus(dto, user);
        }
        throw new BizException(ResultCode.CODE_500);

    }

    private String handlerDisposalSiteOrderStatus(OrderUpdateDto dto, GarUser user) {
        // 完成订单
        GarOrder order = getById(dto.getGarOrderId());
        // TODO 发送短信  通知企业和用户 修改订单状态为完成 disposal 和 handler表的状态一起修改
        String message = "您的清运订单已完成,可前往小程序进行评价,感谢您的使用。";
        smsUtils.sendMessage(order.getGarOrderContactTel(), message);
        smsUtils.sendMessage(order.getGarOrderCompanyTel(), "您的清运订单已完成,详情可在小程序查看。");
        successOrder(order);
        redisCache.deleteObject(order.getGarOrderId());
        // TODO 用户消息通知 订单菜单消息
        userOrderMessageSend(order, message);
        return "当前订单已完成";
    }

    private boolean checkCode(String code, String orderId, String userId) {
        if (StringUtils.isNotBlank(code)) {
            String validCode = redisCache.getCacheMapValue(orderId, userId);
            return code.equals(validCode);
        }
        return false;
    }


    @Deprecated
    private String handlerDispatchOrderStatus(OrderUpdateDto dto, GarUser user) {
        GarOrderDriverVo order = baseMapper.queryOrderByTelWithType(user.getGarUserTel(), dto.getGarOrderId(), GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
        String tel = user.getGarUserTel();
        // 公司所属 待清运- 》 清运中
        // 接受订单的时候把自己的id更新到handler表中
        if (order.getGarOrderHandlerStatus().equals(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue())
                || GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(dto.getHandleType())) {
            LambdaUpdateWrapper<GarOrderMatchHandler> uw = new LambdaUpdateWrapper<>();
            uw.eq(GarOrderMatchHandler::getGarOrderId, dto.getGarOrderId())
                    .eq(GarOrderMatchHandler::getGarOrderHandlerTel, tel)
                    .set(GarOrderMatchHandler::getGarOrderHandlerStatus, GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue())
                    .set(GarOrderMatchHandler::getGarOrderHandlerId, user.getGarUserId());
            handlerService.update(uw);
            return "已接受订单";
        }
        throw new BizException(ResultCode.CODE_500);
    }

    private String handlerOrderStatus(OrderUpdateDto dto, GarUser user) {
        GarOrder order = getById(dto.getGarOrderId());
        // 取消订单公用
        if (GlobalStatus.GarOrderStatus.CANCEL_FLAG_YES.getValue().equals(dto.getGarCancelFlag())) {
            LambdaUpdateWrapper<GarOrder> uw = new LambdaUpdateWrapper<>();
            uw.set(GarOrder::getGarCancelFlag, dto.getGarCancelFlag())
                    .eq(GarOrder::getGarOrderId, dto.getGarOrderId())
                    .set(GarOrder::getGarReason, dto.getGarReason());
            update(uw);
            // TODO 短信提醒  公司 | 居民
            String tel = GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription().equals(user.getGarUserType()) ?
                    order.getGarOrderCompanyTel() : order.getGarOrderContactTel();
            String message = GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription().equals(user.getGarUserType()) ?
                    "您的清运订单已取消,详情可在小程序查看" : "企业拒单";
            smsUtils.sendMessage(tel, message);
            // TODO 用户消息通知 订单菜单消息
            userOrderMessageSend(order, message);
            return "订单取消成功";
        }
        // 用户修改
        else if (GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription().equals(user.getGarUserType()) && dto.getUpdated()) {
            // TODO 待优化   可能出现线程安全 需要上锁
            if (order.getGarOrderScanHandlerFlag().equals(GlobalStatus.GarOrderStatus.SCAN_HANDLER_YES.getValue())) {
                throw new BizException(ResultCode.CODE_400, "当前订单无法修改,因为已有驾驶员确认");
            }
            // 删除之前的车辆数
            LambdaQueryWrapper<GarOrderCar> qw = new LambdaQueryWrapper<>();
            qw.eq(GarOrderCar::getGarOrderId, dto.getGarOrderId());
            garOrderCarService.remove(qw);
            // 保存车辆信息
            List<OrderDto.CarInfo> garCarInfoList = dto.getGarCarInfoList();
            List<GarOrderCar> garOrderCars = new ArrayList<>();
            for (OrderDto.CarInfo carInfo : garCarInfoList) {
                for (int index = 0; index < carInfo.getGarOrderCarNumber(); index++) {
                    GarOrderCar car = new GarOrderCar();
                    car.setGarOrderCarType(carInfo.getGarOrderCarType());
                    car.setGarOrderId(dto.getGarOrderId());
                    car.setContainerVolume(carInfo.getContainerVolume());
                    car.setCarId(carInfo.getId());
                    car.setGarOrderCarUserType(GlobalStatus.GarOrderStatus.REAL_CAR_TYPE.getValue());
                    garOrderCars.add(car);
                }
            }
            garOrderCarService.saveBatch(garOrderCars);
            order.setGarRealCarCount(garOrderCars.size());
            updateById(order);
            // TODO  发送短信用户修改订单了
            String message = "您的清运订单有修改,请及时查看并处理!";
            smsUtils.sendMessage(dto.getGarOrderCompanyTel(), message);
            // TODO 用户消息通知 订单菜单消息
            userOrderMessageSend(order, message);
            return "修改成功";
        }
        // 企业负责人 清运-》完成
        else if (GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription().equals(user.getGarUserType())) {
            // 公司所属 待清运- 》 清运中
            if (order.getGarOrderHandlerStatus().equals(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue())
                    || GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(dto.getHandleType())) {
                LambdaUpdateWrapper<GarOrder> uw = new LambdaUpdateWrapper<>();
                uw.eq(GarOrder::getGarOrderId, dto.getGarOrderId())
                        .set(GarOrder::getGarOrderHandlerStatus, GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue())
                        .set(GarOrder::getGarOrderCompanyUserId, user.getGarUserId());
                update(uw);
                // TODO 短信提醒
                String message = "运输公司已接受订单号为 " + order.getGarOrderId() + " 的订单。";
                smsUtils.sendMessage(order.getGarOrderContactTel(), message);
                // TODO 用户消息通知 订单菜单消息
                userOrderMessageSend(order, message);
                return "已接受订单";
            }
            // 企业负责人 清运中 ==》已完成
            if (GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(order.getGarOrderHandlerStatus())
                    && GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(dto.getHandleType())) {
                LambdaUpdateWrapper<GarOrder> uw = new LambdaUpdateWrapper<>();
                uw.eq(GarOrder::getGarOrderId, dto.getGarOrderId())
                        .set(GarOrder::getGarOrderHandlerStatus, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue())
                        .set(GarOrder::getGarHandlerEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue())
                        .set(GarOrder::getGarEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue());
                update(uw);
                smsUtils.sendMessage(order.getGarOrderContactTel(), "您的清运订单已完成,可前往小程序进行评价,感谢您的使用");
                smsUtils.sendMessage(order.getGarOrderCompanyTel(), "您的清运订单已完成,详情可在小程序查看。");
                // 更新disposal
                LambdaUpdateWrapper<GarOrderMatchDisposal> uwd = new LambdaUpdateWrapper<>();
                uwd.eq(GarOrderMatchDisposal::getGarOrderId, dto.getGarOrderId())
                        .set(GarOrderMatchDisposal::getGarOrderDisposalStatus, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
                disposalService.update(uwd);
                // 更新handler
                LambdaUpdateWrapper<GarOrderMatchHandler> uwh = new LambdaUpdateWrapper<>();
                uwh.eq(GarOrderMatchHandler::getGarOrderId, dto.getGarOrderId())
                        .set(GarOrderMatchHandler::getGarOrderHandlerStatus, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
                handlerService.update(uwh);
            }
            // TODO 短信提醒
            String message = "运输公司已完成订单号为 " + order.getGarOrderId() + " 的订单。";
            smsUtils.sendMessage(order.getGarOrderContactTel(), message);
            // TODO 用户消息通知 订单菜单消息
            userOrderMessageSend(order, message);
            return "订单已完成";
        }

        throw new BizException(ResultCode.CODE_400);
    }

    private void userOrderMessageSend(GarOrder order, String message) {
        GarUserOrderMessage guom = new GarUserOrderMessage();
        guom.setGarMessageState(GlobalStatus.GarUserStatusEnum.ORDER_MESSAGE_UNREAD.getStatus());
        guom.setGarContent(message);
        guom.setGarUserId(order.getGarCreateBy());
        guom.setGarUserTel(order.getGarOrderContactTel());
        orderMessageService.save(guom);
    }

    @Override
    public String uploadImageUrlByType(UploadDto dto) {
        List<GarOrderImage> garOrderImages = new ArrayList<>(dto.getImageUrls().size());
        for (String imageUrl : dto.getImageUrls()) {
            GarOrderImage orderImage = new GarOrderImage();
            orderImage.setGarOrderId(dto.getGarOrderId());
            orderImage.setGarOrderImageUrl(imageUrl);
            orderImage.setGarOrderImageType(dto.getType());
            garOrderImages.add(orderImage);
        }
        garOrderImageService.saveBatch(garOrderImages);
        return "上传成功!";
    }

    @Override
    public String evaluateOrder(EvaluateDto dto) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        GarUser user = garUserService.getById(userId);
        GarOrder order = getById(dto.getOrderId());
        if (GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(order.getGarOrderHandlerStatus())) {
            evaluate(dto, order, user);
        }
        return "已评价";
    }

    @Override
    public List<GarOrder> queryOrderListByGarOrder(GarOrder garOrder) {
        LambdaQueryWrapper<GarOrder> qw = createQueryWrapper(garOrder);
        return list(qw);
    }

    private LambdaQueryWrapper<GarOrder> createQueryWrapper(GarOrder garOrder) {
        return new LambdaQueryWrapper<GarOrder>()
                .eq(StringUtils.isNotEmpty(garOrder.getGarOrderAddress()), GarOrder::getGarOrderAddress, garOrder.getGarOrderAddress())
                .eq(!Objects.isNull(garOrder.getGarCancelFlag()), GarOrder::getGarCancelFlag, garOrder.getGarCancelFlag())
                .eq(!Objects.isNull(garOrder.getGarOrderHandlerStatus()), GarOrder::getGarOrderHandlerStatus, garOrder.getGarOrderHandlerStatus())
                .eq(!Objects.isNull(garOrder.getGarEvaluateFlag()), GarOrder::getGarEvaluateFlag, garOrder.getGarEvaluateFlag());
    }

    @Override
    public PageInfo queryOrderListByGarOrderPage(OrderWebDto dto) {
        LambdaQueryWrapper<GarOrder> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotEmpty(dto.getGarOrderCompanyName()), GarOrder::getGarOrderCompanyName, dto.getGarOrderCompanyName())
                .eq(dto.getGarOrderHandlerStatus() != null, GarOrder::getGarOrderHandlerStatus, dto.getGarOrderHandlerStatus())
                .eq(dto.getGarCancelFlag() != null, GarOrder::getGarCancelFlag, dto.getGarCancelFlag());
        List<GarOrder> list = list(qw);
        PageInfo<GarOrder> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public OrderDetailVo queryOrderWebDetail(String id) {
        GarOrder order = this.getById(id);
        LambdaQueryWrapper<GarOrderImage> qwi = new LambdaQueryWrapper<>();
        qwi.eq(GarOrderImage::getGarOrderId, id);
        OrderDetailVo vo = new OrderDetailVo();
        List<DriverVo> driverVos = null;
        BeanUtils.copyProperties(order, vo);
        List<GarOrderImage> imageList = garOrderImageService.list(qwi);
        for (GarOrderImage image : imageList) {
            if (GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue().equals(image.getGarOrderImageType())) {
                vo.getCurrentImages().add(image.getGarOrderImageUrl());
            }
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_PUT_ON.getValue().equals(image.getGarOrderImageType())) {
                vo.getPutOnImages().add(image.getGarOrderImageUrl());
            }
            if (GlobalStatus.GarOrderStatus.IMAGE_TYPE_PUT_DOWN.getValue().equals(image.getGarOrderImageType())) {
                vo.getPutDownImages().add(image.getGarOrderImageUrl());
            }
        }
        if (StringUtils.isNotEmpty(vo.getGarOrderHandlerId())) {
            GarUser handleUser = garUserService.getById(vo.getGarOrderHandlerId());
            DriverVo driverVo = new DriverVo();
            driverVo.setPhoneNo(handleUser.getGarUserTel());
            driverVos = driverService.selectDriverList(driverVo);
            if (CollectionUtil.isNotEmpty(driverVos)) {
                vo.setGarOrderHandleName(driverVos.get(0).getName());
                vo.setGarOrderHandleTel(driverVos.get(0).getPhoneNo());
            }
        }
        // 获取车辆信息
        LambdaQueryWrapper<GarOrderCar> qwc = new LambdaQueryWrapper<>();
        qwc.eq(GarOrderCar::getGarOrderId, id);
        List<GarOrderCar> carList = garOrderCarService.list(qwc);
        vo.setGarCarInfoList(carList);
        return vo;
    }

    @Override
    public PageInfo queryEnterpriseList(TransportationEnterprise enterprise) {
        // 1)支持选择企业“所属区域”(长沙市内的)展示区域内所有企业
        // 2)支持选择车辆“车辆类型”展示有该车辆类型的企业
        // TODO 车辆类型暂时不考虑
        List<TransportationEnterprise> list = transportationEnterpriseService.selectTransportationEnterpriseList(enterprise);
        Integer pageNum = ServletUtils.getParameterToInt("pageNum");
        Integer pageSize = ServletUtils.getParameterToInt("pageSize");
        Integer orderByColumn = ServletUtils.getParameterToInt("orderByColumn");
        Comparator<TransportationEnterpriseVo> comparator;
        if (1 == orderByColumn) {
            comparator = Comparator.comparing(TransportationEnterpriseVo::getCleanNumber);
        } else if (2 == orderByColumn) {
            comparator = Comparator.comparing(TransportationEnterpriseVo::getScore);
        } else {
            comparator = Comparator.comparing(TransportationEnterpriseVo::getDistance);
        }
        // 企业id为空说明没有公司
        List<Long> enterpriseIds = list.stream().map(TransportationEnterprise::getId).collect(Collectors.toList());
        List<GarOrder> orderList = baseMapper.queryCleanNumberByEnterpriseIds(enterpriseIds, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
        List<GarOrderEvaluate> evaluateList = garOrderEvaluateService.queryEvaluateByEnterpriseIds(enterpriseIds, GlobalStatus.GarOrderStatus.EVALUATE_TYPE_COMPANY.getValue());
        Map<String, List<GarOrderEvaluate>> evaluateMap = new HashMap<>();
        for (GarOrderEvaluate garOrderEvaluate : evaluateList) {
            List<GarOrderEvaluate> evaluate = evaluateMap.get(garOrderEvaluate.getGarCompanyId());
            if (CollectionUtil.isEmpty(evaluate)) {
                evaluateMap.put(garOrderEvaluate.getGarCompanyId(), new ArrayList<>(Arrays.asList(garOrderEvaluate)));
            } else {
                evaluate.add(garOrderEvaluate);
            }
        }
        // 获取当前选中地址计算距离
        LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
        qw.eq(GarAddress::getGarUserId, SecurityUtils.getLoginUser().getUser().getUserId())
                .eq(GarAddress::getGarUserDefault, GlobalStatus.GarAddressStatus.CURRENT_ADDRESS.getValue());
        GarAddress address = garAddressService.getOne(qw);

        Stream<TransportationEnterpriseVo> stream = list.stream().map(item -> {
            TransportationEnterpriseVo vo = new TransportationEnterpriseVo();
            BeanUtils.copyProperties(item, vo);
            List<GarOrderEvaluate> evaluate = evaluateMap.get(String.valueOf(item.getId()));
            handleCleanNumber(vo, orderList);
            handleScore(vo, evaluate);
            handleDistance(vo, address);
            return vo;
        });
        List<TransportationEnterpriseVo> voList;
        if (orderByColumn != 0) {
            // 降序
            voList = stream.sorted(comparator.reversed()).collect(Collectors.toList());
        } else {
            voList = stream.sorted(comparator).collect(Collectors.toList());
        }
        int total = voList.size();
        int remainder = total % pageSize;
        int currentPage = pageNum > 0 ? (pageNum - 1) * pageSize : pageNum * pageSize;
        // 怕页码超出界限了 超出界限就通过currenPage (3 * 10) > total (25) ? currentPage (20) - (pageSize (10) - remainder (3)) : currentPage
        int startPage = currentPage > total ? currentPage - (pageSize - remainder) : currentPage;
        int endPage = Math.min(startPage + pageSize, total);
        PageInfo<TransportationEnterpriseVo> pageInfo = new PageInfo<>();
        pageInfo.setList(voList.subList(startPage, endPage));
        pageInfo.setTotal(total);
        return pageInfo;
    }


    private void handleDistance(TransportationEnterpriseVo vo, GarAddress address) {
        if(Objects.isNull(vo) || StringUtils.isEmpty(vo.getOfficeAddressGps()) || StringUtils.indexOf(vo.getOfficeAddressGps(),",")==-1 || Objects.isNull(address)){
            vo.setDistance(9999999);
            return;
        }
        String[] params = vo.getOfficeAddressGps().split(",");
        double distance = calculateDistance(Double.parseDouble(params[1]), Double.parseDouble(params[0]), address.getGarLatitude(), address.getGarLongitude());
        vo.setDistance(distance);
    }

    private double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        // 将经纬度转换为弧度
        double lat1Rad = Math.toRadians(lat1);
        double lon1Rad = Math.toRadians(lon1);
        double lat2Rad = Math.toRadians(lat2);
        double lon2Rad = Math.toRadians(lon2);

        // 应用 Haversine 公式计算距离
        double dlon = lon2Rad - lon1Rad;
        double dlat = lat2Rad - lat1Rad;
        double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +
                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                        Math.sin(dlon / 2) * Math.sin(dlon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double radius = 6371; // 地球平均半径(单位:公里)
        double distance = radius * c;
        return distance;
    }

    @Override
    public List<GarOrderEvaluate> queryEvaluateDetail(String orderId) {
        //首先查询最近20条数据
        LambdaQueryWrapper<GarOrderEvaluate> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderEvaluate::getGarOrderId, orderId).orderByDesc(GarOrderEvaluate::getGarCreateTime);
        PageHelper.startPage(1, 20, Boolean.FALSE);
        List<GarOrderEvaluate> evaluateList = garOrderEvaluateService.list(qw);

        if (CollectionUtils.isNotEmpty(evaluateList)) {
            //再正序排列评价
            evaluateList.sort(new Comparator<GarOrderEvaluate>() {
                @Override
                public int compare(GarOrderEvaluate o1, GarOrderEvaluate o2) {

                    return Objects.isNull(o1.getGarCreateTime()) || Objects.isNull(o2.getGarCreateTime()) ? 0 : o1.getGarCreateTime().compareTo(o2.getGarCreateTime());
                }
            });
        }
        return evaluateList;
    }

    @Override
    public void dispatchDriverOrders(DispatchDto dto) {
        GarOrder order = getById(dto.getGarOrderId());
        List<GarOrderMatchHandler> handlerList = new ArrayList<>(dto.getDispatchList().size());
        // 已分配 继续下发
//        if (order.getGarOrderScanHandlerFlag().equals(GlobalStatus.GarOrderStatus.SCAN_HANDLER_YES.getValue())) {
        LambdaQueryWrapper<GarOrderMatchHandler> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderMatchHandler::getGarOrderId, order.getGarOrderId());
        Map<String, GarOrderMatchHandler> handlerMap = handlerService.list(qw).stream().collect(Collectors.toMap(item -> item.getGarOrderHandlerTel(), item -> item));
        for (DispatchDto.DispatchDetail dispatchDetail : dto.getDispatchList()) {
            if (handlerMap.containsKey(dispatchDetail.getTel())) {
                continue;
            }
            GarOrderMatchHandler handler = getGarOrderMatchHandler(order, dispatchDetail);
            handlerList.add(handler);
        }
//        }
//        else {
//            for (DispatchDto.DispatchDetail detail : dto.getDispatchList()) {
//                GarOrderMatchHandler handler = getGarOrderMatchHandler(order, detail);
//                handlerList.add(handler);
//            }
//        }
        handlerService.saveBatch(handlerList);
        List<String> tels = handlerList.stream().map(GarOrderMatchHandler::getGarOrderHandlerTel).collect(Collectors.toList());
        // TODO 短信通知
        smsUtils.sendMessage(tels, "您有新的清运任务!请打开小程序查看当前任务。");
    }

    private GarOrderMatchHandler getGarOrderMatchHandler(GarOrder order, DispatchDto.DispatchDetail detail) {
        GarOrderMatchHandler handler = new GarOrderMatchHandler();
        handler.setGarOrderHandlerTel(detail.getTel());
        handler.setGarOrderHandlerName(detail.getName());
        handler.setGarHandlerCarCode(detail.getCarCode());
        handler.setGarCancelFlag(order.getGarCancelFlag());
        handler.setGarOrderId(order.getGarOrderId());
        handler.setGarOrderHandlerStatus(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue());
        handler.setGarOrderHandlerCompanyName(order.getGarOrderCompanyName());
        handler.setGarOrderHandlerCompanyId(order.getGarOrderCompanyId());
        handler.setGarOrderContainerVolume(detail.getGarOrderContainerVolume());
//        handler.setGarOrderHandlerId(detail.getId());
        handler.setGarOrderStatus(GlobalStatus.GarOrderStatus.DISPATCH_HANDLE_NEW.getValue());
        return handler;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DispatchDriverVo> queryDispatch(String orderId) {
//        GarOrder order = getById(orderId);
//        order.setGarOrderMatchFlag(GlobalStatus.GarOrderStatus.MATCH_YES.getValue());
//        updateById(order);
        String tel = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        TransportationEnterprise enterprise = new TransportationEnterprise();
        enterprise.setServicePhone(tel);
        List<TransportationEnterprise> enterprises = transportationEnterpriseService.selectTransportationEnterpriseList(enterprise);
        if(CollectionUtils.isEmpty(enterprises)){
            return Collections.emptyList();
        }

       List<GarOrderCar> garOrderCars = garOrderCarService.queryByOrderId(orderId);
        if(CollectionUtils.isEmpty(garOrderCars)){
            return Collections.emptyList();
        }

        Set<String> containerVolumees = garOrderCars.stream().map(GarOrderCar::getContainerVolume).collect(Collectors.toSet());
        // 选中的司机
        List<DispatchDriverVo> voList = handlerService.queryDriverListWithDispatchStatus(orderId, enterprises.get(0).getId(),containerVolumees);
        return voList;
    }

    @Override
    public List<GarOrderMatchHandler> queryOrderHandlerStatus(String orderId) {
        List<GarOrderMatchHandler> list =
                handlerService.list(new LambdaQueryWrapper<GarOrderMatchHandler>()
                        .eq(GarOrderMatchHandler::getGarOrderId, orderId));
        return list;
    }

    @Override
    public PageInfo querySearchHistory() {
        // 查询历史搜索记录 最多返回8个历史搜索
        PageHelper.startPage(1, 8);
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<GarSearchHistory> qw = new LambdaQueryWrapper<>();
        qw.eq(GarSearchHistory::getGarCreateBy, userId);
        List<GarSearchHistory> list = garSearchHistoryService.list(qw);
        PageInfo<GarSearchHistory> page = new PageInfo<>(list);
        return page;
    }

    @Override
    public void dispatchDisposalOrders(DisposalDispatchDto dto) {
        // TODO
        GarOrder order = getById(dto.getGarOrderId());
        List<GarOrderMatchDisposal> disposalList = new ArrayList<>(dto.getDispatchList().size());
        LambdaQueryWrapper<GarOrderMatchDisposal> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderMatchDisposal::getGarOrderId, order.getGarOrderId());
        Map<String, GarOrderMatchDisposal> handlerMap = disposalService.list(qw).stream().collect(Collectors.toMap(item -> item.getGarOrderDisposalTel(), item -> item));
        for (DisposalDispatchDto.DispatchDetail detail : dto.getDispatchList()) {
            if (handlerMap.containsKey(detail.getTel())) {
                continue;
            }
            GarOrderMatchDisposal disposal = getGarOrderMatchDisposal(order, detail);
            disposalList.add(disposal);
        }
        disposalService.saveBatch(disposalList);
        List<String> tels = disposalList.stream().map(GarOrderMatchDisposal::getGarOrderDisposalTel).collect(Collectors.toList());
        // TODO 短信通知
        smsUtils.sendMessage(tels, "您有新的驻场任务!请打开小程序查看驻场任务。");
    }

    private GarOrderMatchDisposal getGarOrderMatchDisposal(GarOrder order, DisposalDispatchDto.DispatchDetail detail) {
        GarOrderMatchDisposal disposal = new GarOrderMatchDisposal();
        disposal.setGarOrderDisposalTel(detail.getTel());
        disposal.setGarOrderDisposalName(detail.getName());
        disposal.setGarOrderId(order.getGarOrderId());
        disposal.setGarOrderDisposalCompanyName(detail.getCompanyName());
        disposal.setGarOrderDisposalName(detail.getName());
        disposal.setGarOrderDisposalCompanyId(detail.getCompanyId());
//        disposal.setGarOrderDisposalId(detail.getId());
        disposal.setGarOrderDisposalStatus(GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue());
        return disposal;
    }

    @Override
    public List<DispatchDisposalVo> queryDisposalDispatch(String orderId) {
        // TODO
        // String tel = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        // 选中的司机处理场所
        List<DispatchDisposalVo> voList = disposalService.queryDisposalListWithDispatchStatus(orderId);
        return voList;
    }

    @Override
    public ScanDriverDetailVo checkValidCode(String validCode) {
        if (StringUtils.isNotBlank(validCode)) {
            String[] params = validCode.split(",");
            String orderId = params[0];
            String userId = params[1];
            // TODO check code
            if (checkCode(validCode, orderId, userId)) {
                ScanDriverDetailVo vo = baseMapper.queryDriverDetailByTelWithOrderId(orderId, userId);
                return vo;
            }
        }

        throw new BizException(ResultCode.CODE_400, "二维码验证不通过");
    }

    @Override
    public String askTransport(AskTransportDto dto) {
        // TODO 判断是否运载完毕  已经到预估趟次则不在生成验证码
        String orderId = dto.getGarOrderId();
        // 查询当前运载几趟  如果全部运输完毕则发送成功短信
        LambdaQueryWrapper<GarOrderMatchAsk> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderMatchAsk::getGarOrderId, dto.getGarOrderId());
        int transportCount = askService.list(qw).size();
        GarOrder order = getById(orderId);
        if (transportCount <= order.getGarRealCarCount() - 1) {
            // 第一次的话需要修改订单状态为已扫码
            if (order.getGarOrderScanHandlerFlag().equals(GlobalStatus.GarOrderStatus.SCAN_HANDLER_NO.getValue())) {
                order.setGarOrderScanHandlerFlag(GlobalStatus.GarOrderStatus.SCAN_HANDLER_YES.getValue());
                updateById(order);
            }
            GarOrderMatchAsk ask = new GarOrderMatchAsk();
            BeanUtils.copyProperties(dto, ask);
            matchAskService.save(ask);
            // 保存图片url
            List<GarOrderImage> imageList = new ArrayList<>(dto.getFillImageList().size());
            for (String fillImageUrl : dto.getFillImageList()) {
                GarOrderImage image = new GarOrderImage();
                image.setGarOrderImageType(GlobalStatus.GarOrderStatus.IMAGE_TYPE_FILL_CAR.getValue());
                image.setGarOrderId(orderId);
                image.setGarOrderImageUrl(fillImageUrl);
                image.setGarRemark(ask.getGarId());
                imageList.add(image);
            }
            garOrderImageService.saveBatch(imageList);
            // TODO 删除验证码
            redisCache.deleteObject(orderId, dto.getGarOrderHandlerId());
            return "当前趟次记录成功";
        }
        throw new BizException(ResultCode.CODE_400, "当前记录无效,已完成所有趟次!");
    }

    private void successOrder(GarOrder order) {
        order.setGarOrderHandlerStatus(GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
        order.setGarHandlerEvaluateFlag(GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue());
        order.setGarEvaluateFlag(GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue());
        updateById(order);
        // 更新disposal
        LambdaUpdateWrapper<GarOrderMatchDisposal> uwd = new LambdaUpdateWrapper<>();
        uwd.eq(GarOrderMatchDisposal::getGarOrderId, order.getGarOrderId())
                .set(GarOrderMatchDisposal::getGarOrderDisposalStatus, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
        disposalService.update(uwd);
        // 更新handler
        LambdaUpdateWrapper<GarOrderMatchHandler> uwh = new LambdaUpdateWrapper<>();
        uwh.eq(GarOrderMatchHandler::getGarOrderId, order.getGarOrderId())
                .set(GarOrderMatchHandler::getGarOrderHandlerStatus, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
        handlerService.update(uwh);
    }


    @Override
    public OrderDetailTransportVo queryOrderTransportDetail(String id) {
        // 根据当前订单id查订单数据 - 查扫码趟次数据
        OrderDetailTransportVo vo = baseMapper.queryOrderTransportDetail(id);
        vo.setCurrentImages(new ArrayList<>());
        // 全景图片
        LambdaQueryWrapper<GarOrderImage> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderImage::getGarOrderId, id)
                .in(GarOrderImage::getGarOrderImageType,
                        Arrays.asList(GlobalStatus.GarOrderStatus.IMAGE_TYPE_FILL_CAR.getValue(), GlobalStatus.GarOrderStatus.IMAGE_TYPE_CURRENT.getValue()));
        List<GarOrderImage> imageList = garOrderImageService.list(qw);
        for (GarOrderImage image : imageList) {
            // 现场照片
            if (image.getGarOrderImageType().equals(GlobalStatus.GarOrderStatus.IMAGE_TYPE_CURRENT.getValue())) {
                vo.getCurrentImages().add(image.getGarOrderImageUrl());
            }
            // 全景图片
            else {
                for (OrderDetailTransportVo.TransportDetail detail : vo.getTransportDetails()) {
                    if (detail.getGarAskId().equals(image.getGarRemark())) {
                        detail.setFillImage(image.getGarOrderImageUrl());
                        break;
                    }
                }
            }
        }
        return vo;
    }

    @Override
    public GarOrderMatchAskVo scanDetail(String askId) {
        GarOrderMatchAsk ask = askService.getById(askId);
        GarOrderMatchAskVo vo = new GarOrderMatchAskVo();
        BeanUtils.copyProperties(ask, vo);
        // 图片url
        LambdaQueryWrapper<GarOrderImage> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderImage::getGarOrderId, ask.getGarOrderId())
                .eq(GarOrderImage::getGarRemark, askId)
                .eq(GarOrderImage::getGarOrderImageType, GlobalStatus.GarOrderStatus.IMAGE_TYPE_FILL_CAR.getValue());
        List<String> fillImageList = garOrderImageService.list(qw).stream().map(GarOrderImage::getGarOrderImageUrl).collect(Collectors.toList());
        vo.setFillImageList(fillImageList);
        return vo;
    }

    @Override
    public String createHandlerQrCode(String orderId) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        // 返回验证码
        // TODO 以订单id和用户id hash key返回前端生成二维码  存放到redis中
        String code = orderId + "," + userId + "," + ValidateCodeUtil.generatorCode(6);
        redisCache.setCacheMapValue(orderId, userId, code);
        return code;
    }

    @Override
    public PageInfo queryOrderMessageList(Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<GarUserOrderMessage> qw = new LambdaQueryWrapper<>();
        qw.eq(GarUserOrderMessage::getGarUserId, userId)
                .eq(GarUserOrderMessage::getGarMessageState, GlobalStatus.GarUserStatusEnum.ORDER_MESSAGE_UNREAD.getStatus());
        List<GarUserOrderMessageVo> messageVos = orderMessageService.queryMessageListByUserIdWithState(userId, GlobalStatus.GarUserStatusEnum.ORDER_MESSAGE_UNREAD.getStatus());
        PageInfo<GarUserOrderMessageVo> pageInfo = new PageInfo<>(messageVos, pageSize);
        return pageInfo;
    }

    @Override
    public String readMessage(List<String> messageIds) {
        LambdaQueryWrapper<GarUserOrderMessage> qw = new LambdaQueryWrapper<>();
        qw.in(GarUserOrderMessage::getGarId, messageIds);
        List<GarUserOrderMessage> messageList = orderMessageService.list(qw);
        List<GarUserOrderMessageHistory> historyList = messageList.stream().map(item -> {
            GarUserOrderMessageHistory history = new GarUserOrderMessageHistory();
            item.setGarMessageState(GlobalStatus.GarUserStatusEnum.ORDER_MESSAGE_READ.getStatus());
            BeanUtils.copyProperties(item, history, "garId");
            return history;
        }).collect(Collectors.toList());
        orderMessageHistoryService.saveBatch(historyList);
        // 删除数据
        orderMessageService.removeByIds(messageIds);
        return "消息确认成功";
    }

    @Override
    public Integer queryOrderMessageCount() {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<GarUserOrderMessage> qw = new LambdaQueryWrapper<>();
        qw.eq(GarUserOrderMessage::getGarUserId, userId)
                .eq(GarUserOrderMessage::getGarMessageState, GlobalStatus.GarUserStatusEnum.ORDER_MESSAGE_UNREAD.getStatus());
        int count = orderMessageService.count(qw);
        return count;
    }

    @Override
    public List<GarOrder> queryUnprocessedOrder(Integer value, Integer orderTimeOutFlag, Integer value1) {
        return baseMapper.queryUnprocessedOrder(value, orderTimeOutFlag, value1);
    }

    @Override
    public void updateTimeOutOrderStatus(List<GarOrder> timeOutList) {
        if (CollectionUtil.isNotEmpty(timeOutList)) {
            baseMapper.updateTimeOutOrderStatus(timeOutList, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue(), GlobalStatus.GarOrderStatus.ORDER_TIME_OUT_FLAG_YES.getValue());
        }
    }

    @Override
    public MyBargeVo queryBadgeByType(Integer type) {
        GarUser user = garUserService.getById(SecurityUtils.getLoginUser().getUser().getUserId());
        MyBargeVo vo = new MyBargeVo();
        // 用户
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription())) {
            if (GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                LambdaQueryWrapper<GarOrder> qw = new LambdaQueryWrapper<>();
                qw.eq(GarOrder::getGarOrderUserId, user.getGarUserId())
                        .eq(GarOrder::getGarOrderHandlerStatus, type)
                        .eq(GarOrder::getGarCancelFlag, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                if (GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                    qw.eq(GarOrder::getGarEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue())
                            .eq(GarOrder::getGarTimeOutFlag, GlobalStatus.GarOrderStatus.ORDER_TIME_OUT_FLAG_NO.getValue());
                }
                int badge = count(qw);
                vo.setBadge(badge);
                vo.setType(type);
            }
        }
        // 运输企业
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())) {
            if (GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                LambdaQueryWrapper<GarOrder> qw = new LambdaQueryWrapper<>();
                qw.eq(GarOrder::getGarOrderCompanyTel, user.getGarUserTel())
                        .eq(GarOrder::getGarOrderHandlerStatus, type)
                        .eq(GarOrder::getGarCancelFlag, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                if (GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                    qw.eq(GarOrder::getGarHandlerEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_NO.getValue())
                            .eq(GarOrder::getGarTimeOutFlag, GlobalStatus.GarOrderStatus.ORDER_TIME_OUT_FLAG_NO.getValue());
                }
                int badge = count(qw);
                vo.setBadge(badge);
                vo.setType(type);
            }
        }
        // 驾驶员
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription())) {
            if (GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                Integer badge = baseMapper.queryDriverOrderListByTelWithTypeCount(user.getGarUserTel(), type, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                vo.setBadge(badge);
                vo.setType(type);
            }
        }
        // 处理场所
        else if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription())) {
            if (GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(type)
                    || GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(type)) {
                Integer badge = baseMapper.queryDisposalOrderListByTelWithTypeCount(user.getGarUserTel(), type, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
                vo.setType(type);
                vo.setBadge(badge);
            }
        }
        return vo;
    }

    @Override
    public Long queryCarIdOfDriver(String  phone) {
        return  baseMapper.queryCompanyIdByPhone(phone);
    }



    private void handleCleanNumber(TransportationEnterpriseVo vo, List<GarOrder> orderList) {
        Long cleanNumber = 0L;
        for (GarOrder order : orderList) {
            if (vo.getId().toString().equals(order.getGarOrderCompanyId())) {
                cleanNumber = order.getCount();
            }
        }
        vo.setCleanNumber(cleanNumber.intValue());
    }

    private void handleScore(TransportationEnterpriseVo vo, List<GarOrderEvaluate> evaluate) {
        float score = 0;
        if (CollectionUtil.isNotEmpty(evaluate)) {
            for (GarOrderEvaluate orderEvaluate : evaluate) {
                score += orderEvaluate.getGarEvaluateScore();
            }
            vo.setScore(score / evaluate.size());
        } else {
            vo.setScore(score);
        }
    }

    private void evaluate(EvaluateDto dto, GarOrder order, GarUser user) {
        GarOrderEvaluate evaluate = new GarOrderEvaluate();
        evaluate.setGarOrderId(order.getGarOrderId());
        evaluate.setGarEvaluateContent(dto.getContent());
        evaluate.setGarEvaluateScore(dto.getScore());
        evaluate.setGarCompanyId(order.getGarOrderCompanyId());
        evaluate.setGarEvaluateTarget(dto.getEvaluateType());
        garOrderEvaluateService.save(evaluate);
        // 修改订单评价状态
        LambdaUpdateWrapper<GarOrder> uw = new LambdaUpdateWrapper<>();
        uw.eq(GarOrder::getGarOrderId, order.getGarOrderId())
                .set(dto.getEvaluateType().equals(GlobalStatus.GarOrderStatus.EVALUATE_TYPE_COMPANY.getValue()), GarOrder::getGarEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_YES.getValue())
                .set(dto.getEvaluateType().equals(GlobalStatus.GarOrderStatus.EVALUATE_TYPE_USER.getValue()), GarOrder::getGarHandlerEvaluateFlag, GlobalStatus.GarOrderStatus.EVALUATE_ORDER_YES.getValue());
        update(uw);
    }
}