GarOrderServiceImpl.java 36 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
package com.trash.garbage.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.trash.common.utils.ServletUtils;
import com.trash.enterprise.domain.TransportationEnterprise;
import com.trash.enterprise.service.ITransportationEnterpriseService;
import com.trash.garbage.custom.BizException;
import com.trash.garbage.global.ResultCode;
import com.trash.garbage.pojo.domain.*;
import com.trash.garbage.pojo.dto.*;
import com.trash.garbage.pojo.vo.DispatchDriverVo;
import com.trash.garbage.pojo.vo.GarOrderDriverVo;
import com.trash.garbage.pojo.vo.TransportationEnterpriseVo;
import com.trash.garbage.service.*;
import com.trash.garbage.utils.SMSUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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.utils.SecurityUtils;
import com.trash.common.utils.bean.BeanUtils;
import com.trash.driver.domain.vo.DriverVo;
import com.trash.driver.service.IDriverService;
import com.trash.garbage.global.GlobalStatus;
import com.trash.garbage.mapper.GarOrderMapper;
import com.trash.garbage.pojo.vo.OrderDetailVo;
import cn.hutool.core.collection.CollectionUtil;

import javax.annotation.Resource;

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


    @Resource
    private SMSUtils smsUtils;

    @Autowired
    private GarOrderImageService garOrderImageService;

    @Autowired
    private GarAddressService garAddressService;

    @Autowired
    private ITransportationEnterpriseService transportationEnterpriseService;

    @Autowired
    private GarOrderEvaluateService garOrderEvaluateService;

    @Autowired
    private GarSearchHistoryService garSearchHistoryService;

    @Autowired
    private GarUserService garUserService;

    @Autowired
    private IDriverService driverService;

    @Autowired
    private ITransportationEnterpriseService enterpriseService;

    @Autowired
    private IDriverService iDriverService;

    @Autowired
    private GarOrderMatchHandlerService handlerService;

    @Autowired
    private GarOrderCarService garOrderCarService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveOrder(OrderDto dto) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        GarOrder order = new GarOrder();
        BeanUtils.copyBeanProp(order, dto);
        order.setGarOrderUserId(userId);
        order.setGarOrderHandlerStatus(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue());
        order.setGarCancelFlag(GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
        order.setGarOrderMatchFlag(GlobalStatus.GarOrderStatus.MATCH_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.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());
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())
                || user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription())) {
            return getOrderDetailVoResponsible(id, user);
        }
        //  订单分发获取 处理人员
        if (user.getGarUserType().equals(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription())) {
            return getOrderDetailVoDriver(id, user);
        }
        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.copyBeanProp(vo, orderVo);
        // 获取图片
        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);
        return vo;
    }

    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);
            // 防止其他人员处理订单
            if (!order.getGarOrderHandlerStatus().equals(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue()) && !order.getGarOrderHandlerId().equals(user.getGarUserId())) {
                vo.setHandleFlag(false);
            }
        }
        BeanUtils.copyBeanProp(vo, order);
        // 获取图片
        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);
        return vo;
    }

    @Override
    public PageInfo queryOrderList(Integer type, 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.orderByAsc(GarOrder::getGarUpdateTime, GarOrder::getGarOrderHandlerStatus);
            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::getGarOrderUserId, userId)
                        .eq(GarOrder::getGarCancelFlag, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue())
                        .eq(GarOrder::getGarOrderHandlerStatus, type);
                List<GarOrder> orderList = list(qw);
                PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
                return pageInfo;
            }

            // 全部
            if (GlobalStatus.GarOrderStatus.ALL_ORDER.getValue().equals(type)) {
                qw.eq(GarOrder::getGarOrderUserId, userId);
                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.queryOrderListByTelWithType(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.queryOrderListByTelWithType(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<GarOrder>();
            qw.eq(GarOrder::getGarOrderCompanyTel, user.getGarUserTel())
                    .orderByDesc(GarOrder::getGarOrderAgreementTime);
            // 全部
            if (GlobalStatus.GarOrderStatus.ALL_ORDER.getValue().equals(type)) {
                List<GarOrder> orderList = baseMapper.selectList(qw);
                PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
                return pageInfo;
            }
            qw.eq(GarOrder::getGarOrderHandlerStatus, type)
                    .eq(GarOrder::getGarCancelFlag, GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
            List<GarOrder> orderList = baseMapper.selectList(qw);
            PageInfo<GarOrder> pageInfo = new PageInfo<GarOrder>(orderList, pageSize);
            return pageInfo;
        }
        return null;
    }

    @Override
    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);
        }

        throw new BizException(ResultCode.CODE_500);

    }

    @Deprecated
    private String handlerDispatchOrderStatus(OrderUpdateDto dto, GarUser user) {
//        GarOrder order = getById(dto.getGarOrderId());
        GarOrderDriverVo order = baseMapper.queryOrderByTelWithType(user.getGarUserTel(), dto.getGarOrderId(), GlobalStatus.GarOrderStatus.CANCEL_FLAG_NO.getValue());
        // 取消订单
        if (GlobalStatus.GarOrderStatus.CANCEL_FLAG_YES.getValue().equals(dto.getGarCancelFlag())) {
            LambdaUpdateWrapper<GarOrderMatchHandler> uw = new LambdaUpdateWrapper<>();
            uw.set(GarOrderMatchHandler::getGarCancelFlag, dto.getGarCancelFlag())
                    .set(GarOrderMatchHandler::getGarReason, dto.getGarReason())
                    .eq(GarOrderMatchHandler::getGarOrderId, dto.getGarOrderId());
            handlerService.update(uw);
            return "已取消订单";
        } else {
            // 公司所属 待清运- 》 清运中
            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, user.getGarUserTel())
                        .set(GarOrderMatchHandler::getGarOrderStatus, GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue());
                handlerService.update(uw);
                return "已接受订单";
            }
            // 运输驾驶员 清运中 ==》已完成
            if (GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue().equals(order.getGarOrderHandlerStatus())
                    && GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue().equals(dto.getHandleType())) {
                LambdaUpdateWrapper<GarOrderMatchHandler> uw = new LambdaUpdateWrapper<>();
                uw.eq(GarOrderMatchHandler::getGarOrderId, dto.getGarOrderId())
                        .eq(GarOrderMatchHandler::getGarOrderHandlerTel, user.getGarUserTel())
                        .set(GarOrderMatchHandler::getGarOrderStatus, GlobalStatus.GarOrderStatus.SUCCESS_ORDER.getValue());
                handlerService.update(uw);
            }
            return "订单已完成";
        }
    }

    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())
                    .set(GarOrder::getGarReason, dto.getGarReason())
                    .eq(GarOrder::getGarOrderId, dto.getGarOrderId());
            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);
            return "订单取消成功";
        }
        // 企业负责人
        else {
            // 公司所属 待清运- 》 清运中
            if (order.getGarOrderHandlerStatus().equals(GlobalStatus.GarOrderStatus.NEW_ORDER.getValue())
                    || GlobalStatus.GarOrderStatus.NEW_ORDER.getValue().equals(dto.getHandleType())) {
                if (StringUtils.isNotEmpty(order.getGarOrderHandlerId())) {
                    throw new BizException(ResultCode.CODE_500, "订单已经接受了");
                }
                LambdaUpdateWrapper<GarOrder> uw = new LambdaUpdateWrapper<>();
                uw.eq(GarOrder::getGarOrderId, dto.getGarOrderId())
                        .set(GarOrder::getGarOrderHandlerStatus, GlobalStatus.GarOrderStatus.ACTIVE_ORDER.getValue())
                        .set(GarOrder::getGarOrderHandlerId, user.getGarUserId());
                update(uw);
                // TODO 短信提醒
                smsUtils.sendMessage(order.getGarOrderContactTel(), "运输公司已接受订单号为 " + order.getGarOrderId() + " 的订单。");
                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);
            }
            // TODO 短信提醒
            smsUtils.sendMessage(order.getGarOrderContactTel(), "运输公司已完成订单号为 " + order.getGarOrderId() + " 的订单。");
            return "订单已完成";
        }
    }

    @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 "已评价";
    }

    public static void main(String[] args) {
        System.out.println(convert("PAYPALISHIRING", 3));
    }

    public static String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        List<StringBuilder> list = new ArrayList<>(numRows);
        for (int i = 0; i < numRows; i++) {
            list.add(new StringBuilder());
        }
        int space = 1;
        int x = -1;
        // 0 1 2 - 2 1 0 - 0 1 2    ||    0 1 2 3 2 1 0 1 2 3  || 0 1 2 3 4 5 6 7 8 9
        for (int i = 0; i < s.length(); i++) {
            space = space + x;
            list.get(space).append(s.charAt(i));
            if (i % (numRows - 1) == 0) {
                x = -x;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            sb.append(list.get(i));
        }
        return sb.toString();
    }

    @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.copyBeanProp(vo, order);
        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);
        }

        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);
        List<TransportationEnterpriseVo> voList = 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;
                })
                // 降序
                .sorted(comparator.reversed())
                .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) {
        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) {
        LambdaQueryWrapper<GarOrderEvaluate> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderEvaluate::getGarOrderId, orderId);
        List<GarOrderEvaluate> evaluateList = garOrderEvaluateService.list(qw);
        return evaluateList;
    }

    @Override
    public void dispatchOrder(DispatchDto dto) {
        GarOrder order = getById(dto.getGarOrderId());
        List<GarOrderMatchHandler> handlerList = new ArrayList<>(dto.getDispatchList().size());
        int realCarCount = 0;
        // 每次下发统计选中驾驶员更新实际派车数量
        // 已分配 继续下发
        if (order.getGarOrderMatchFlag().equals(GlobalStatus.GarOrderStatus.MATCH_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);
            }
            realCarCount = handlerMap.size() + handlerList.size();
        } else {
            for (DispatchDto.DispatchDetail detail : dto.getDispatchList()) {
                GarOrderMatchHandler handler = getGarOrderMatchHandler(order, detail);
                handlerList.add(handler);
            }
            realCarCount = handlerList.size();
        }
        handlerService.saveBatch(handlerList);
        order.setGarOrderMatchFlag(GlobalStatus.GarOrderStatus.MATCH_YES.getValue());
        order.setGarRealCarCount(realCarCount);
        updateById(order);
    }

    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(order.getGarOrderHandlerStatus());
        handler.setGarOrderHandlerCompanyName(order.getGarOrderCompanyName());
        handler.setGarOrderHandlerCompanyId(order.getGarOrderCompanyId());
        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);
        // 选中的司机
        LambdaQueryWrapper<GarOrderMatchHandler> qw = new LambdaQueryWrapper<>();
        qw.eq(GarOrderMatchHandler::getGarOrderId, orderId);
        List<DispatchDriverVo> voList = handlerService.queryDriverListWithDispatchStatus(orderId, enterprises.get(0).getId());
        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;
    }

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