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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
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.module.appBase.controller.admin.InspectionSocket;
import cn.iocoder.yudao.module.constant.InspectionConstants;
import cn.iocoder.yudao.module.inspection.entity.*;
import cn.iocoder.yudao.module.inspection.mapper.InspectionWorkNodeMapper;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.inspection.vo.StaffProjectCountVO;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 检测流程表 服务实现类
 * </p>
 *
 * @author dianliang
 * @since 2024-10-31
 */
@Service
public class InspectionWorkNodeServiceImpl extends ServiceImpl<InspectionWorkNodeMapper, InspectionWorkNode> implements IInspectionWorkNodeService {
    @Autowired
    private IInspectionInfoService inspectionInfoService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private DlInspectionProjectService inspectionProjectService;
    @Autowired
    private InspectionStepInfoService inspectionStepService;
    @Autowired
    private InspectionSocket inspectionSocket;
    @Autowired
    private RoleService roleService;
    @Autowired
    private InspectionMeetCarOrderService inspectionMeetCarOrderService;
    @Autowired
    private InspectionNoticeService noticeService;

    /**
     * 员工接单
     *
     * @param inspectionId
     * @param workNodeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInspectionWorkNode(Integer inspectionId, String workNodeId) {
        //获取当前登录人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //当前登陆人 就是检测人
        AdminUserDO workerUser = userService.getUser(loginUser.getId());
        //根据工单id获取工单
        InspectionInfo inspectionInfo = inspectionInfoService.getById(inspectionId);
        if (ObjectUtil.isNull(inspectionInfo)) {
            throw new RuntimeException("工单不存在");
        }
        //根据流程id获取流程
        InspectionWorkNode workNode = this.getById(workNodeId);
        if (ObjectUtil.isNull(workNode)) {
            throw new RuntimeException("流程不存在");
        }
        //判断当前流程是否已被接单
        if (!workNode.getStatus().equals("0") && !workNode.getStatus().equals("3")) {
            throw new RuntimeException("当前流程已被接单");
        }
        //修改流程相关信息
        workNode.setDealUserId(workerUser.getId());
        workNode.setDealUserName(workerUser.getNickname());
        workNode.setStatus("1");
        //更新
        this.updateById(workNode);

        // 插入步骤信息
        InspectionStepInfo inspectionStepInfo = new InspectionStepInfo();
        inspectionStepInfo.setInspectionInfoId(inspectionId);
        DlInspectionProject project = inspectionProjectService.getOne(new LambdaQueryWrapper<DlInspectionProject>()
                .eq(DlInspectionProject::getId, workNode.getProjectId()));
        if (ObjectUtil.isNotNull(project)) {
            inspectionStepInfo.setTitle(project.getProjectName());
        } else {
            inspectionStepInfo.setTitle("检测项目");
        }
        inspectionStepInfo.setCreateTime(DateUtil.date());
        inspectionStepInfo.setCreator(Integer.parseInt(SecurityFrameworkUtils.getLoginUserId() + ""));
        inspectionStepInfo.setWorkNodeId(workNodeId);
        inspectionStepService.save(inspectionStepInfo);

        //查询用户 信息
        //修改工单表中当前施工人
//        inspectionInfo.setWorkId(workerUser.getId());
//        inspectionInfo.setWorkerName(workerUser.getNickname());
//        inspectionInfo.setWorkerPhone(workerUser.getMobile());
//        inspectionInfoService.updateById(inspectionInfo);

//        //新增步骤
//        //根据projectId查询项目名称
//        DlInspectionProject project = inspectionProjectService.getOne(new LambdaQueryWrapper<DlInspectionProject>()
//                .eq(DlInspectionProject::getId, workNode.getProjectId()));
//
//        InspectionStepInfo inspectionStepInfo = new InspectionStepInfo();
//        inspectionStepInfo.setInspectionInfoId(Integer.parseInt(String.valueOf(inspectionInfo.getId())));
//        if (ObjectUtil.isNotNull(project)) {
//            inspectionStepInfo.setTitle(project.getProjectName() + "项目开始检测");
//        } else {
//            inspectionStepInfo.setTitle("项目检测开始");
//        }
//        inspectionStepInfo.setCreateTime(DateUtil.date());
//        inspectionStepInfo.setCreator(Integer.parseInt(String.valueOf(workerUser.getId())));
//        inspectionStepService.save(inspectionStepInfo);
    }

    /**
     * 员工取消接单
     *
     * @param inspectionId
     * @param workNodeId
     */
    @Override
    public void cancelAnOrder(Integer inspectionId, String workNodeId) {
        //获取当前登录人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //当前登陆人 就是检测人
        AdminUserDO workerUser = userService.getUser(loginUser.getId());
        //根据工单id获取工单
        InspectionInfo inspectionInfo = inspectionInfoService.getById(inspectionId);
        if (ObjectUtil.isNull(inspectionInfo)) {
            throw new RuntimeException("工单不存在");
        }
        //根据流程id获取流程
        InspectionWorkNode workNode = this.getById(workNodeId);
        if (ObjectUtil.isNull(workNode)) {
            throw new RuntimeException("流程不存在");
        }
        //判断当前流程节点的接单员是否是当前登陆人
        if (!workNode.getDealUserId().equals(workerUser.getId())) {
            throw new RuntimeException("当前流程不是你接单的");
        }
        // 更新流程
//        this.updateById(workNode);
        baseMapper.cancelAnOrder(workNode);

        // 删除步骤信息
        DlInspectionProject project = inspectionProjectService.getOne(new LambdaQueryWrapper<DlInspectionProject>()
                .eq(DlInspectionProject::getId, workNode.getProjectId()));
        inspectionStepService.remove(new LambdaQueryWrapper<InspectionStepInfo>()
                .and(i ->
                        i.eq(InspectionStepInfo::getInspectionInfoId, inspectionId)
                                .eq(InspectionStepInfo::getWorkNodeId, workNodeId)
                                .eq(InspectionStepInfo::getTitle, project.getProjectName())
                ));
    }

    /**
     * 更新流程图片 步骤信息
     *
     * @param inspectionWorkNode
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateImageAndStep(InspectionWorkNode inspectionWorkNode) {
        //获取当前登陆人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        switch (inspectionWorkNode.getSelectType()) {
            case 1:
                //退办理
                returnInspectionInfo(inspectionWorkNode);
                return;
            case 2:
                //选择重审
                retrial(inspectionWorkNode);
                return;
            default:
                //项目完成
                break;
        }
        //根据流程id获取流程
        InspectionWorkNode workNode = this.getById(inspectionWorkNode.getId());
        if (ObjectUtil.isNotEmpty(workNode.getNodeCount())) {
            inspectionWorkNode.setNodeCount(workNode.getNodeCount() + 1);
        } else {
            inspectionWorkNode.setNodeCount(1);
        }

        //根据工单id查询工单
        InspectionInfo inspectionInfo = inspectionInfoService.selectInspectionInfoById(workNode.getInspectionInfoId());

        //判断是否是还有项目完成 根据工单id查询
        //根据工单id查询流程列表
        LambdaQueryWrapper<InspectionWorkNode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionWorkNode::getInspectionInfoId, workNode.getInspectionInfoId());
        //是否还有进行中或者待开始的状态
        queryWrapper.in(InspectionWorkNode::getStatus, "0", "1");
        List<InspectionWorkNode> inspectionWorkNodes = this.list(queryWrapper);
        boolean flag = true;
        //判断是否是最后一个流程
        if (inspectionWorkNodes.size() == 1 && inspectionWorkNodes.get(0).getId().equals(workNode.getId()) && "1".equals(inspectionWorkNode.getType())) {
            flag = false;
        }

        // 更新或插入步骤信息
        DlInspectionProject project = inspectionProjectService.getOne(new LambdaQueryWrapper<DlInspectionProject>()
                .eq(DlInspectionProject::getId, workNode.getProjectId()));
        // 判断检测项目是否包含制证 并且是合格
        if (ObjectUtil.isNotEmpty(project)) {
            if (project.getProjectName().contains("制证") && "1".equals(inspectionWorkNode.getType())) {
                flag = false;
            }
        }
        List<InspectionStepInfo> stepInfos = inspectionStepService.list(new LambdaQueryWrapper<InspectionStepInfo>()
                .and(i -> i.eq(InspectionStepInfo::getInspectionInfoId, workNode.getInspectionInfoId())
                        .eq(InspectionStepInfo::getWorkNodeId, workNode.getId())
                        .eq(InspectionStepInfo::getTitle, ObjectUtil.isNotEmpty(project) ? project.getProjectName() : workNode.getProjectName())
                ));
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        if (CollUtil.isNotEmpty(stepInfos)) {
            List<InspectionStepInfo> sorted = stepInfos.stream()
                    .sorted(Comparator.comparing(InspectionStepInfo::getCreateTime).reversed()).collect(Collectors.toList());
            stepInfo = sorted.get(0);
        }
        if (ObjectUtil.isNotEmpty(stepInfo)) {
            stepInfo.setUpdateTime(DateUtil.date());
            stepInfo.setUpdater(Integer.parseInt(SecurityFrameworkUtils.getLoginUserId() + ""));
        } else {
            stepInfo.setInspectionInfoId(Integer.parseInt(String.valueOf(workNode.getInspectionInfoId())));
            if (ObjectUtil.isNotNull(project)) {
                stepInfo.setTitle(project.getProjectName());
            } else {
                stepInfo.setTitle("项目检测完成");
            }
            stepInfo.setWorkNodeId(workNode.getId());
            stepInfo.setCreateTime(DateUtil.date());
            stepInfo.setCreator(Integer.parseInt(String.valueOf(loginUser.getId())));
            stepInfo.setUpdater(Integer.parseInt(String.valueOf(loginUser.getId())));
            stepInfo.setUpdateTime(DateUtil.date());
        }
        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getRemark())) {
            stepInfo.setContent(inspectionWorkNode.getRemark());
        }
        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getDealImages())) {
            stepInfo.setImages(inspectionWorkNode.getDealImages());
        }
        inspectionStepService.saveOrUpdate(stepInfo);
        if (!flag) {
            //设置工单状态为已完成
            inspectionInfo.setStatus("1");
            //设置工单通过
            inspectionInfo.setIsPass("1");
            //设置工单结束时间
            inspectionInfo.setEndTime(DateUtil.date());
            //设置制证完成
            inspectionInfo.setMakeCert("1");

            //步骤结束
            stepInfo = new InspectionStepInfo();
            stepInfo.setInspectionInfoId(Integer.parseInt(String.valueOf(workNode.getInspectionInfoId())));
            stepInfo.setTitle("检测结束");
            stepInfo.setCreateTime(DateUtil.date());
            stepInfo.setCreator(Integer.parseInt(String.valueOf(loginUser.getId())));
            inspectionStepService.save(stepInfo);

            // 如果是业务经理需要发送提示
            // 查询接车订单表中的工单
            InspectionMeetCarOrder inspectionMeetCarOrder = inspectionMeetCarOrderService.getOne(new LambdaQueryWrapper<InspectionMeetCarOrder>()
                    .eq(InspectionMeetCarOrder::getInspectionInfoId, workNode.getInspectionInfoId()).last("limit 1").orderByAsc(InspectionMeetCarOrder::getCreateTime));
            if (ObjectUtil.isNotEmpty(inspectionMeetCarOrder) && inspectionMeetCarOrder.getMeetType() == 2) {
                // 发送订单返程的站内信
                String msg = String.format(InspectionConstants.INSPECTION_NOTICE_TEMPLATE_BUSINESS_MANAGER_MEET_CAR_ORDER_COMPLETE, inspectionMeetCarOrder.getBuyName() == null ? inspectionMeetCarOrder.getBuyPhone() : inspectionMeetCarOrder.getBuyName());
                noticeService.sentMessage(inspectionMeetCarOrder.getMeetManId(), msg);
            }
        }
//        else {
//            //修改工单表当前流程
//            inspectionInfo.setNowOrderNum(workNode.getOrderNum() + 1);
//            //获取下一节点
//            InspectionWorkNode nextNode = getNextNode(inspectionWorkNodes, workNode);
//            /*给下一单人员发送信息*/
//            List<UserDTO> listByUserId = roleService.getListByUserId(nextNode.getRoleId());
//            List<Long> ids = listByUserId.stream().map(UserDTO::getId).collect(Collectors.toList());
//            if (ObjectUtil.isNotNull(inspectionInfo.getLeadManId())){
//                ids.add(inspectionInfo.getLeadManId());
//            }
//            sendSocketMessage(ids);
//        }

        //将节点状态改为已完成
        inspectionWorkNode.setStatus("2");
        //更新流程节点表
        baseMapper.updateById(inspectionWorkNode);
        //更细工单状态
        inspectionInfoService.updateById(inspectionInfo);
    }

    private InspectionWorkNode getNextNode(List<InspectionWorkNode> inspectionWorkNodes, InspectionWorkNode workNode) {
        for (InspectionWorkNode node : inspectionWorkNodes) {
            if (node.getOrderNum() == workNode.getOrderNum() + 1) {
                return node;
            }
        }
        return null;
    }

    /**
     * 根据检测id获取流程信息
     *
     * @param inspectionId
     * @return
     */
    @Override
    public List<InspectionWorkNode> getWeorkNodesById(Integer inspectionId) {
        return baseMapper.getWeorkNodesById(inspectionId);
    }

    @Override
    public boolean orImages(Integer inspectionId, String workNodeId) {
        /*获取当前节点*/
        InspectionWorkNode workNode = getById(workNodeId);
        if (workNode.getOrderNum() == 1) {
            return true;
        }
        /*获取所有流程*/
        List<InspectionWorkNode> workNodes = getWeorkNodesById(inspectionId);
        if (!hasNextNode(workNodes, workNode)) {
            return true;
        }
        return false;
    }

    /**
     * 分页查询提成
     *
     * @param page
     * @param inspectionWorkNode
     * @return
     */
    @Override
    public IPage<Map> getRoyaltyList(IPage page, InspectionWorkNode inspectionWorkNode) {
        return baseMapper.getRoyaltyList(page, inspectionWorkNode);
    }

    @Override
    public Map getRoyaltySum(InspectionWorkNode inspectionWorkNode) {
        return baseMapper.getRoyaltySum(inspectionWorkNode);
    }

    /**
     * 重新检测
     *
     * @param workNodes
     */
    @Override
    public void recheck(InspectionWorkNode workNodes) {
        //获取当前登陆人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //将传递过来的流程节点全部改为未进行
        String status = "0";
        if (CollUtil.isNotEmpty(workNodes.getWorkNodes()) && ObjectUtil.isNotEmpty(workNodes.getWorkNodes().get(0).getStatus())) {
            status = workNodes.getWorkNodes().get(0).getStatus();
        }
        baseMapper.recheck(workNodes.getWorkNodes(), status);
        //将检测工单设置为重审
        InspectionInfo info = inspectionInfoService.getById(workNodes.getInspectionInfoId());
        info.setIsRetrial("1");
        info.setIsPass("0");
        // 设置检测次数加一
        if (ObjectUtil.isNotEmpty(info.getReinspectCount())) {
            info.setReinspectCount(info.getReinspectCount() + 1);
        } else {
            info.setReinspectCount(1);
        }
        //更新工单表
        inspectionInfoService.updateById(info);

        // 通过流程id获取项目
        List<String> workNodeIds = workNodes.getWorkNodes().stream().map(InspectionWorkNode::getId).collect(Collectors.toList());
        // 查询项目id
        List<InspectionWorkNode> inspectionWorkNodes = baseMapper.selectBatchIds(workNodeIds);
        List<String> projectIds = inspectionWorkNodes.stream().map(InspectionWorkNode::getProjectId).collect(Collectors.toList());
        List<DlInspectionProject> projectList = inspectionProjectService.list(Wrappers.<DlInspectionProject>lambdaQuery()
                .in(DlInspectionProject::getId, projectIds));
        // 将项目名称以逗号隔开
        String projectNames = projectList.stream().map(DlInspectionProject::getProjectName).collect(Collectors.joining("、"));


//        /*将当前步骤修改完已完成*/
//        if (ObjectUtil.isNotNull(workNodes.getId())) {
//            workNodes.setStatus("2");
//            baseMapper.updateById(workNodes);
//        }

        // 添加步骤信息表
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(Integer.parseInt(workNodes.getInspectionInfoId().toString()));
        stepInfo.setTitle("重检");
        stepInfo.setCreateTime(DateUtil.date());
        stepInfo.setCreator(Integer.parseInt(loginUser.getId().toString()));
        if (ObjectUtil.isNotEmpty(workNodes.getRemark())) {
            stepInfo.setContent(workNodes.getRemark());
        } else {
            stepInfo.setContent("重检");
        }
        if (ObjectUtil.isNotEmpty(workNodes.getDealImages())) {
            stepInfo.setImages(workNodes.getDealImages());
        }
        inspectionStepService.save(stepInfo);

        List<Integer> roleIds = new ArrayList<>();
        /*获取所有的角色id*/
        if (CollUtil.isNotEmpty(workNodes.getWorkNodes())) {
            roleIds = workNodes.getWorkNodes().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(info.getLeadManId())) {
            ids.add(info.getLeadManId());
        }
        //给ids去重
        ids = ids.stream().distinct().collect(Collectors.toList());
        // 获取当前共单引车员的id
        if (CollUtil.isNotEmpty(ids) && ObjectUtil.isNull(info.getAdditionalRecording())) {
            for (Long id : ids) {
                inspectionSocket.sendMessage("接工单", id.toString());
            }
        }
    }

    /**
     * 获取员工统计排序
     *
     * @param dlInspectionProject
     * @return
     */
    @Override
    public List<Map<String, Object>> getStaffCount(DlInspectionProject dlInspectionProject) {
        Map<Long, Map<String, Object>> tempMap = new LinkedHashMap<>();
        List<StaffProjectCountVO> staffCount = baseMapper.getStaffCount(dlInspectionProject);

        for (StaffProjectCountVO vo : staffCount) {
            Map<String, Object> userEntry = tempMap.computeIfAbsent(vo.getUserId(), k -> {
                Map<String, Object> m = new HashMap<>();
                m.put("userId", vo.getUserId());
                m.put("nickname", vo.getNickname());
                m.put("totalCount", 0L); // 初始总数
                m.put("children", new ArrayList<Map<String, Object>>());
                return m;
            });

            // 添加项目
            List<Map<String, Object>> children = (List<Map<String, Object>>) userEntry.get("children");
            vo.setCount(vo.getCount() == null ? 0 : vo.getCount());
            if (vo.getCount() == 0) {
                continue;
            }
            Map<String, Object> project = new HashMap<>();
            project.put("projectName", vo.getProjectName());
            project.put("count", vo.getCount());
            project.put("id", vo.getId());
            project.put("inspectionInfoId", vo.getInspectionInfoIds());
            children.add(project);

            // 累加总数
            Long currentTotal = (Long) userEntry.get("totalCount");
            userEntry.put("totalCount", currentTotal + vo.getCount());
        }

        // 转成 List 并按 totalCount 降序排序
        return tempMap.values().stream()
                .peek(userEntry -> {
                    // 排序每个用户下的项目 children
                    List<Map<String, Object>> children = (List<Map<String, Object>>) userEntry.get("children");
                    children.sort((a, b) -> Long.compare((Long) b.get("count"), (Long) a.get("count")));
                })
                .sorted((a, b) -> Long.compare((Long) b.get("totalCount"), (Long) a.get("totalCount")))
                .collect(Collectors.toList());
    }

    /**
     * 获取员工统计排序
     *
     * @param dlInspectionProject
     * @return
     */
    @Override
    public Map<String, Object> getStaffCountByUserId(DlInspectionProject dlInspectionProject) {
        Map<Long, Map<String, Object>> tempMap = new LinkedHashMap<>();
        List<StaffProjectCountVO> staffCount = baseMapper.getStaffCountByUserId(dlInspectionProject);

        for (StaffProjectCountVO vo : staffCount) {
            Map<String, Object> userEntry = tempMap.computeIfAbsent(vo.getUserId(), k -> {
                Map<String, Object> m = new HashMap<>();
                m.put("userId", vo.getUserId());
                m.put("nickname", vo.getNickname());
                m.put("totalCount", 0L); // 初始总数
                m.put("children", new ArrayList<Map<String, Object>>());
                return m;
            });

            // 添加项目
            List<Map<String, Object>> children = (List<Map<String, Object>>) userEntry.get("children");
            vo.setCount(vo.getCount() == null ? 0 : vo.getCount());
            if (vo.getCount() == 0) {
                continue;
            }
            Map<String, Object> project = new HashMap<>();
            project.put("projectName", vo.getProjectName());
            project.put("count", vo.getCount());
            project.put("id", vo.getId());
            project.put("inspectionInfoId", vo.getInspectionInfoIds());
            children.add(project);

            // 累加总数
            Long currentTotal = (Long) userEntry.get("totalCount");
            userEntry.put("totalCount", currentTotal + vo.getCount());
        }

        // 如果查出来的用户为空，返回空对象
        if (tempMap.isEmpty()) {
            return Collections.emptyMap();
        }

        // 只取一个用户数据（因为你保证只有一个用户）
        Map<String, Object> result = tempMap.values().iterator().next();

        // 排序该用户下的项目 children
        List<Map<String, Object>> children = (List<Map<String, Object>>) result.get("children");
        children.sort((a, b) -> Long.compare((Long) b.get("count"), (Long) a.get("count")));

        return result;
    }


    /**
     * 根据检测id获取异常节点
     *
     * @param idList
     * @return
     */
    @Override
    public List<Map<String, Object>> selectExceptionNodesByInspectionIds(List<Long> idList) {
        return baseMapper.selectExceptionNodesByInspectionIds(idList);
    }

    /**
     * 完成异常节点
     *
     * @param idList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateException(Long inspectionInfoId, List<String> idList) {
        // 1. 修改工单表为已完成
        inspectionInfoService.update(Wrappers.lambdaUpdate(InspectionInfo.class)
                .eq(InspectionInfo::getId, inspectionInfoId)
                .set(InspectionInfo::getIsPass, "1")
                .set(InspectionInfo::getStatus, "1"));

        // 2.修改工单节点表为已完成
        update(Wrappers.lambdaUpdate(InspectionWorkNode.class)
                .in(InspectionWorkNode::getId, idList)
                .set(InspectionWorkNode::getStatus, "2")
                .set(InspectionWorkNode::getType, "1"));

        // 3.新增工单步骤表为消除异常项目
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(Integer.parseInt(String.valueOf(inspectionInfoId)));
        stepInfo.setTitle("消除异常项目");
        stepInfo.setCreateTime(new Date());
        stepInfo.setCreator(Integer.parseInt(String.valueOf(SecurityFrameworkUtils.getLoginUserId())));
        inspectionStepService.save(stepInfo);
    }

    /**
     * @description: 员工统计根据车型
     * @author: 许
     * @date: 2025/8/5 11:41
     * @param: [dlInspectionProject]
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     */
    @Override
    public List<Map<String, Object>> queryStaffCountGroupByGoods(DlInspectionProject dlInspectionProject) {
        return baseMapper.queryStaffCountGroupByGoods(dlInspectionProject);
    }

    /**
     * @description: 员工统计初检数量和复检数量
     * @author: 许
     * @date: 2025/8/5 14:04
     * @param: [dlInspectionProject]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     */
    @Override
    public Map<String, Object> queryStaffInspectionCount(DlInspectionProject dlInspectionProject) {
        return baseMapper.queryStaffInspectionCount(dlInspectionProject);
    }

    /**
     * 判断传入的 InspectionWorkNode 对象是否在集合中有后续项目
     *
     * @param nodes       InspectionWorkNode 对象的集合
     * @param currentNode 当前需要判断的 InspectionWorkNode 对象
     * @return 如果存在后续项目返回 true，否则返回 false
     */
    public boolean hasNextNode(List<InspectionWorkNode> nodes, InspectionWorkNode currentNode) {
        int currentOrderNum = currentNode.getOrderNum();

        // 遍历集合中的所有节点，检查是否有 orderNum 大于当前节点的
        for (InspectionWorkNode node : nodes) {
            if (node.getOrderNum() > currentOrderNum) {
                return true;
            }
        }
        return false;
    }

    /**
     * 退办理
     *
     * @param inspectionWorkNode
     */
    public void returnInspectionInfo(InspectionWorkNode inspectionWorkNode) {
        // 获取当前登录人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //通过工单id获取工单
        InspectionInfo info = inspectionInfoService.getById(inspectionWorkNode.getInspectionInfoId());
        info.setIsPass("0");
        info.setEndTime(DateUtil.date());
        info.setStatus("1");
        inspectionInfoService.updateById(info);

        //插入步骤信息
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(Integer.parseInt(inspectionWorkNode.getInspectionInfoId().toString()));
        stepInfo.setTitle("退办理");
        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getRemark())) {
            stepInfo.setContent(inspectionWorkNode.getRemark());
        }
        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getDealImages())) {
            stepInfo.setImages(inspectionWorkNode.getDealImages());
        }
        stepInfo.setCreateTime(DateUtil.date());
        stepInfo.setCreator(Integer.parseInt(loginUser.getId().toString()));
        inspectionStepService.save(stepInfo);

        stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(Integer.parseInt(inspectionWorkNode.getInspectionInfoId().toString()));
        stepInfo.setTitle("检测结束");
        stepInfo.setCreateTime(DateUtil.date());
        stepInfo.setCreator(Integer.parseInt(loginUser.getId().toString()));
        inspectionStepService.save(stepInfo);

        // 如果是业务经理需要发送提示
        // 查询接车订单表中的工单
        InspectionMeetCarOrder inspectionMeetCarOrder = inspectionMeetCarOrderService.getOne(new LambdaQueryWrapper<InspectionMeetCarOrder>()
                .eq(InspectionMeetCarOrder::getInspectionInfoId, inspectionWorkNode.getInspectionInfoId()).last("limit 1").orderByAsc(InspectionMeetCarOrder::getCreateTime));
        if (ObjectUtil.isNotEmpty(inspectionMeetCarOrder) && inspectionMeetCarOrder.getMeetType() == 2) {
            // 发送订单返程的站内信
            String msg = String.format(InspectionConstants.INSPECTION_NOTICE_TEMPLATE_BUSINESS_MANAGER_MEET_CAR_ORDER_UNQUALIFIED, inspectionMeetCarOrder.getBuyName() == null ? inspectionMeetCarOrder.getBuyName() : inspectionMeetCarOrder.getBuyPhone());
            noticeService.sentMessage(inspectionMeetCarOrder.getMeetManId(), msg);
        }

        //将流程节点改为已完成
//        InspectionWorkNode byId = this.getById(inspectionWorkNode.getId());
//        byId.setStatus("2");
//        baseMapper.updateById(byId);
    }

    /**
     * 复检
     *
     * @param inspectionWorkNode
     */
    public void retrial(InspectionWorkNode inspectionWorkNode) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //通过工单id获取工单
        InspectionInfo info = inspectionInfoService.getById(inspectionWorkNode.getInspectionInfoId());
        info.setIsRetrial("1");
        info.setIsPass("0");
//        info.setStatus("2");
//        info.setNowOrderNum(workNode.getOrderNum());
        // 通过流程id获取项目
        List<String> workNodeIds = inspectionWorkNode.getWorkNodes().stream().map(InspectionWorkNode::getId).collect(Collectors.toList());

        // 将复检的项目重走一遍
        this.update(new UpdateWrapper<InspectionWorkNode>()
                .set("status", "3")
                .set("type", null)
                .in("id", workNodeIds));

        // 复检次数加一
        if (ObjectUtil.isNotNull(info.getRecheckCount())) {
            info.setRecheckCount(info.getRecheckCount() + 1);
        } else {
            info.setRecheckCount(1);
        }

        //更新工单表
        inspectionInfoService.updateById(info);

        //获取重审的节点的roleID
//        Integer roleId = workNode.getRoleId();
//        List<UserDTO> listByUserId = roleService.getListByUserId(roleId);
//        List<Long> ids = listByUserId.stream().map(UserDTO::getId).collect(Collectors.toList());
//        if (ObjectUtil.isNotNull(info.getLeadManId())) {
//            ids.add(info.getLeadManId());
//        }
//        sendSocketMessage(ids);


        // 查询项目id
        List<InspectionWorkNode> inspectionWorkNodes = baseMapper.selectBatchIds(workNodeIds);
        List<String> projectIds = inspectionWorkNodes.stream().map(InspectionWorkNode::getProjectId).collect(Collectors.toList());
        List<DlInspectionProject> projectList = inspectionProjectService.list(Wrappers.<DlInspectionProject>lambdaQuery()
                .in(DlInspectionProject::getId, projectIds));
        // 将项目名称以逗号隔开
        String projectNames = projectList.stream().map(DlInspectionProject::getProjectName).collect(Collectors.joining("、"));


//        /*将当前步骤修改完已完成*/
//        if (ObjectUtil.isNotNull(workNodes.getId())) {
//            workNodes.setStatus("2");
//            baseMapper.updateById(workNodes);
//        }

        // 添加步骤信息表
        InspectionStepInfo stepInfo = new InspectionStepInfo();
        stepInfo.setInspectionInfoId(Integer.parseInt(inspectionWorkNode.getInspectionInfoId().toString()));
        stepInfo.setTitle("复检");
        stepInfo.setCreateTime(DateUtil.date());
        stepInfo.setCreator(Integer.parseInt(loginUser.getId().toString()));
        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getRemark())) {
            stepInfo.setContent(inspectionWorkNode.getRemark());
        } else {
            stepInfo.setContent("复检了" + projectNames + "项目");
        }
        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getDealImages())) {
            stepInfo.setImages(inspectionWorkNode.getDealImages());
        }
        inspectionStepService.save(stepInfo);

        // 添加步骤信息表
//        InspectionStepInfo stepInfo = new InspectionStepInfo();
//        stepInfo.setInspectionInfoId(Integer.parseInt(inspectionWorkNode.getInspectionInfoId().toString()));
//        stepInfo.setWorkNodeId(inspectionWorkNode.getId());
//        stepInfo.setTitle("复检");
//        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getRemark())) {
//            stepInfo.setContent(inspectionWorkNode.getRemark());
//        }
//        if (ObjectUtil.isNotEmpty(inspectionWorkNode.getDealImages())) {
//            stepInfo.setImages(inspectionWorkNode.getDealImages());
//        }
//        stepInfo.setCreateTime(DateUtil.date());
//        stepInfo.setCreator(Integer.parseInt(loginUser.getId().toString()));
//        inspectionStepService.save(stepInfo);
    }

    public void sendSocketMessage(List<Long> userIds) {
        if (CollUtil.isNotEmpty(userIds)) {
            for (Long userId : userIds) {
                try {
                    inspectionSocket.sendMessage("接工单", userId.toString());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
