package cn.iocoder.yudao.module.inspection.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.common.service.InspectionNoticeService;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.appBase.controller.admin.InspectionSocket;
import cn.iocoder.yudao.module.constant.InspectionConstants;
import cn.iocoder.yudao.module.custom.entity.CustomerMain;
import cn.iocoder.yudao.module.custom.service.CustomerMainService;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.inspection.query.OrderTableQuery;
import cn.iocoder.yudao.module.inspection.vo.DlInspectionWorkNodeVo;
import cn.iocoder.yudao.module.partner.entity.PartnerCustomerInfo;
import cn.iocoder.yudao.module.partner.service.IPartnerCustomerInfoService;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.payment.service.IOrderInfoDetailService;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.SendSmsUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.entity.*;
import cn.iocoder.yudao.module.inspection.mapper.InspectionInfoMapper;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.inspection.utils.PhoneValidator;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.payment.entity.OrderInfoDetail;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

import static cn.iocoder.yudao.framework.common.config.CommonStr.USER_TYPE_CUS;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-13
 */
@Service
public class InspectionInfoServiceImpl extends ServiceImpl<InspectionInfoMapper, InspectionInfo> implements IInspectionInfoService {
    @Autowired
    private AdminUserService userService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private IPartnerWorkerService workerService;
    @Autowired
    private IShopInspectionGoodsService goodsService;
    @Autowired
    private InspectionGoodsSkuService skuService;
    @Autowired
    @Lazy
    private AppInspectionPartnerService appInspectionPartnerService;
    @Autowired
    private IPartnerCustomerInfoService customerInfoService;
    @Autowired
    private IOrderInfoDetailService orderInfoDetailService;
    @Autowired
    private IDelOrderInfoService delInspectionOrderService;
    @Autowired
    private IDelInspectionInfoService delInspectionInfoService;
    @Autowired
    private IInspectionWorkNodeService workNodeService;
    @Autowired
    private InspectionStepInfoService inspectionStepInfoService;
    @Autowired
    private InspectionNoticeService noticeService;
    @Resource
    private CustomerMainService customerMainService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private InspectionSocket inspectionSocket;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private InspectionLeadRecordService inspectionLeadRecordService;
    @Resource
    @Lazy
    private DlInspectionProjectService projectService;
    @Autowired
    private FileService fileService;
    @Autowired
    private IInspectionAppointmentService inspectionAppointmentService;
    @Autowired
    private InspectionMeetCarOrderService inspectionMeetCarOrderService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public InspectionInfo selectInspectionInfoById(Long id) {
        return baseMapper.selectInspectionInfoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param inspectionInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public IPage<InspectionInfo> selectInspectionInfoList(Page<InspectionInfo> page, InspectionInfo inspectionInfo) {
        return baseMapper.selectInspectionInfoList(page, inspectionInfo);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param inspectionInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertInspectionInfo(InspectionInfo inspectionInfo) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();

        if (ObjectUtils.isEmpty(inspectionInfo.getInspectionWorkNodes())) {
            throw new RuntimeException("请选择检测项目");
        }
        //当前登陆人 就是检测人
        AdminUserDO workerUser = userService.getUser(loginUser.getId());
        String buyName = StringUtils.isNotEmpty(inspectionInfo.getBuyName()) ? inspectionInfo.getBuyName() : "未知客户";
        String buyPhone = StringUtils.isNotEmpty(inspectionInfo.getBuyPhone()) ? inspectionInfo.getBuyPhone() : StringUtils.isNotEmpty(inspectionInfo.getBuyName()) ? inspectionInfo.getBuyName() : "无";
        AdminUserDO user = userService.getUserByUsername(buyPhone, null, USER_TYPE_CUS);

        if (ObjectUtils.isEmpty(user)) {
            //新增用户
            UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
            userSaveReqVO.setNickname(buyName);
            userSaveReqVO.setUsername(buyPhone);
            userSaveReqVO.setMobile(buyPhone);
            userSaveReqVO.setUserType(USER_TYPE_CUS);
            userSaveReqVO.setPassword("123456");
            Long uid = userService.createUser(userSaveReqVO);
            inspectionInfo.setUserId(uid);
            user = new AdminUserDO();
            user.setId(uid);
            user.setNickname(buyName);
            user.setUsername(buyPhone);
            user.setMobile(buyPhone);
        } else {
            inspectionInfo.setUserId(user.getId());
        }
        InspectionGoodsSku sku = skuService.getById(inspectionInfo.getSkuId());
        if (ObjectUtil.isEmpty(sku)) {
            throw new RuntimeException("商品不存在");
        }
        ShopInspectionGoods goods = goodsService.getById(sku.getGoodsId());
//        ShopMallPartners partner = appInspectionPartnerService.getById(goods.getPartnerId());

        OrderInfo orderInfo = new OrderInfo();

        //判断有没有传预约信息
        if (ObjectUtil.isNotNull(inspectionInfo.getAppointmentId())) {
            //根据预约id查询预约信息
            InspectionAppointment appointment1 = inspectionAppointmentService.getById(inspectionInfo.getAppointmentId());
            if (ObjectUtil.isNotEmpty(appointment1.getOrderId())) {
                // 需要核销订单表
                // 查询订单
                orderInfo = orderInfoService.getById(appointment1.getOrderId());
            } else {
//                orderInfo.setPartnerId(partners.getPartnerId());
                orderInfo.setGoodsId(Long.parseLong(goods.getId().toString()));
                orderInfo.setGoodsTitle(goods.getTitle());
                orderInfo.setGoodsType("jc");
                orderInfo.setGoodNum(1);
                orderInfo.setSkuId(Long.parseLong(sku.getId().toString()));
                orderInfo.setSkuName(sku.getSkuName());
                orderInfo.setGoodsPrice(goods.getPrice());
                orderInfo.setStartTime(new Date());
                orderInfo.setOrderTime(new Date());
                orderInfo.setOrderType("jc");
                orderInfo.setUserId(user.getId());
                orderInfo.setRealName(user.getNickname());
                orderInfo.setIsOnline("0");
                orderInfo.setPhonenumber(user.getMobile());
//                orderInfo.setPartnerName(partner.getPartnerName());
                orderInfo.setOrderNo("线下订单-" + System.currentTimeMillis());
                //赊账的情况
                orderInfo.setOrderStatus("0");
                orderInfoService.save(orderInfo);

                //修改预约信息表的orderId
                InspectionAppointment appointment = new InspectionAppointment();
                appointment.setOrderId(orderInfo.getId());
                inspectionAppointmentService.update(Wrappers.<InspectionAppointment>lambdaUpdate()
                        .eq(InspectionAppointment::getId, inspectionInfo.getAppointmentId())
                        .set(InspectionAppointment::getOrderId, orderInfo.getId()));
            }

            //修改订单的核销时间
            orderInfoService.update(Wrappers.<OrderInfo>lambdaUpdate()
                    .eq(OrderInfo::getId, orderInfo.getId())
                    .set(OrderInfo::getValidationTime, new Date()));
        } else {
//            orderInfo.setPartnerId(partners.getPartnerId());
            orderInfo.setGoodsId(Long.parseLong(goods.getId().toString()));
            orderInfo.setGoodsTitle(goods.getTitle());
            orderInfo.setGoodsType("jc");
            orderInfo.setGoodNum(1);
            orderInfo.setSkuId(Long.parseLong(sku.getId().toString()));
            orderInfo.setSkuName(sku.getSkuName());
            orderInfo.setGoodsPrice(goods.getPrice());
            orderInfo.setStartTime(new Date());
            orderInfo.setOrderTime(new Date());
            orderInfo.setOrderType("jc");
            orderInfo.setUserId(user.getId());
            orderInfo.setRealName(user.getNickname());
            orderInfo.setIsOnline("0");
            orderInfo.setPhonenumber(user.getMobile());
//            orderInfo.setPartnerName(partner.getPartnerName());
            orderInfo.setOrderNo("线下订单-" + System.currentTimeMillis());
            //赊账的情况
            orderInfo.setOrderStatus("0");
            orderInfoService.save(orderInfo);

            //修改预约信息表的orderId
            InspectionAppointment appointment = new InspectionAppointment();
            appointment.setOrderId(orderInfo.getId());
            inspectionAppointmentService.update(Wrappers.<InspectionAppointment>lambdaUpdate()
                    .eq(InspectionAppointment::getId, inspectionInfo.getAppointmentId())
                    .set(InspectionAppointment::getOrderId, orderInfo.getId()));
        }
        inspectionInfo.setInspectionOrderId(orderInfo.getId());
//        inspectionInfo.setPartnerId(partners.getPartnerId());
        inspectionInfo.setWorkerName(workerUser.getNickname());
        inspectionInfo.setWorkerPhone(workerUser.getMobile());
        if (ObjectUtil.isNull(inspectionInfo.getStartTime())) {
            inspectionInfo.setStartTime(new Date());
        }
        inspectionInfo.setCategoryId(goods.getGoodsCategoryId());

        if (ObjectUtil.isNotNull(inspectionInfo.getAdditionalRecording()) && inspectionInfo.getAdditionalRecording() == 1) {
            inspectionInfo.setStatus("1");
            inspectionInfo.setIsPass("1");
            inspectionInfo.setEndTime(inspectionInfo.getStartTime());
        } else {
            inspectionInfo.setStatus("0");
        }
        inspectionInfo.setWorkId(workerUser.getId());
        inspectionInfo.setYear(DateUtil.format(inspectionInfo.getStartTime(), "yyyy"));
        inspectionInfo.setMonth(DateUtil.format(inspectionInfo.getStartTime(), "yyyy-MM"));
        inspectionInfo.setDay(DateUtil.format(inspectionInfo.getStartTime(), "yyyy-MM-dd"));
        try {
            //开始检测短信发送
            // 获取当前日期和时间
            LocalDateTime currentTime = LocalDateTime.now();

            // 定义指定格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日H:mm分");

            // 将当前时间转换为指定格式
            String formattedTime = currentTime.format(formatter);
            if (PhoneValidator.isValid(orderInfo.getPhonenumber())) {
                SendSmsUtil.sendMsgCommon(new String[]{formattedTime}, orderInfo.getPhonenumber(), "1400852709", "机动车管家小程序", "2389282");
            }
        } catch (Exception ignored) {
            log.error(ignored.getMessage());
        }
        //增加客户信息
        LambdaQueryWrapper<PartnerCustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PartnerCustomerInfo::getUserId, orderInfo.getUserId()).last("limit 1");
        PartnerCustomerInfo customerInfo = customerInfoService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(customerInfo)) {
            customerInfo = new PartnerCustomerInfo();
            customerInfo.setUserId(user.getId());
            customerInfo.setCustomerPhone(user.getMobile());
            customerInfo.setCustomerName(user.getNickname());
            customerInfo.setSex("0");
            customerInfo.setUserAge(user.getUserAge());
            // 设置客户来源
            try {
                customerInfoService.insertPartnerCustomerInfo(customerInfo);
            } catch (Exception ignored) {

            }

        }
        //追加订单明细记录
        orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(), "线下订单创建", new Date(), 0L, "1"));
        //默认当前流程的顺序为1
        inspectionInfo.setNowOrderNum(1);
        if (ObjectUtil.isNotNull(inspectionInfo.getAdditionalRecording()) && inspectionInfo.getAdditionalRecording() == 1) {
            //设置制证完成
            inspectionInfo.setMakeCert("1");
        }
        //添加检测工单
        baseMapper.insert(inspectionInfo);
        //补充检测流程
        List<InspectionWorkNode> inspectionWorkNodes = inspectionInfo.getInspectionWorkNodes();
        boolean save = false;
        //将检测工单流程补充检测工单id
        //如果是补录就将节点设置为已完成
        if (ObjectUtil.isNotNull(inspectionInfo.getAdditionalRecording()) && inspectionInfo.getAdditionalRecording() == 1) {
            inspectionWorkNodes.stream().forEach(inspectionWorkNode -> {
                //检测工单id
                inspectionWorkNode.setInspectionInfoId(inspectionInfo.getId());
                inspectionWorkNode.setCreateTime(inspectionInfo.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                inspectionWorkNode.setUpdateTime(inspectionInfo.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

                inspectionWorkNode.setStatus("2");
                inspectionWorkNode.setType("1");
            });

            /*获取所有的检测项目 填充步骤*/
            List<InspectionStepInfo> inspectionStepInfos = new ArrayList<>();
            InspectionStepInfo inspectionStepInfoStrt = new InspectionStepInfo();
            inspectionStepInfoStrt.setTitle("检测开始");
            inspectionStepInfoStrt.setInspectionInfoId(Integer.parseInt(String.valueOf(inspectionInfo.getId())));
            inspectionStepInfoStrt.setCreator(Integer.parseInt(String.valueOf(loginUser.getId())));
            inspectionStepInfoStrt.setUpdater(Integer.parseInt(String.valueOf(loginUser.getId())));
            inspectionStepInfoStrt.setCreateTime(inspectionInfo.getStartTime());
            inspectionStepInfoStrt.setUpdateTime(inspectionInfo.getStartTime());
            inspectionStepInfos.add(inspectionStepInfoStrt);

            for (InspectionWorkNode inspectionWorkNode : inspectionWorkNodes) {
                InspectionStepInfo inspectionStepInfo = new InspectionStepInfo();
                inspectionStepInfo.setTitle(inspectionWorkNode.getProjectName() + "项目检测完成");
                inspectionStepInfo.setInspectionInfoId(Integer.parseInt(String.valueOf(inspectionInfo.getId())));
                inspectionStepInfo.setCreator(Integer.parseInt(String.valueOf(inspectionWorkNode.getDealUserId())));
                inspectionStepInfo.setUpdater(Integer.parseInt(String.valueOf(inspectionWorkNode.getDealUserId())));
                inspectionStepInfo.setCreateTime(inspectionInfo.getStartTime());
                inspectionStepInfo.setUpdateTime(inspectionInfo.getStartTime());

                inspectionStepInfos.add(inspectionStepInfo);
            }
            InspectionStepInfo inspectionStepInfoEnd = new InspectionStepInfo();
            inspectionStepInfoEnd.setTitle("检测结束");
            inspectionStepInfoEnd.setInspectionInfoId(Integer.parseInt(String.valueOf(inspectionInfo.getId())));
            inspectionStepInfoEnd.setCreator(Integer.parseInt(String.valueOf(loginUser.getId())));
            inspectionStepInfoEnd.setUpdater(Integer.parseInt(String.valueOf(loginUser.getId())));
            inspectionStepInfoEnd.setCreateTime(inspectionInfo.getStartTime());
            inspectionStepInfoEnd.setUpdateTime(inspectionInfo.getStartTime());
            inspectionStepInfos.add(inspectionStepInfoEnd);
            save = inspectionStepInfoService.saveBatch(inspectionStepInfos);
        } else {
            inspectionWorkNodes.stream().forEach(inspectionWorkNode -> {
                //检测工单id
                inspectionWorkNode.setInspectionInfoId(inspectionInfo.getId());
                //设置开始时间与更新时间为null
                inspectionWorkNode.setCreateTime(null);
                inspectionWorkNode.setUpdateTime(null);
                //将节点状态设置为未开始
                inspectionWorkNode.setStatus("0");
            });
            //检测步骤表插入检测开始
            InspectionStepInfo stepInfo = new InspectionStepInfo();
            stepInfo.setInspectionInfoId(Integer.parseInt(String.valueOf(inspectionInfo.getId())));
            stepInfo.setTitle("检测开始");
            stepInfo.setCreateTime(new Date());
            stepInfo.setCreator(Integer.parseInt(String.valueOf(loginUser.getId())));
            save = inspectionStepInfoService.save(stepInfo);
        }
        // 判断meetCarId是否有值
        if (StrUtil.isNotEmpty(inspectionInfo.getMeetCarId())) {
            // 如果有值修改步骤表中的id
            inspectionStepInfoService.update(Wrappers.<InspectionStepInfo>lambdaUpdate()
                    .eq(InspectionStepInfo::getInspectionInfoId, inspectionInfo.getMeetCarId())
                    .set(InspectionStepInfo::getInspectionInfoId, inspectionInfo.getId()));

            //修改接车订单表中的检测主键id
            inspectionMeetCarOrderService.update(Wrappers.<InspectionMeetCarOrder>lambdaUpdate()
                    .eq(InspectionMeetCarOrder::getId, inspectionInfo.getMeetCarId())
                    .set(InspectionMeetCarOrder::getInspectionInfoId, inspectionInfo.getId()));

            // 修改工单表的是否接车为已接车
            update(Wrappers.<InspectionInfo>lambdaUpdate()
                    .eq(InspectionInfo::getId, inspectionInfo.getId())
                    .set(InspectionInfo::getIsMeetCar, 1));

            // 查询接车标
            InspectionMeetCarOrder inspectionMeetCarOrder = inspectionMeetCarOrderService.getById(inspectionInfo.getMeetCarId());
            // 判断接车类型是否是业务接车
            if (inspectionMeetCarOrder.getMeetType() == 2) {
                // 给对应的业务经理发送消息
                String message = String.format(InspectionConstants.INSPECTION_NOTICE_TEMPLATE_BUSINESS_MANAGER_MEET_CAR_ORDER_CREATE, inspectionInfo.getBuyName() == null ? inspectionInfo.getBuyPhone() : inspectionInfo.getBuyName());
                noticeService.sentMessage(inspectionMeetCarOrder.getMeetManId(), message);
            }
        }

        workNodeService.saveBatch(inspectionWorkNodes);
//        //获取第一个节点的角色
//        Integer roleId = inspectionWorkNodes.get(0).getRoleId();
        List<Integer> roleIds = new ArrayList<>();
        /*获取所有的角色id*/
        if (CollUtil.isNotEmpty(inspectionWorkNodes)) {
            roleIds = inspectionWorkNodes.stream().map(inspectionWorkNode -> inspectionWorkNode.getRoleId()).collect(Collectors.toList());
        }
        //根据角色id获取所有用户
        List<UserDTO> listByUserId = roleService.getListByUserIds(roleIds);
        List<Long> ids = listByUserId.stream().map(UserDTO::getId).collect(Collectors.toList());
        if (ObjectUtil.isNotNull(inspectionInfo.getLeadManId())) {
            ids.add(inspectionInfo.getLeadManId());
        }
        if (ObjectUtil.isNotNull(inspectionInfo.getMeetManId())) {
            ids.add(inspectionInfo.getMeetManId());
        }
        //给ids去重
        ids = ids.stream().distinct().collect(Collectors.toList());
        // 获取当前共单引车员的id
        if (CollUtil.isNotEmpty(ids) && ObjectUtil.isNull(inspectionInfo.getAdditionalRecording())) {
            for (Long id : ids) {
                inspectionSocket.sendMessage("接工单", id.toString());
            }
        }


        return save ? 1 : 0;
    }

    @TenantIgnore
    private AdminUserDO getAdminUserDO(String buyPhone) {
        AdminUserDO user = userService.getUserByMobileTenantIgnore(buyPhone);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void settleAccounts(Long InspectionId) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        InspectionInfo info = baseMapper.selectById(InspectionId);
        OrderInfo orderInfo = orderInfoService.getById(info.getInspectionOrderId());
        orderInfo.setValidationTime(new Date());
        orderInfo.setValidationUserId(loginUser.getId());
        orderInfo.setValidationRealName(user.getNickname());
        orderInfo.setEndTime(new Date());
        orderInfo.setOrderStatus("2");
        orderInfo.setPayTime(new Date());
        orderInfoService.updateById(orderInfo);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param inspectionInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateInspectionInfo(InspectionInfo inspectionInfo) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = appInspectionPartnerService.shopInfo();
        LambdaQueryWrapper<PartnerWorker> workerQueryWrapper = new LambdaQueryWrapper<>();
        workerQueryWrapper.eq(PartnerWorker::getUserId, loginUser.getId()).eq(PartnerWorker::getPartnerId, partners.getPartnerId());
//        PartnerWorker worker = workerService.getOne(workerQueryWrapper);
        AdminUserDO workerUser = userService.getUser(loginUser.getId());
//        if (ObjectUtils.isNotEmpty(worker)) {
        inspectionInfo.setWorkId(workerUser.getId());
//        } else {
//            throw new Exception("请先将接待员加入员工");
//        }
        String buyName = StringUtils.isNotEmpty(inspectionInfo.getBuyName()) ? inspectionInfo.getBuyName() : "未知客户";
        String buyPhone = StringUtils.isNotEmpty(inspectionInfo.getBuyPhone()) ? inspectionInfo.getBuyPhone() : StringUtils.isNotEmpty(inspectionInfo.getBuyName()) ? inspectionInfo.getBuyName() : "无";
        AdminUserDO user = getAdminUserDO(buyPhone);
        if (ObjectUtils.isEmpty(user)) {
            //新增用户
            UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
            userSaveReqVO.setNickname(buyName);
            userSaveReqVO.setUsername(buyPhone);
            userSaveReqVO.setMobile(buyPhone);
            userSaveReqVO.setPassword("123456");
            Long uid = userService.createUser(userSaveReqVO);
            inspectionInfo.setUserId(uid);
        } else {
            inspectionInfo.setUserId(user.getId());
        }
        InspectionGoodsSku sku = skuService.getById(inspectionInfo.getSkuId());
        ShopInspectionGoods goods = goodsService.getById(sku.getGoodsId());
        inspectionInfo.setPartnerId(partners.getPartnerId());
        inspectionInfo.setWorkerName(workerUser.getNickname());
        inspectionInfo.setWorkerPhone(workerUser.getMobile());
        inspectionInfo.setCategoryId(goods.getGoodsCategoryId());
        //增加客户信息
        return baseMapper.updateById(inspectionInfo);
    }

    /**
     * 修改引车员或接车人
     *
     * @param inspectionInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLeadMan(InspectionInfo inspectionInfo) {
        Map<String, Object> info = new HashMap<>();
        if (inspectionInfo.getSourceType() == 1) {
            // 修改接车订单表
            inspectionMeetCarOrderService.update(Wrappers.<InspectionMeetCarOrder>lambdaUpdate()
                    .eq(InspectionMeetCarOrder::getId, inspectionInfo.getId())
                    .set(InspectionMeetCarOrder::getMeetManId, inspectionInfo.getMeetManId())
                    .set(InspectionMeetCarOrder::getIsMeet, 0)
                    .set(InspectionMeetCarOrder::getIsMeetPickCar, 0));

            // 查询接车订单信息
            InspectionMeetCarOrder order = inspectionMeetCarOrderService.getById(inspectionInfo.getId());
            info.put("meetManId", order.getMeetManId());
            info.put("day", order.getAppointmentDay());
            info.put("carNo", order.getCarNum());

        } else {
            int i = baseMapper.updateById(inspectionInfo);
        }
        if (ObjectUtil.isNotEmpty(inspectionInfo.getLeadManId())) {
            inspectionSocket.sendMessage("接工单", inspectionInfo.getLeadManId().toString());
        }
        if (ObjectUtil.isNotEmpty(inspectionInfo.getMeetManId())) {
            inspectionSocket.sendMessage("接工单", inspectionInfo.getMeetManId().toString());
        }
        saveLeadRecord(inspectionInfo.getId(), inspectionInfo.getMeetManId());


//        // 发送站内信
//        String msg = String.format(InspectionConstants.INSPECTION_NOTICE_TEMPLATE_ASSIGN_STAFF_MEET_CAR, info.get("day"), inspectionInfo.getCarNum());
//        noticeService.sentMessage(inspectionInfo.getLeadManId(), msg);
        return 1;
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteInspectionInfoByIds(Long id) {
        InspectionInfo info = this.getById(id);
        baseMapper.deleteInspectionInfoById(id);
        OrderInfo orderInfo = orderInfoService.getById(info.getInspectionOrderId());
        orderInfoService.removeById(info.getInspectionOrderId());
        //往回收站插入
        DelInspectionInfo delInspectionInfo = new DelInspectionInfo();
        DelOrderInfo delInspectionOrder = new DelOrderInfo();
        BeanUtils.copyProperties(info, delInspectionInfo);
        BeanUtils.copyProperties(orderInfo, delInspectionOrder);
        delInspectionInfoService.insertDelInspectionInfo(delInspectionInfo);
        delInspectionOrderService.insertDelOrderInfo(delInspectionOrder);
        return 1;
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteInspectionInfoById(Long id) {
        return baseMapper.deleteInspectionInfoById(id);
    }

    @Override
    public List<InspectionInfo> workOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime) {
        return baseMapper.workOrder(partnerId, carNum, goodsTitle, customerSource, payType, startTime, roleId, endTime);
    }

    @Override
    public IPage<InspectionInfo> pageWorkOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime, Page<InspectionInfo> page) {
        return baseMapper.pageWorkOrder(partnerId, carNum, goodsTitle, customerSource, payType, startTime, roleId, endTime, page);
    }
    @Override
    public IPage<InspectionInfo> pageWorkOrder(OrderTableQuery query, Page<InspectionInfo> page) {
        if (StringUtils.isNotEmpty(query.getDatetimeRange())) {
            query.getDatetimeRange()[0] = query.getDatetimeRange()[0] + " 00:00:00";
            query.getDatetimeRange()[1] = query.getDatetimeRange()[1] + " 23:59:59";
        }
        return baseMapper.pageWorkOrderNew(query, page);
    }

    @Override
    public List<InspectionInfo> delworkOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime) {
        return baseMapper.delworkOrder(partnerId, carNum, goodsTitle, customerSource, payType, startTime, roleId, endTime);
    }

    @Override
    public IPage<InspectionInfo> pageDelWorkOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime, Page<InspectionInfo> page) {
        return baseMapper.pageDelWorkOrder(partnerId, carNum, goodsTitle, customerSource, payType, startTime, roleId, endTime, page);
    }

    @Override
    public Map<String, Object> workOrderData(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime) {
        return baseMapper.workOrderData(partnerId, carNum, goodsTitle, customerSource, payType, startTime, roleId, endTime);
    }

    @Override
    public Map<String, Object> workOrderData(OrderTableQuery query) {
        return baseMapper.workOrderDataNew(query);
    }

    /**
     * 根据当前登陆人获取可以选择的工单
     *
     * @param page
     * @return
     */
    @Override
    public IPage<InspectionInfo> geStelectInspection(IPage page, InspectionInfo inspectionInfo) {
        //获取当前登录人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //获取当前登陆人的角色
        List<UserRoleDO> byUserId = roleService.getByUserId(loginUser.getId());
        inspectionInfo.setLeadManId(loginUser.getId());
        List<Long> roleIds = byUserId.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        if (!"1".equals(inspectionInfo.getStatus())) {
            //进行中 已完成
            inspectionInfo.setDealUserId(loginUser.getId());
        }
        return baseMapper.selectByUser(page, roleIds, inspectionInfo);
    }

    /**
     * 获取工单详情
     *
     * @return
     */
    @Override
    public DlInspectionWorkNodeVo getWorkNode(Integer inspectionId, String workNodeId) {
        //查询工单
        InspectionInfo inspectionInfo = this.getById(inspectionId);
        //根据工单id查询流程节点
        InspectionWorkNode inspectionWorkNode = workNodeService.getById(workNodeId);
        //根据工单id查询步骤
        List<InspectionStepInfo> inspectionStepInfos = inspectionStepInfoService.list(new LambdaQueryWrapper<InspectionStepInfo>()
                .eq(InspectionStepInfo::getInspectionInfoId, inspectionId));

        DlInspectionWorkNodeVo dlInspectionWorkNodeVo = new DlInspectionWorkNodeVo();
        dlInspectionWorkNodeVo.setInspectionInfo(inspectionInfo);
        dlInspectionWorkNodeVo.setNode(inspectionWorkNode);
        dlInspectionWorkNodeVo.setSteps(inspectionStepInfos);
        return dlInspectionWorkNodeVo;
    }

    /**
     * 根据工单id获取工单流程
     *
     * @param inspectionId
     * @return
     */
    @Override
    public List<InspectionWorkNode> getWeorkNodesById(Integer inspectionId) {
        return workNodeService.getWeorkNodesById(inspectionId);
    }

    /**
     * 判断app当前检测人是否有审核权限
     *
     * @return
     */
    @Override
    public Boolean isExamine(String code) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //获取当前登陆人的所有角色
        List<UserRoleDO> userRoles = roleService.getByUserId(loginUser.getId());
        List<Long> userRoleIds = userRoles.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIds);

        //判断当前角色集合中的code是否包含jcyszz
        if (CollectionUtil.isNotEmpty(roleList)) {
            List<RoleDO> filteredRoleList = roleList.stream()
                    .filter(role -> role.getCode().contains(code))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filteredRoleList)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取某个工单针对当前操作用户，某个状态的项目们
     *
     * @param id     工单ID
     * @param status 状态
     * @author 小李
     * @date 10:48 2024/12/11
     **/
    @Override
    public Map<String, String> getWorkNodeByIdAndNow(Long id, String status, Boolean flag) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        List<UserRoleDO> roles = roleService.getByUserId(userId);
        if (CollUtil.isEmpty(roles)) {
            throw exception0(500, "查询角色为空");
        }
        List<Long> roleIds = roles.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        LambdaQueryWrapper<InspectionWorkNode> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InspectionWorkNode::getInspectionInfoId, id);
        if (flag) {
            wrapper.eq(InspectionWorkNode::getStatus, status);
        }
        InspectionInfo inspectionInfo = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(inspectionInfo.getLeadManId()) || !inspectionInfo.getLeadManId().equals(userId)) {
            wrapper.in(InspectionWorkNode::getRoleId, roleIds);
        }
        List<InspectionWorkNode> workNodes = workNodeService.list(wrapper);
        if (CollUtil.isEmpty(workNodes)) {
            throw exception0(500, "没有项目需要操作");
        }
        List<String> projectIds = workNodes.stream().map(InspectionWorkNode::getProjectId).collect(Collectors.toList());
        if (CollUtil.isEmpty(projectIds)) {
            throw exception0(500, "没有项目需要操作");
        }
        List<DlInspectionProject> projects = projectService.listByIds(projectIds);
        if (CollUtil.isEmpty(projects)) {
            throw exception0(500, "没有项目需要操作");
        }
        Map<String, String> map = projects.stream().collect(Collectors.toMap(DlInspectionProject::getId, DlInspectionProject::getProjectName));
        Map<String, String> result = new HashMap<>();
        workNodes.forEach(item -> {
            result.put(item.getId(), map.get(item.getProjectId()));
        });
        return result;
    }

    /**
     * 判断是否可以修改引车员
     *
     * @param id 工单ID
     * @author 小李
     * @date 15:22 2024/12/11
     **/
    @Override
    public Boolean judgeUpdateLeadMan(Long id) {
        boolean result = true;
        InspectionInfo inspectionInfo = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(inspectionInfo)) {
            throw new RuntimeException("工单不存在");
        }
        if (!inspectionInfo.getStatus().equals("2")) {
            result = false;
        }
        if (!result) {
            List<InspectionWorkNode> list = workNodeService.list(new LambdaQueryWrapper<InspectionWorkNode>().eq(InspectionWorkNode::getInspectionInfoId, id));
            Set<String> status = list.stream().map(InspectionWorkNode::getStatus).collect(Collectors.toSet());
            if (status.contains("3")) {
                result = true;
            }
        }
        if (result) {
            result = inspectionInfo.getCreator().equals(SecurityFrameworkUtils.getLoginUserId() + "");
        }
        return result;
    }

    /**
     * 获取当前登陆人的角色列表
     *
     * @return
     */
    @Override
    public List<RoleDO> getRoleList() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //获取当前登陆人的所有角色
        List<UserRoleDO> userRoles = roleService.getByUserId(loginUser.getId());
        List<Long> userRoleIds = userRoles.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        return roleService.getRoleList(userRoleIds);
    }

    /**
     * EasyPoi 替换数据 导出 word
     *
     * @param templatePath word模板地址
     * @param filename     文件名称
     * @param data         替换参数
     * @param request
     * @param response
     */
    public String easyPoiExport(String templatePath, String filename, Map<String, Object> data, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(filename, "文件名称不能为空");
        Assert.isTrue(filename.endsWith(".docx"), "文件名称仅支持docx格式");

        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                filename = URLEncoder.encode(filename, "UTF-8");
            } else {
                filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
            }

            XWPFDocument document = WordExportUtil.exportWord07(templatePath, data);
            MultipartFile files = convertXWPFDocumentToMultipartFile(document, filename);
            filename = fileService.createFile(files.getOriginalFilename(), "", IoUtil.readBytes(files.getInputStream()));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return filename;
    }

    public static MultipartFile convertXWPFDocumentToMultipartFile(XWPFDocument document, String filename) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        document.write(bos);
        byte[] bytes = bos.toByteArray();
        return new MockMultipartFile(filename, filename, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", bytes);
    }

    /**
     * 获得不同状态的数据的数量
     *
     * @author 小李
     * @date 16:22 2024/12/18
     **/
    @Override
    public Map<String, Long> getCountByType(Integer partnerId) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);

        try {
            InspectionInfo inspectionInfo = new InspectionInfo();
//            inspectionInfo.setPartnerId(partnerId.longValue());

            // 获取当前登录人
            LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
            // 获取当前登陆人的角色
            List<UserRoleDO> byUserId = roleService.getByUserId(loginUser.getId());
            inspectionInfo.setLeadManId(loginUser.getId());
            List<Long> roleIds = byUserId.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());

            if (!"1".equals(inspectionInfo.getStatus())) {
                inspectionInfo.setDealUserId(loginUser.getId());
            }

            Map<String, Long> result = new ConcurrentHashMap<>(); // 线程安全

            // 这里 `5` 而不是 `6`，因为 i 从 `0` 开始
            CompletableFuture<Void>[] futures = new CompletableFuture[10];

            for (int i = 0; i < 10; i++) { // 改为 `0~4`
                final String status = String.valueOf(i + 1);

                // 深拷贝对象，防止多线程修改冲突
                InspectionInfo infoCopy = JSON.parseObject(JSON.toJSONString(inspectionInfo), InspectionInfo.class);
                infoCopy.setStatus(status);

//                Page<InspectionInfo> page = new Page<>(1, 10);

                futures[i] = CompletableFuture.runAsync(() -> {
                    Long count = baseMapper.countByUser(roleIds, infoCopy);
                    result.put(status, count);
                }, executor);
            }

            // 等待所有任务完成
            CompletableFuture.allOf(futures).join();

            return result;

        } catch (Exception e) {
            throw new RuntimeException("Failed to execute tasks in parallel", e);
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }

    /**
     * 接车拍照
     *
     * @param inspectionWorkNode
     */
    @Override
    @Transactional
    public Boolean meetCarPhoto(InspectionWorkNode inspectionWorkNode) {
        //图片和描述
        String remark = StrUtil.isNotEmpty(inspectionWorkNode.getRemark()) ? inspectionWorkNode.getRemark() : "";
        String dealImages = StrUtil.isNotEmpty(inspectionWorkNode.getDealImages()) ? inspectionWorkNode.getDealImages() : "";

        //存入步骤表
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(inspectionWorkNode.getMeetCarId());
        stepInfo.setTitle("接车拍照");
        stepInfo.setContent(remark);
        stepInfo.setImages(dealImages);
        stepInfo.setCreator(Math.toIntExact(SecurityFrameworkUtils.getLoginUserId()));
        stepInfo.setUpdater(Math.toIntExact(SecurityFrameworkUtils.getLoginUserId()));
        stepInfo.setCreateTime(new Date());
        stepInfo.setUpdateTime(new Date());

        inspectionStepInfoService.save(stepInfo);

        // 判断接车类型是工单表还是接车订单表
        if (Objects.equals(inspectionWorkNode.getSourceType(), InspectionConstants.INSPECTION_MEET_CAR_ORDER_IS_MEET_CAR_COMPLETE_TYPE_ORDER)) {
            //修改主表为已接车
            int update = baseMapper.update(Wrappers.<InspectionInfo>lambdaUpdate()
                    .eq(InspectionInfo::getId, inspectionWorkNode.getMeetCarId())
                    .set(InspectionInfo::getIsMeetCar, InspectionConstants.INSPECTION_MEET_CAR_ORDER_IS_MEET_CAR_YES));
        } else if (Objects.equals(inspectionWorkNode.getSourceType(), InspectionConstants.INSPECTION_MEET_CAR_ORDER_IS_MEET_CAR_COMPLETE_TYPE_MEET_CAR_ORDER)) {
            // 修改接车订单表为已接车
            inspectionMeetCarOrderService.update(Wrappers.<InspectionMeetCarOrder>lambdaUpdate()
                    .eq(InspectionMeetCarOrder::getId, inspectionWorkNode.getMeetCarId())
                    .set(InspectionMeetCarOrder::getIsMeet, InspectionConstants.INSPECTION_MEET_CAR_ORDER_IS_MEET_CAR_YES)
                    .set(InspectionMeetCarOrder::getIsMeetPickCar, InspectionConstants.INSPECTION_MEET_CAR_ORDER_IS_MEET_CAR_YES));
        }

        return true;
    }

    /**
     * 还车拍照
     *
     * @param inspectionWorkNode
     */
    @Override
    public Boolean returnCarPhoto(InspectionWorkNode inspectionWorkNode) {
        //图片和描述
        String remark = StrUtil.isNotEmpty(inspectionWorkNode.getRemark()) ? inspectionWorkNode.getRemark() : "";
        String dealImages = StrUtil.isNotEmpty(inspectionWorkNode.getDealImages()) ? inspectionWorkNode.getDealImages() : "";

        //存入步骤表
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(inspectionWorkNode.getInspectionInfoId());
        String title = "还车拍照";
        if (inspectionWorkNode.getReturnType() == 0) {
            title = "还车拍照";
        } else if (inspectionWorkNode.getReturnType() == 1) {
            title = "上门还车";
        }
        stepInfo.setTitle(title);
        stepInfo.setContent(remark);
        stepInfo.setImages(dealImages);
        stepInfo.setCreator(Math.toIntExact(SecurityFrameworkUtils.getLoginUserId()));
        stepInfo.setUpdater(Math.toIntExact(SecurityFrameworkUtils.getLoginUserId()));
        stepInfo.setCreateTime(new Date());
        stepInfo.setUpdateTime(new Date());

        inspectionStepInfoService.save(stepInfo);

        // 修改主表为已还车
        int update = baseMapper.update(Wrappers.<InspectionInfo>lambdaUpdate()
                .eq(InspectionInfo::getId, inspectionWorkNode.getInspectionInfoId())
                .set(InspectionInfo::getIsReturnCar, InspectionConstants.INSPECTION_MEET_CAR_ORDER_IS_MEET_CAR_YES)
                .set(InspectionInfo::getReturnType, inspectionWorkNode.getReturnType())
                .set(InspectionInfo::getReturnCarUserId, SecurityFrameworkUtils.getLoginUserId()));
        return true;
    }

    /**
     * 引车
     *
     * @param inspectionInfo
     */
    @Override
    public void leadCar(InspectionInfo inspectionInfo) {
        // 获取当前登陆人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        inspectionInfo.setLeadManId(loginUser.getId());

        baseMapper.updateById(inspectionInfo);
        saveLeadRecord(inspectionInfo.getId(), loginUser.getId());
    }

    /**
     * 获取业务方工单
     *
     * @param page
     * @param inspectionInfo
     * @return
     */
    @Override
    public IPage<InspectionInfo> geStelectInspectionByBusiness(Page<InspectionInfo> page, InspectionInfo inspectionInfo) {
        return baseMapper.geStelectInspectionByBusiness(page, inspectionInfo);
    }

    /**
     * @param partnerId
     * @return
     */
    @Override
    public Map<String, Long> getBusinessCountByType(Integer partnerId, List<String> datetimeRange) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);

        try {
            InspectionInfo inspectionInfo = new InspectionInfo();
//            inspectionInfo.setPartnerId(partnerId.longValue());

            // 获取当前登录人
            LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
            // 获取当前登陆人的角色
//            List<UserRoleDO> byUserId = roleService.getByUserId(loginUser.getId());
//            inspectionInfo.setLeadManId(loginUser.getId());
//            List<Long> roleIds = byUserId.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
            inspectionInfo.setUserId(loginUser.getId());

            if (!"1".equals(inspectionInfo.getStatus())) {
                inspectionInfo.setDealUserId(loginUser.getId());
            }

            Map<String, Long> result = new ConcurrentHashMap<>(); // 线程安全

            // 这里 `5` 而不是 `6`，因为 i 从 `0` 开始
            CompletableFuture<Void>[] futures = new CompletableFuture[3];

            for (int i = 0; i < 3; i++) { // 改为 `0~4`
                final String status = String.valueOf(i + 1);

                // 深拷贝对象，防止多线程修改冲突
                InspectionInfo infoCopy = JSON.parseObject(JSON.toJSONString(inspectionInfo), InspectionInfo.class);
                infoCopy.setStatus(status);
                infoCopy.setDatetimeRange(datetimeRange);

                Page<InspectionInfo> page = new Page<>(1, 1);

                futures[i] = CompletableFuture.runAsync(() -> {
                    IPage<InspectionInfo> inspectionInfoIPage = baseMapper.geStelectInspectionByBusiness(page, infoCopy);
                    Long count = inspectionInfoIPage.getTotal();
                    result.put(status, count);
                }, executor);
            }

            // 等待所有任务完成
            CompletableFuture.allOf(futures).join();

            return result;

        } catch (Exception e) {
            throw new RuntimeException("Failed to execute tasks in parallel", e);
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }

    /**
     * @return
     */
    @Override
    public List<InspectionInfo> selectMeetCarList(List<String> datetimeRange, String goodsTitle) {
        return baseMapper.selectMeetCarList(datetimeRange,goodsTitle);
    }

    /**
     * @param carNos
     * @return
     */
    @Override
    public List<InspectionInfo> selectLatestByCarNums(Collection<String> carNos) {
        return baseMapper.selectLatestByCarNums(carNos);
    }

    /**
     * @param ids
     * @return
     */
    @Override
    public Map<Long, Long> selectBuyUserIdsByInfoIds(Collection<Long> ids) {
        return baseMapper.selectBuyUserIdsByInfoIds(ids);
    }

    /**
     * 保存引车员记录
     *
     * @param inspectionInfoId 检测单ID
     * @param userId           引车员ID
     */
    private void saveLeadRecord(Long inspectionInfoId, Long userId) {
        InspectionLeadRecord inspectionLeadRecord = InspectionLeadRecord.builder()
                .inspectionId(String.valueOf(inspectionInfoId))
                .userId(userId)
                .build();

        // 添加引车记录
        inspectionLeadRecordService.save(inspectionLeadRecord);
    }

}
