package com.sundot.airport.system.service.approval.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.system.service.approval.BusinessApprovalHandler;
import com.sundot.airport.system.service.approval.IApprovalUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sundot.airport.system.domain.approval.*;
import com.sundot.airport.system.mapper.approval.*;
import com.sundot.airport.system.service.approval.IApprovalEngineService;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.system.mapper.SysUserMapper;

/**
 * 审批流程引擎Service业务层处理
 *
 * @author simon lin
 * @date 2025-09-06
 */
@Service
public class ApprovalEngineServiceImpl implements IApprovalEngineService {
    private static final Logger logger = LoggerFactory.getLogger(ApprovalEngineServiceImpl.class);

    @Autowired
    private ApprovalWorkflowDefinitionMapper workflowDefinitionMapper;

    @Autowired
    private ApprovalNodeDefinitionMapper nodeDefinitionMapper;

    @Autowired
    private ApprovalInstanceMapper instanceMapper;

    @Autowired
    private ApprovalTaskMapper taskMapper;

    @Autowired
    private ApprovalHistoryMapper historyMapper;

    @Autowired
    private ApprovalCcMapper ccMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IApprovalUserService approvalUserService;

    @Autowired(required = false)
    private List<BusinessApprovalHandler> businessHandlers;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService iSysUserService;


    /**
     * 启动审批流程
     */
    @Override
    @Transactional
    public ApprovalInstance startProcess(String workflowCode, String businessType, Long businessId,
                                         String title, Long submitterId, String submitterName,
                                         Map<String, Object> formData, Map<String, Object> businessData) {
        // 1. 查询流程定义
        ApprovalWorkflowDefinition workflow = workflowDefinitionMapper.selectApprovalWorkflowDefinitionByCode(workflowCode);
        if (workflow == null) {
            throw new RuntimeException("未找到流程定义：" + workflowCode);
        }

        // 2. 创建流程实例
        ApprovalInstance instance = new ApprovalInstance();
        instance.setInstanceNo(instanceMapper.generateInstanceNo());
        instance.setWorkflowId(workflow.getId());
        instance.setTitle(title);
        instance.setBusinessType(businessType);
        instance.setBusinessId(businessId);
        instance.setSubmitterId(submitterId);
        instance.setSubmitterName(submitterName);
        instance.setSubmitTime(DateUtils.getNowDate());
        instance.setStatus("RUNNING");
        instance.setUrgentLevel("NORMAL");

        try {
            instance.setFormData(formData != null ? objectMapper.writeValueAsString(formData) : null);
            instance.setBusinessData(businessData != null ? objectMapper.writeValueAsString(businessData) : null);
        } catch (Exception e) {
            throw new RuntimeException("表单数据序列化失败", e);
        }

        instance.setCreateBy(SecurityUtils.getUsername());
        instance.setCreateTime(DateUtils.getNowDate());

        instanceMapper.insertApprovalInstance(instance);

        // 3. 获取第一个节点
        boolean isAutoPass = false;// 是否自动审批通过
        ApprovalNodeDefinition firstNode = nodeDefinitionMapper.selectFirstNodeByWorkflowId(workflow.getId());
        if (firstNode != null) {
            instance.setCurrentNodeId(firstNode.getId());
            instanceMapper.updateApprovalInstance(instance);

            // 4. 创建第一个任务（如果不是开始节点）
            if (!"START".equals(firstNode.getNodeType())) {
                createTasksForNode(instance, firstNode, formData, null);
            } else {
                // 开始节点，直接流转到下一个节点
                isAutoPass = moveToNextNode(instance, firstNode, submitterId, submitterName, "提交", formData, null);
            }
        }

        // 5. 记录历史
        recordHistory(instance.getId(), null, null, null, "SUBMIT", submitterId, submitterName, "提交审批", formData);

        // 执行业务处理逻辑
        executeBusinessLogic(instance, "APPROVED");

        // 自动审批通过
        if (isAutoPass) {
            firstNode.setSortOrder(firstNode.getSortOrder() + 1);
            moveToNextNode(instance, firstNode, submitterId, submitterName, "自动审批通过", formData, null);
            recordHistory(instance.getId(), null, null, null, "AUTO_APPROVE", submitterId, submitterName, "自动审批通过", formData);
            executeBusinessLogic(instance, "APPROVED");
        }
        return instance;
    }

    /**
     * 审批任务（同意）
     */
    @Override
    @Transactional
    public boolean approveTask(Long taskId, Long operatorId, String operatorName, String comment, Map<String, Object> formData) {
        // 1. 查询任务
        ApprovalTask task = taskMapper.selectApprovalTaskById(taskId);
        if (task == null || !"PENDING".equals(task.getStatus())) {
            throw new RuntimeException("任务不存在或已处理");
        }

        // 2. 查询实例和当前节点（在更新任务状态之前）
        ApprovalInstance instance = instanceMapper.selectApprovalInstanceById(task.getInstanceId());
        ApprovalNodeDefinition currentNode = nodeDefinitionMapper.selectApprovalNodeDefinitionById(task.getNodeId());

        // 3. 更新任务状态
        task.setStatus("APPROVED");
        task.setCompleteTime(DateUtils.getNowDate());
        task.setComment(comment);

        try {
            task.setFormData(formData != null ? objectMapper.writeValueAsString(formData) : null);
        } catch (Exception e) {
            throw new RuntimeException("表单数据序列化失败", e);
        }

        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        taskMapper.updateApprovalTask(task);

        // 4. 自动取消同节点的其他待办任务
        cancelOtherPendingTasksInSameNode(task.getInstanceId(), task.getNodeId(), taskId, operatorId, operatorName);

        // 5. 记录历史
        recordHistory(instance.getId(), task.getId(), currentNode.getId(), currentNode.getNodeName(),
                "APPROVE", operatorId, operatorName, comment, formData);

        // 6. 流转到下一节点（传递当前任务引用）
        moveToNextNode(instance, currentNode, operatorId, operatorName, comment, formData, task);

        return true;
    }

    /**
     * 驳回任务
     */
    @Override
    @Transactional
    public boolean rejectTask(Long taskId, Long operatorId, String operatorName, String comment) {
        // 1. 查询任务
        ApprovalTask task = taskMapper.selectApprovalTaskById(taskId);
        if (task == null || !"PENDING".equals(task.getStatus())) {
            throw new RuntimeException("任务不存在或已处理");
        }

        // 2. 更新任务状态
        task.setStatus("REJECTED");
        task.setCompleteTime(DateUtils.getNowDate());
        task.setComment(comment);
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        taskMapper.updateApprovalTask(task);

        // 3. 自动取消同节点的其他待办任务
        cancelOtherPendingTasksInSameNode(task.getInstanceId(), task.getNodeId(), taskId, operatorId, operatorName);

        // 4. 查询实例和当前节点
        ApprovalInstance instance = instanceMapper.selectApprovalInstanceById(task.getInstanceId());
        ApprovalNodeDefinition currentNode = nodeDefinitionMapper.selectApprovalNodeDefinitionById(task.getNodeId());

        // 5. 查找任务的原始创建者或更新者
        Long originalUserId = approvalUserService.getTaskCreatorOrUpdaterByTaskId(taskId);

        if (isSectionCheckWorkflow(instance) && ("DEPARTMENT_LEVEL_LEADER_XINGZHENG".equals(currentNode.getNodeCode()) || "DEPARTMENT_LEVEL_LEADER_JINGLI_ONE".equals(currentNode.getNodeCode()) || "DEPARTMENT_LEVEL_LEADER_JINGLI_TWO".equals(currentNode.getNodeCode()))) {
            currentNode.setSortOrder(1);
            moveToNextNode(instance, currentNode, operatorId, operatorName, comment, null, task);
        } else if (originalUserId != null) {
            // 5.1. 不结束流程，而是创建回流任务给原始操作者
            instance.setStatus("RUNNING"); // 保持运行状态
            instance.setUpdateBy(SecurityUtils.getUsername());
            instance.setUpdateTime(DateUtils.getNowDate());
            instanceMapper.updateApprovalInstance(instance);

            // 5.2. 创建回流任务
            createBackflowTask(instance, currentNode, originalUserId, comment, operatorName);
        } else {
            // 5.3. 如果找不到原始操作者，则结束流程
            instance.setStatus("REJECTED");
            instance.setCompletionTime(DateUtils.getNowDate());
            instance.setUpdateBy(SecurityUtils.getUsername());
            instance.setUpdateTime(DateUtils.getNowDate());
            instanceMapper.updateApprovalInstance(instance);
        }

        // 6. 记录历史
        recordHistory(instance.getId(), task.getId(), currentNode.getId(), currentNode.getNodeName(),
                "REJECT", operatorId, operatorName, comment, null);

        // 执行业务处理逻辑
        executeBusinessLogic(instance, "REJECTED");
        return true;
    }

    /**
     * 批量审批任务
     */
    @Override
    @Transactional
    public boolean approveTaskList(List<Long> ids) {
        //获取当前登陆人
        SysUser user = sysUserMapper.selectUserById(SecurityUtils.getUserId());

        boolean allSuccess = true;
        for (Long taskId : ids) {
            try {
                this.approveTask(taskId, user.getUserId(), user.getUserName(), "批量审批通过", null);
            } catch (Exception e) {
                logger.error("批量审批任务失败，任务ID: " + taskId, e);
                allSuccess = false;
            }
        }
        return allSuccess;
    }

    @Override
    @Transactional
    public boolean rejectTaskList(List<Long> ids) {
        //获取当前登陆人
        SysUser user = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        boolean allSuccess = true;
        for (Long taskId : ids) {
            try {
                this.rejectTask(taskId, user.getUserId(), user.getUserName(), "批量审批拒绝");
            } catch (Exception e) {
                logger.error("批量审批任务失败，任务ID: " + taskId, e);
                allSuccess = false;
            }
        }

        return allSuccess;
    }

    /**
     * 取消审批流程
     */
    @Override
    @Transactional
    public boolean cancelProcess(Long instanceId, Long operatorId, String operatorName, String comment) {
        // 1. 查询实例
        ApprovalInstance instance = instanceMapper.selectApprovalInstanceById(instanceId);
        if (instance == null || !"RUNNING".equals(instance.getStatus())) {
            throw new RuntimeException("流程实例不存在或已结束");
        }

        // 2. 更新实例状态为已取消
        instance.setStatus("CANCELLED");
        instance.setCompletionTime(DateUtils.getNowDate());
        instance.setUpdateBy(SecurityUtils.getUsername());
        instance.setUpdateTime(DateUtils.getNowDate());
        instanceMapper.updateApprovalInstance(instance);

        // 3. 取消所有待办任务
        List<ApprovalTask> pendingTasks = taskMapper.selectApprovalTaskByInstanceId(instanceId)
                .stream().filter(task -> "PENDING".equals(task.getStatus())).collect(Collectors.toList());

        for (ApprovalTask task : pendingTasks) {
            task.setStatus("CANCELLED");
            task.setCompleteTime(DateUtils.getNowDate());
            task.setUpdateBy(SecurityUtils.getUsername());
            task.setUpdateTime(DateUtils.getNowDate());
            taskMapper.updateApprovalTask(task);
        }

        // 4. 记录历史
        recordHistory(instanceId, null, null, null, "CANCEL", operatorId, operatorName, comment, null);

        executeBusinessLogic(instance, "CANCELLED");
        return true;
    }

    /**
     * 获取用户待办任务列表
     */
    @Override
    public List<ApprovalTask> getUserPendingTasks(Long userId) {
        return taskMapper.selectApprovalTaskByAssignee(userId, "PENDING");
    }

    /**
     * 获取用户已办任务列表
     */
    @Override
    public List<ApprovalTask> getUserCompletedTasks(Long userId) {
        return taskMapper.selectApprovalTaskByAssignee(userId, null)
                .stream().filter(task -> !"PENDING".equals(task.getStatus()))
                .collect(Collectors.toMap(
                        item -> Arrays.asList(item.getInstanceId(), item.getNodeId()), // 组合键
                        item -> item,
                        (existing, replacement) -> existing, // 冲突时保留已存在的（第一个）
                        java.util.LinkedHashMap::new // 第四个参数：指定使用LinkedHashMap
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
    }

    /**
     * 获取用户发起的审批实例列表
     */
    @Override
    public List<ApprovalInstance> getUserSubmittedInstances(Long userId, String status) {
        return instanceMapper.selectApprovalInstanceBySubmitter(userId, status);
    }

    /**
     * 根据业务类型和级别获取对应的流程代码
     */
    @Override
    public String getWorkflowCodeByBusinessAndLevel(String businessType, String level, String submitterRole) {
        if ("SEIZURE_REPORT".equals(businessType)) {
            if ("SEIZURE_REPORT_DEFAULT".equals(submitterRole)) {
                return "SEIZURE_REPORT_DEFAULT";
            } else if ("SEIZURE_REPORT_LEADER".equals(submitterRole)) {
                return "SEIZURE_REPORT_LEADER";
            } else {
                return "SEIZURE_REPORT_STAFF";
            }
        }

        switch (level) {
            case "PERSONAL":
                return "PERSONAL_LEVEL";
            case "SECTION":
                return "SECTION_LEVEL";
            case "GROUP":
                return "GROUP_LEVEL";
            case "BRIGADE":
                return "BRIGADE_LEVEL";
            default:
                throw new RuntimeException("未知的级别类型：" + level);
        }
    }

    /**
     * 个人级别审批流程（发送通知确认）
     */
    @Override
    @Transactional
    public ApprovalInstance startPersonalLevelProcess(String businessType, Long businessId, String title,
                                                      Long submitterId, String submitterName, Long sectionLeaderId,
                                                      Map<String, Object> formData, Map<String, Object> businessData) {
        // 新的个人级别流程：组长发起 → 科长审批 → 问题人整改 → 发起人审批 → 完成
        ApprovalInstance instance = startProcess("PERSONAL_LEVEL", businessType, businessId, title,
                submitterId, submitterName, formData, businessData);

        // 获取第一个审批节点（科长审批节点）
        ApprovalNodeDefinition firstApprovalNode = nodeDefinitionMapper.selectNextNodeByOrder(
                instance.getWorkflowId(), 1); // 获取排序为2的节点（科长审批）

        if (firstApprovalNode != null) {
            // 更新实例当前节点为科长审批节点
            instance.setCurrentNodeId(firstApprovalNode.getId());
            instanceMapper.updateApprovalInstance(instance);

            // 创建科长审批任务
            SysUser sectionLeader = sysUserMapper.selectUserById(sectionLeaderId);
            if (sectionLeader != null) {
                createSingleApprovalTask(instance, sectionLeaderId, sectionLeader.getNickName(), "科长审批");
            } else {
                throw new RuntimeException("科长用户不存在，ID: " + sectionLeaderId);
            }
        } else {
            throw new RuntimeException("无法找到科长审批节点");
        }

        return instance;
    }

    /**
     * 科级审批流程
     */
    @Override
    @Transactional
    public ApprovalInstance startSectionLevelProcess(String businessType, Long businessId, String title,
                                                     Long submitterId, String submitterName, Long sectionLeaderId,
                                                     Map<String, Object> formData, Map<String, Object> businessData) {
        ApprovalWorkflowDefinition workflow = workflowDefinitionMapper.selectApprovalWorkflowDefinitionByCode("DEPARTMENT_LEVEL");
        if (workflow == null) {
            throw new RuntimeException("流程定义不存在: DEPARTMENT_LEVEL");
        }

        ApprovalInstance instance = new ApprovalInstance();
        instance.setInstanceNo(instanceMapper.generateInstanceNo());
        instance.setWorkflowId(workflow.getId());
        instance.setTitle(title);
        instance.setBusinessType(businessType);
        instance.setBusinessId(businessId);
        instance.setSubmitterId(submitterId);
        instance.setSubmitterName(submitterName);
        instance.setSubmitTime(DateUtils.getNowDate());
        instance.setStatus("RUNNING");

        try {
            instance.setFormData(formData != null ? objectMapper.writeValueAsString(formData) : null);
        } catch (Exception e) {
            throw new RuntimeException("表单数据序列化失败", e);
        }

        // 扩展业务数据，添加科长ID和发起人ID用于后续流程
        if (businessData == null) {
            businessData = new HashMap<>();
        }
        businessData.put("sectionLeaderId", sectionLeaderId);
        businessData.put("initiatorId", submitterId);

        try {
            instance.setBusinessData(objectMapper.writeValueAsString(businessData));
        } catch (Exception e) {
            throw new RuntimeException("业务数据序列化失败", e);
        }

        instance.setCreateBy(SecurityUtils.getUsername());
        instance.setCreateTime(DateUtils.getNowDate());

        instanceMapper.insertApprovalInstance(instance);

        // 获取第一个节点
        ApprovalNodeDefinition firstNode = nodeDefinitionMapper.selectFirstNodeByWorkflowId(workflow.getId());
        if (firstNode != null) {
            instance.setCurrentNodeId(firstNode.getId());
            instanceMapper.updateApprovalInstance(instance);

            // 如果是开始节点，直接流转到下一个节点（科长审批）
            if ("START".equals(firstNode.getNodeType())) {
                moveToNextNode(instance, firstNode, submitterId, submitterName, "提交", formData, null);
            }
        }

        // 记录提交历史
        recordHistory(instance.getId(), null, null, null, "SUBMIT", submitterId, submitterName, "提交主管级审批流程", formData);

        return instance;
    }

    /**
     * 大队级审批流程
     */
    @Override
    @Transactional
    public ApprovalInstance startBrigadeLevelProcess(String businessType, Long businessId, String title,
                                                     Long submitterId, String submitterName, Long sectionLeaderId,
                                                     Map<String, Object> formData, Map<String, Object> businessData) {
        ApprovalWorkflowDefinition workflow = workflowDefinitionMapper.selectApprovalWorkflowDefinitionByCode("BRIGADE_LEVEL");
        if (workflow == null) {
            throw new RuntimeException("流程定义不存在: SECTION_LEVEL");
        }

        ApprovalInstance instance = new ApprovalInstance();
        instance.setInstanceNo(instanceMapper.generateInstanceNo());
        instance.setWorkflowId(workflow.getId());
        instance.setTitle(title);
        instance.setBusinessType(businessType);
        instance.setBusinessId(businessId);
        instance.setSubmitterId(submitterId);
        instance.setSubmitterName(submitterName);
        instance.setSubmitTime(DateUtils.getNowDate());
        instance.setStatus("RUNNING");

        try {
            instance.setFormData(formData != null ? objectMapper.writeValueAsString(formData) : null);
        } catch (Exception e) {
            throw new RuntimeException("表单数据序列化失败", e);
        }

        try {
            instance.setBusinessData(objectMapper.writeValueAsString(businessData));
        } catch (Exception e) {
            throw new RuntimeException("业务数据序列化失败", e);
        }

        instance.setCreateBy(SecurityUtils.getUsername());
        instance.setCreateTime(DateUtils.getNowDate());

        instanceMapper.insertApprovalInstance(instance);

        // 获取第一个节点
        ApprovalNodeDefinition firstNode = nodeDefinitionMapper.selectFirstNodeByWorkflowId(workflow.getId());
        if (firstNode != null) {
            instance.setCurrentNodeId(firstNode.getId());
            instanceMapper.updateApprovalInstance(instance);

            // 如果是开始节点，直接流转到下一个节点（科长审批）
            if ("START".equals(firstNode.getNodeType())) {
                moveToNextNode(instance, firstNode, submitterId, submitterName, "提交", formData, null);
            }
        }

        // 记录提交历史
        recordHistory(instance.getId(), null, null, null, "SUBMIT", submitterId, submitterName, "提交大队级审批流程", formData);

        return instance;
    }

    /**
     * 班组级审批流程
     */
    @Override
    @Transactional
    public ApprovalInstance startGroupLevelProcess(String businessType, Long businessId, String title,
                                                   Long submitterId, String submitterName,
                                                   Map<String, Object> formData, Map<String, Object> businessData) {
        return startProcess("GROUP_LEVEL", businessType, businessId, title,
                submitterId, submitterName, formData, businessData);
    }

    /**
     * 查获上报审批流程
     */
    @Override
    @Transactional
    public ApprovalInstance startSeizureReportProcess(String businessType, Long businessId, String title,
                                                      Long submitterId, String submitterName, String submitterRole,
                                                      Map<String, Object> formData, Map<String, Object> businessData) {
        String workflowCode = getWorkflowCodeByBusinessAndLevel(businessType, null, submitterRole);
        return startProcess(workflowCode, businessType, businessId, title,
                submitterId, submitterName, formData, businessData);
    }

    /**
     * 为节点创建任务
     */
    private void createTasksForNode(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark) {
        // 根据审批人类型获取审批人列表
        List<Long> assigneeIds = getAssigneeIds(node, instance);

        for (Long assigneeId : assigneeIds) {
            SysUser user = sysUserMapper.selectUserById(assigneeId);
            if (user != null) {
                ApprovalTask task = new ApprovalTask();
                task.setTaskNo(taskMapper.generateTaskNo());
                task.setInstanceId(instance.getId());
                task.setNodeId(node.getId());
                task.setTaskName(node.getNodeName());
                task.setAssigneeId(assigneeId);
                task.setAssigneeName(user.getNickName());
                task.setAssignTime(DateUtils.getNowDate());
                task.setStatus("PENDING");

                // 设置备注
                task.setRemark(remark);

                // 设置表单数据 - 如果formData为空，使用当前实例的formData
                try {
                    if (formData != null) {
                        task.setFormData(objectMapper.writeValueAsString(formData));
                    } else {
                        task.setFormData(instance.getFormData());
                    }
                } catch (Exception e) {
                    // 序列化失败时使用实例的formData
                    task.setFormData(instance.getFormData());
                }

                // 设置超时时间
                if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                    task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                }

                task.setCreateBy(SecurityUtils.getUsername());
                task.setCreateTime(DateUtils.getNowDate());

                taskMapper.insertApprovalTask(task);
            }
        }
    }

    /**
     * 为节点创建任务（支持动态分配）
     */
    private void createTasksForNodeWithDynamicAssignment(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark) {
        // 使用带表单数据的获取审批人方法
        List<Long> assigneeIds = getAssigneeIds(node, instance, formData);

        for (Long assigneeId : assigneeIds) {
            SysUser user = sysUserMapper.selectUserById(assigneeId);
            if (user != null) {
                ApprovalTask task = new ApprovalTask();
                task.setTaskNo(taskMapper.generateTaskNo());
                task.setInstanceId(instance.getId());
                task.setNodeId(node.getId());
                task.setTaskName(node.getNodeName());
                task.setAssigneeId(assigneeId);
                task.setAssigneeName(user.getNickName());
                task.setAssignTime(DateUtils.getNowDate());
                task.setStatus("PENDING");

                // 设置备注
                task.setRemark(remark);

                // 设置表单数据 - 如果formData为空，使用当前实例的formData
                try {
                    if (formData != null) {
                        task.setFormData(objectMapper.writeValueAsString(formData));
                    } else {
                        task.setFormData(instance.getFormData());
                    }
                } catch (Exception e) {
                    // 序列化失败时使用实例的formData
                    task.setFormData(instance.getFormData());
                }

                // 设置超时时间
                if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                    task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                }

                task.setCreateBy(SecurityUtils.getUsername());
                task.setCreateTime(DateUtils.getNowDate());

                taskMapper.insertApprovalTask(task);
            }
        }
    }

    /**
     * 创建通知任务
     */
    private void createNotificationTask(ApprovalInstance instance, Long userId, String userName, String taskName) {
        ApprovalTask task = new ApprovalTask();
        task.setTaskNo(taskMapper.generateTaskNo());
        task.setInstanceId(instance.getId());
        task.setNodeId(instance.getCurrentNodeId());
        task.setTaskName(taskName);
        task.setAssigneeId(userId);
        task.setAssigneeName(userName);
        task.setAssignTime(DateUtils.getNowDate());
        task.setStatus("PENDING");

        // 设置备注（通知任务的默认备注）
        task.setRemark("系统自动分配的通知任务");

        // 通知任务可以不设置formData，或者使用实例的formData
        task.setFormData(instance.getFormData());

        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), 24)); // 24小时超时
        task.setCreateBy(SecurityUtils.getUsername());
        task.setCreateTime(DateUtils.getNowDate());

        taskMapper.insertApprovalTask(task);
    }

    /**
     * 为单个用户创建审批任务
     */
    private void createSingleApprovalTask(ApprovalInstance instance, Long userId, String userName, String taskName) {
        ApprovalTask task = new ApprovalTask();
        task.setTaskNo(taskMapper.generateTaskNo());
        task.setInstanceId(instance.getId());
        task.setNodeId(instance.getCurrentNodeId());
        task.setTaskName(taskName);
        task.setAssigneeId(userId);
        task.setAssigneeName(userName);
        task.setAssignTime(DateUtils.getNowDate());
        task.setStatus("PENDING");
        task.setRemark("系统自动分配的审批任务");
        task.setFormData(instance.getFormData());
        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), 48)); // 48小时超时
        task.setCreateBy(SecurityUtils.getUsername());
        task.setCreateTime(DateUtils.getNowDate());

        taskMapper.insertApprovalTask(task);
    }

    /**
     * 为特定节点和用户创建审批任务
     */
    private void createSingleApprovalTaskForNode(ApprovalInstance instance, ApprovalNodeDefinition node, Long userId, String userName) {
        ApprovalTask task = new ApprovalTask();
        task.setTaskNo(taskMapper.generateTaskNo());
        task.setInstanceId(instance.getId());
        task.setNodeId(node.getId());
        task.setTaskName(node.getNodeName());
        task.setAssigneeId(userId);
        task.setAssigneeName(userName);
        task.setAssignTime(DateUtils.getNowDate());
        task.setStatus("PENDING");
        task.setRemark("系统自动分配的审批任务");
        task.setFormData(instance.getFormData());
        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), 48)); // 48小时超时
        task.setCreateBy(SecurityUtils.getUsername());
        task.setCreateTime(DateUtils.getNowDate());

        taskMapper.insertApprovalTask(task);
    }

    /**
     * 流转到下一节点
     */
    private boolean moveToNextNode(ApprovalInstance instance, ApprovalNodeDefinition currentNode,
                                   Long operatorId, String operatorName, String comment, Map<String, Object> formData, ApprovalTask currentTask) {
        // 查找下一个节点
        ApprovalNodeDefinition nextNode = nodeDefinitionMapper.selectNextNodeByOrder(
                instance.getWorkflowId(), currentNode.getSortOrder());

        if (nextNode != null) {
            // 更新实例当前节点
            instance.setCurrentNodeId(nextNode.getId());
            instance.setUpdateBy(SecurityUtils.getUsername());
            instance.setUpdateTime(DateUtils.getNowDate());
            instanceMapper.updateApprovalInstance(instance);

            if ("END".equals(nextNode.getNodeType())) {
                // 结束节点，完成流程
                completeProcess(instance, operatorId, operatorName);
            } else {
                // 大队级别检查流程的特殊处理
                if (isBrigadeCheckWorkflow(instance)) {
                    handleBrigadeCheckNodeAssignment(instance, nextNode, formData);
                }
                // 个人级别检查流程的特殊处理
                else if (isPersonalCheckWorkflow(instance)) {
                    handlePersonalCheckNodeAssignment(instance, nextNode, formData);
                }
                // 科级检查流程的特殊处理
                else if (isSectionCheckWorkflow(instance)) {
                    boolean isNext = handleSectionCheckNodeAssignment(instance, nextNode, formData);
                    if (isNext) {
                        currentNode.setSortOrder(nextNode.getSortOrder() + 1);
                        moveToNextNode(instance, currentNode, operatorId, operatorName, comment, formData, currentTask);
                    }
                }
                // 检查下一节点是否需要动态分配
                else if (isSeizureReportWorkflow(instance) && "SECTION_KEZHANG".equals(nextNode.getApproverType())) {
                    Long submitterId = instance.getSubmitterId();
                    if (ObjectUtil.isNotEmpty(currentTask) && ObjectUtil.isNotEmpty(currentTask.getAssigneeId())) {
                        submitterId = currentTask.getAssigneeId();
                    }
                    SysUser sysUser = iSysUserService.selectUserById(submitterId);
                    List<String> roleKeyList = sysUser.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
                    boolean isAutoPass = roleKeyList.contains(RoleTypeEnum.kezhang.getCode());
                    if (isAutoPass) {
                        // 违禁品审批流程：根据提交人角色为主管则自动审批通过
                        createTasksForNodeWithKeZhangAutoPass(instance, nextNode, formData, null, submitterId);
                        return true;
                    } else {
                        // 违禁品审批流程：根据提交人角色分配给其主管
                        createTasksForNodeWithKeZhang(instance, nextNode, formData, null, submitterId);
                    }
                } else if (isSeizureReportWorkflow(instance) && ("GROUP_LEADER".equals(nextNode.getApproverType()) || "SECTION_LEADER".equals(nextNode.getApproverType()))) {
                    Long submitterId = instance.getSubmitterId();
                    if ("SECTION_LEADER".equals(nextNode.getApproverType()) && ObjectUtil.isNotEmpty(currentTask) && ObjectUtil.isNotEmpty(currentTask.getAssigneeId())) {
                        submitterId = currentTask.getAssigneeId();
                    }
                    // 违禁品审批流程：根据提交人角色分配给其直接上级
                    createTasksForNodeWithDirectSuperior(instance, nextNode, formData, null, submitterId);
                } else if ("GROUP_LEADER".equals(nextNode.getApproverType()) && formData != null && formData.containsKey("targetGroupId")) {
                    // 科长审批后，分配给指定班组的班组长
                    createTasksForNodeWithDynamicAssignment(instance, nextNode, formData, null);
                } else if ("GROUP_LEADER".equals(nextNode.getApproverType()) && instance.getBusinessData() != null) {
                    // 班组级流程：科长发起后，根据业务数据中的targetDeptId分配给班组长
                    createTasksForNodeWithBusinessData(instance, nextNode, formData, null);
                } else if ("ORIGINAL_OPERATOR".equals(nextNode.getApproverType())) {
                    // 班组长整改完成后，回流给原始科长审批
                    ApprovalTask taskForOriginal = currentTask != null ? currentTask : getCurrentTask(instance);
                    createTasksForNodeWithOriginalOperator(instance, nextNode, formData, taskForOriginal, null);
                } else if ("DEPT_SECTION_LEADER".equals(nextNode.getApproverType())) {
                    // 科长复查完成后，分配给指定部门（如质检科）的科长
                    createTasksForNodeWithDeptSectionLeader(instance, nextNode, formData, null);
                } else {
                    // 使用默认分配逻辑
                    createTasksForNode(instance, nextNode, formData, null);
                }
            }
        } else {
            // 没有下一节点，完成流程
            completeProcess(instance, operatorId, operatorName);
        }
        return false;
    }

    /**
     * 完成流程
     */
    private void completeProcess(ApprovalInstance instance, Long operatorId, String operatorName) {
        instance.setStatus("COMPLETED");
        instance.setCompletionTime(DateUtils.getNowDate());
        instance.setCurrentNodeId(null);
        instance.setUpdateBy(SecurityUtils.getUsername());
        instance.setUpdateTime(DateUtils.getNowDate());
        instanceMapper.updateApprovalInstance(instance);

        // 记录完成历史
        recordHistory(instance.getId(), null, null, null, "COMPLETE", operatorId, operatorName, "流程完成", null);

        // 创建抄送记录
        if (!"SEIZURE_REPORT".equals(instance.getBusinessType())) {
            createCcRecords(instance);
        }

        // 执行业务处理逻辑
        executeBusinessLogic(instance, "APPROVED");
    }

    /**
     * 添加业务处理方法
     */
    private void executeBusinessLogic(ApprovalInstance instance, String action) {
        if (businessHandlers == null || businessHandlers.isEmpty()) {
            return;
        }

        for (BusinessApprovalHandler handler : businessHandlers) {
            if (handler.supports(instance.getBusinessType())) {
                try {
                    if ("APPROVED".equals(action)) {
                        handler.handleApproved(instance);
                    } else if ("REJECTED".equals(action)) {
                        handler.handleRejected(instance);
                    } else if ("CANCELLED".equals(action)) {
                        handler.handleCancelled(instance);
                    }
                } catch (Exception e) {
                    // 记录错误但不中断流程
                    e.printStackTrace();
                }
                break;
            }
        }
    }


    /**
     * 记录历史
     */
    private void recordHistory(Long instanceId, Long taskId, Long nodeId, String nodeName, String action,
                               Long operatorId, String operatorName, String comment, Map<String, Object> formData) {
        // 通过operatorId查询用户真实姓名
        String realOperatorName = operatorName;
        if (operatorId != null) {
            SysUser operator = sysUserMapper.selectUserById(operatorId);
            if (operator != null && StringUtils.isNotEmpty(operator.getNickName())) {
                realOperatorName = operator.getNickName();
            }
        }

        ApprovalHistory history = new ApprovalHistory();
        history.setInstanceId(instanceId);
        history.setTaskId(taskId);
        history.setNodeId(nodeId);
        history.setNodeName(nodeName);
        history.setAction(action);
        history.setOperatorId(operatorId);
        history.setOperatorName(realOperatorName);
        history.setOperationTime(DateUtils.getNowDate());
        history.setComment(comment);

        try {
            history.setFormData(formData != null ? objectMapper.writeValueAsString(formData) : null);
        } catch (Exception e) {
            // 忽略序列化错误
        }

        history.setCreateBy(SecurityUtils.getUsername());
        history.setCreateTime(DateUtils.getNowDate());

        historyMapper.insertApprovalHistory(history);
    }

    /**
     * 根据节点配置获取审批人ID列表
     */
    private List<Long> getAssigneeIds(ApprovalNodeDefinition node, ApprovalInstance instance) {
        String businessData = instance.getBusinessData();
        return approvalUserService.getApproverIds(node.getApproverType(), node.getApproverValue(), businessData);
    }

    /**
     * 根据节点配置和表单数据获取审批人ID列表（用于流转时的动态分配）
     */
    private List<Long> getAssigneeIds(ApprovalNodeDefinition node, ApprovalInstance instance, Map<String, Object> formData) {
        // 优先使用表单数据（包含targetGroupId等动态信息）
        String dynamicData = null;
        if (formData != null) {
            try {
                dynamicData = objectMapper.writeValueAsString(formData);
            } catch (Exception e) {
                // 忽略序列化错误，使用业务数据
            }
        }

        // 如果没有表单数据或序列化失败，使用原始业务数据
        String businessData = dynamicData != null ? dynamicData : instance.getBusinessData();
        return approvalUserService.getApproverIds(node.getApproverType(), node.getApproverValue(), businessData);
    }

    /**
     * 为节点创建任务（回流给原始操作者）
     */
    private void createTasksForNodeWithOriginalOperator(ApprovalInstance instance, ApprovalNodeDefinition node,
                                                        Map<String, Object> formData, ApprovalTask currentTask, String remark) {
        // 创建包含当前taskId的业务数据
        Map<String, Object> businessDataWithTaskId = new HashMap<>();
        if (currentTask != null) {
            businessDataWithTaskId.put("taskId", currentTask.getId());
        }

        // 使用包含taskId的业务数据获取原始操作者
        try {
            String businessDataStr = objectMapper.writeValueAsString(businessDataWithTaskId);
            List<Long> assigneeIds = approvalUserService.getApproverIds(node.getApproverType(), node.getApproverValue(), businessDataStr);

            for (Long assigneeId : assigneeIds) {
                SysUser user = sysUserMapper.selectUserById(assigneeId);
                if (user != null) {
                    ApprovalTask task = new ApprovalTask();
                    task.setTaskNo(taskMapper.generateTaskNo());
                    task.setInstanceId(instance.getId());
                    task.setNodeId(node.getId());
                    task.setTaskName(node.getNodeName());
                    task.setAssigneeId(assigneeId);
                    task.setAssigneeName(user.getNickName());
                    task.setAssignTime(DateUtils.getNowDate());
                    task.setStatus("PENDING");

                    // 设置备注
                    task.setRemark(remark);

                    // 设置表单数据 - 如果formData为空，使用当前实例的formData
                    try {
                        if (formData != null) {
                            task.setFormData(objectMapper.writeValueAsString(formData));
                        } else {
                            task.setFormData(instance.getFormData());
                        }
                    } catch (Exception e) {
                        // 序列化失败时使用实例的formData
                        task.setFormData(instance.getFormData());
                    }

                    // 设置超时时间
                    if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                    }

                    task.setCreateBy(SecurityUtils.getUsername());
                    task.setCreateTime(DateUtils.getNowDate());

                    taskMapper.insertApprovalTask(task);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("创建原始操作者任务失败", e);
        }
    }

    /**
     * 获取当前实例的活跃任务
     */
    private ApprovalTask getCurrentTask(ApprovalInstance instance) {
        if (instance.getCurrentNodeId() != null) {
            List<ApprovalTask> tasks = taskMapper.selectApprovalTaskByInstanceId(instance.getId());
            return tasks.stream()
                    .filter(task -> task.getNodeId().equals(instance.getCurrentNodeId()) && "PENDING".equals(task.getStatus()))
                    .findFirst()
                    .orElse(null);
        }
        return null;
    }

    /**
     * 为指定部门科长节点创建任务（质检科长审批）
     */
    private void createTasksForNodeWithDeptSectionLeader(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark) {
        // 创建包含质检科ID的业务数据
        Map<String, Object> businessDataWithDeptId = new HashMap<>();
        businessDataWithDeptId.put("deptId", 289); // 质检科ID

        try {
            String businessDataStr = objectMapper.writeValueAsString(businessDataWithDeptId);
            List<Long> assigneeIds = approvalUserService.getApproverIds(node.getApproverType(), node.getApproverValue(), businessDataStr);

            for (Long assigneeId : assigneeIds) {
                SysUser user = sysUserMapper.selectUserById(assigneeId);
                if (user != null) {
                    ApprovalTask task = new ApprovalTask();
                    task.setTaskNo(taskMapper.generateTaskNo());
                    task.setInstanceId(instance.getId());
                    task.setNodeId(node.getId());
                    task.setTaskName(node.getNodeName());
                    task.setAssigneeId(assigneeId);
                    task.setAssigneeName(user.getNickName());
                    task.setAssignTime(DateUtils.getNowDate());
                    task.setStatus("PENDING");

                    // 设置备注
                    task.setRemark(remark);

                    // 设置表单数据 - 如果formData为空，使用当前实例的formData
                    try {
                        if (formData != null) {
                            task.setFormData(objectMapper.writeValueAsString(formData));
                        } else {
                            task.setFormData(instance.getFormData());
                        }
                    } catch (Exception e2) {
                        // 序列化失败时使用实例的formData
                        task.setFormData(instance.getFormData());
                    }

                    // 设置超时时间
                    if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                    }

                    task.setCreateBy(SecurityUtils.getUsername());
                    task.setCreateTime(DateUtils.getNowDate());

                    taskMapper.insertApprovalTask(task);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("创建质检科长任务失败", e);
        }
    }

    /**
     * 创建驳回回流任务
     */
    private void createBackflowTask(ApprovalInstance instance, ApprovalNodeDefinition currentNode,
                                    Long originalUserId, String rejectComment, String rejectOperatorName) {
        SysUser originalUser = sysUserMapper.selectUserById(originalUserId);
        if (originalUser != null) {
            // 查找上一个节点
            ApprovalNodeDefinition previousNode = nodeDefinitionMapper.selectPreviousNodeByOrder(
                    instance.getWorkflowId(), currentNode.getSortOrder());

            // 如果没有上一个节点，则使用当前节点（兼容处理）
            ApprovalNodeDefinition targetNode = previousNode != null ? previousNode : currentNode;

            ApprovalTask backflowTask = new ApprovalTask();
            backflowTask.setTaskNo(taskMapper.generateTaskNo());
            backflowTask.setInstanceId(instance.getId());
            backflowTask.setNodeId(targetNode.getId());
            backflowTask.setTaskName("重新处理-" + targetNode.getNodeName());
            backflowTask.setAssigneeId(originalUserId);
            backflowTask.setAssigneeName(originalUser.getNickName());
            backflowTask.setAssignTime(DateUtils.getNowDate());
            backflowTask.setStatus("PENDING");

            // 在任务备注中记录驳回信息
            backflowTask.setRemark("任务被" + rejectOperatorName + "驳回，驳回原因：" + rejectComment);

            // 驳回回流任务使用实例的formData
            backflowTask.setFormData(instance.getFormData());

            // 设置超时时间（默认48小时）
            backflowTask.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), 48));

            backflowTask.setCreateBy(SecurityUtils.getUsername());
            backflowTask.setCreateTime(DateUtils.getNowDate());

            taskMapper.insertApprovalTask(backflowTask);

            // 记录回流历史
//            recordHistory(instance.getId(), backflowTask.getId(), targetNode.getId(), targetNode.getNodeName(),
//                         "BACKFLOW", originalUserId, originalUser.getNickName(),
//                         "驳回回流，需要重新处理。驳回原因：" + rejectComment, null);
        }
    }

    /**
     * 根据业务数据为班组长节点创建任务（班组级流程）
     */
    private void createTasksForNodeWithBusinessData(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark) {
        try {
            // 使用实例的业务数据来获取班组长
            List<Long> assigneeIds = approvalUserService.getApproverIds(node.getApproverType(), node.getApproverValue(), instance.getBusinessData());

            for (Long assigneeId : assigneeIds) {
                SysUser user = sysUserMapper.selectUserById(assigneeId);
                if (user != null) {
                    ApprovalTask task = new ApprovalTask();
                    task.setTaskNo(taskMapper.generateTaskNo());
                    task.setInstanceId(instance.getId());
                    task.setNodeId(node.getId());
                    task.setTaskName(node.getNodeName());
                    task.setAssigneeId(assigneeId);
                    task.setAssigneeName(user.getNickName());
                    task.setAssignTime(DateUtils.getNowDate());
                    task.setStatus("PENDING");

                    // 设置备注
                    task.setRemark(remark);

                    // 设置表单数据 - 如果formData为空，使用当前实例的formData
                    try {
                        if (formData != null) {
                            task.setFormData(objectMapper.writeValueAsString(formData));
                        } else {
                            task.setFormData(instance.getFormData());
                        }
                    } catch (Exception e) {
                        // 序列化失败时使用实例的formData
                        task.setFormData(instance.getFormData());
                    }

                    // 设置超时时间
                    if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                    }

                    task.setCreateBy(SecurityUtils.getUsername());
                    task.setCreateTime(DateUtils.getNowDate());

                    taskMapper.insertApprovalTask(task);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("创建班组长任务失败", e);
        }
    }

    /**
     * 判断是否为违禁品审批流程
     */
    private boolean isSeizureReportWorkflow(ApprovalInstance instance) {
        return "SEIZURE_REPORT".equals(instance.getBusinessType());
    }

    /**
     * 检查是否为个人级别检查流程
     */
    private boolean isPersonalCheckWorkflow(ApprovalInstance instance) {
        return "PERSONAL_CHECK".equals(instance.getBusinessType());
    }

    /**
     * 检查是否为科级检查流程
     */
    private boolean isSectionCheckWorkflow(ApprovalInstance instance) {
        return "DEPARTMENT_CHECK".equals(instance.getBusinessType());
    }

    /**
     * 处理个人级别检查流程的节点分配
     */
    private void handlePersonalCheckNodeAssignment(ApprovalInstance instance, ApprovalNodeDefinition nextNode, Map<String, Object> formData) {
        String nodeCode = nextNode.getNodeCode();

        switch (nodeCode) {
            case "PROBLEM_USER_RECTIFY":
                // 科长审批后 → 问题人整改
                createTaskForProblemUser(instance, nextNode, formData);
                break;
            case "INITIATOR_REVIEW":
                // 问题人整改后 → 发起人审批
                createTaskForInitiator(instance, nextNode, formData);
                break;
            default:
                // 使用默认分配逻辑
                createTasksForNode(instance, nextNode, formData, null);
                break;
        }
    }

    /**
     * 处理科级检查流程的节点分配
     */
    private boolean handleSectionCheckNodeAssignment(ApprovalInstance instance, ApprovalNodeDefinition nextNode, Map<String, Object> formData) {
        boolean isNext = false;
        String nodeCode = nextNode.getNodeCode();

        switch (nodeCode) {
            case "GROUP_LEADER_RECTIFY":
                // 检查是否需要流转至班组长（基于科长审批时的选择）
                if (shouldRouteToGroupLeader(formData)) {
                    createTaskForGroupLeader(instance, nextNode, formData);
                } else {
                    // 跳过班组长节点，直接进入发起人审批
                    skipToInitiatorFinalReview(instance, formData);
                }
                break;
            case "RESPONSIBLE_PERSON_REVIEW":
                // 班组长整改后 → 责任人（科长）审批
                createTaskForResponsiblePerson(instance, nextNode, formData);
                break;
            case "INITIATOR_FINAL_REVIEW":
                // 责任人审批后 → 发起人审批
                createTaskForInitiatorFinalReview(instance, nextNode, formData);
                break;
            case "DEPARTMENT_LEVEL_LEADER_KEZHANG":
                // 开始 → 责任人（主管）审批
                createTaskForResponsiblePerson(instance, nextNode, formData);
                break;
            case "DEPARTMENT_LEVEL_LEADER_XINGZHENG":
                // 责任人（主管）审批 → 发起人（大队行政）审批
                createTaskForInitiator(instance, nextNode, formData);
                break;
            case "DEPARTMENT_LEVEL_LEADER_JINGLI_ONE":
                // 大队行政审批 → 大队经理1审批
                createTaskForDept(instance, nextNode, formData);
                break;
            case "DEPARTMENT_LEVEL_LEADER_JINGLI_TWO":
                // 发起人（大队行政）审批 → 大队经理1审批
                Long deptId = extractTargetDeptIdFromBusinessData(instance.getBusinessData());
                SysDept sysDept = sysDeptService.selectDeptById(deptId);
                List<SysUser> sysUserList = sysUserMapper.selectUserByDeptIdAndRoleKeyList(sysDept.getParentId(), Arrays.asList(RoleTypeEnum.jingli.getCode()));
                if (CollUtil.isNotEmpty(sysUserList) && sysUserList.size() > 1) {
                    createTaskForDeptTwo(instance, nextNode, formData);
                } else {
                    isNext = true;
                }
                break;
            default:
                // 使用默认分配逻辑
                createTasksForNode(instance, nextNode, formData, null);
                break;
        }
        return isNext;
    }

    /**
     * 为问题人创建整改任务
     */
    private void createTaskForProblemUser(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Long problemUserId = extractProblemUserIdFromBusinessData(instance.getBusinessData());
            if (problemUserId != null) {
                SysUser problemUser = sysUserMapper.selectUserById(problemUserId);
                if (problemUser != null) {
                    createSingleApprovalTaskForNode(instance, node, problemUserId, problemUser.getNickName());
                } else {
                    logger.warn("问题人用户不存在，ID: {}", problemUserId);
                }
            } else {
                logger.warn("无法从业务数据中提取problemUserId");
            }
        } catch (Exception e) {
            logger.error("创建问题人整改任务失败", e);
        }
    }

    /**
     * 为发起人创建审批任务
     */
    private void createTaskForInitiator(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Long initiatorId = extractInitiatorIdFromBusinessData(instance.getBusinessData());
            if (initiatorId != null) {
                SysUser initiator = sysUserMapper.selectUserById(initiatorId);
                if (initiator != null) {
                    createSingleApprovalTaskForNode(instance, node, initiatorId, initiator.getNickName());
                } else {
                    logger.warn("发起人用户不存在，ID: {}", initiatorId);
                }
            } else {
                logger.warn("无法从业务数据中提取initiatorId");
            }
        } catch (Exception e) {
            logger.error("创建发起人审批任务失败", e);
        }
    }

    /**
     * 从业务数据中提取问题人ID
     */
    private Long extractProblemUserIdFromBusinessData(Object businessData) {
        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                if (businessDataStr.contains("\"problemUserId\"")) {
                    Pattern pattern = Pattern.compile("\"problemUserId\"\\s*:\\s*(\\d+)");
                    Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        return Long.valueOf(matcher.group(1));
                    }
                }
            } catch (Exception e) {
                logger.warn("解析problemUserId失败", e);
            }
        }
        return null;
    }

    /**
     * 从业务数据中提取发起人ID
     */
    private Long extractInitiatorIdFromBusinessData(Object businessData) {
        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                if (businessDataStr.contains("\"initiatorId\"")) {
                    Pattern pattern = Pattern.compile("\"initiatorId\"\\s*:\\s*(\\d+)");
                    Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        return Long.valueOf(matcher.group(1));
                    }
                }
            } catch (Exception e) {
                logger.warn("解析initiatorId失败", e);
            }
        }
        return null;
    }

    /**
     * 自动取消同一节点的其他待办任务
     *
     * @param instanceId    流程实例ID
     * @param nodeId        审批节点ID
     * @param currentTaskId 当前已处理的任务ID（不取消此任务）
     * @param operatorId    操作人ID
     * @param operatorName  操作人姓名
     */
    private void cancelOtherPendingTasksInSameNode(Long instanceId, Long nodeId, Long currentTaskId, Long operatorId, String operatorName) {
        try {
            // 1. 查询同一实例、同一节点、状态为PENDING的所有任务
            List<ApprovalTask> allTasks = taskMapper.selectApprovalTaskByInstanceId(instanceId);

            List<ApprovalTask> pendingTasks = allTasks.stream()
                    .filter(t -> t.getNodeId().equals(nodeId))
                    .filter(t -> "PENDING".equals(t.getStatus()))
                    .filter(t -> !t.getId().equals(currentTaskId))  // 排除当前任务
                    .collect(Collectors.toList());

            if (pendingTasks.isEmpty()) {
                return;
            }

            // 2. 批量更新为 CANCELLED 状态
            for (ApprovalTask taskToCancel : pendingTasks) {
                taskToCancel.setStatus("CANCELLED");
                taskToCancel.setCompleteTime(DateUtils.getNowDate());
                taskToCancel.setComment("同节点其他审批人已处理，任务自动取消");
                taskToCancel.setUpdateBy(operatorName != null ? operatorName : SecurityUtils.getUsername());
                taskToCancel.setUpdateTime(DateUtils.getNowDate());

                taskMapper.updateApprovalTask(taskToCancel);

                // 3. 记录取消历史
                recordHistory(
                        instanceId,
                        taskToCancel.getId(),
                        nodeId,
                        taskToCancel.getTaskName(),
                        "AUTO_CANCEL",
                        operatorId,
                        operatorName,
                        "同节点任务已由其他审批人处理，自动取消",
                        null
                );
            }

            // 4. 日志记录
            logger.info("流程实例[{}]节点[{}]自动取消{}个待办任务", instanceId, nodeId, pendingTasks.size());

        } catch (Exception e) {
            // 记录错误但不中断流程
            logger.error("自动取消同节点其他待办任务失败", e);
        }
    }

    /**
     * 为违禁品审批节点创建任务（根据提交人角色分配给其直接上级）
     */
    private void createTasksForNodeWithDirectSuperior(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark, Long submitterId) {
        try {

            // 根据提交人查找其直接上级
            List<Long> assigneeIds = approvalUserService.getDirectSuperiorIds(submitterId);

            if (assigneeIds.isEmpty()) {
                throw new RuntimeException("未找到提交人的直接上级，无法分配审批任务");
            }

            for (Long assigneeId : assigneeIds) {
                SysUser user = sysUserMapper.selectUserById(assigneeId);
                if (user != null) {
                    ApprovalTask task = new ApprovalTask();
                    task.setTaskNo(taskMapper.generateTaskNo());
                    task.setInstanceId(instance.getId());
                    task.setNodeId(node.getId());
                    task.setTaskName(node.getNodeName());
                    task.setAssigneeId(assigneeId);
                    task.setAssigneeName(user.getNickName());
                    task.setAssignTime(DateUtils.getNowDate());
                    task.setStatus("PENDING");

                    // 设置表单数据 - 如果formData为空，使用当前实例的formData
                    try {
                        if (formData != null) {
                            task.setFormData(objectMapper.writeValueAsString(formData));
                        } else {
                            task.setFormData(instance.getFormData());
                        }
                    } catch (Exception e) {
                        // 序列化失败时使用实例的formData
                        task.setFormData(instance.getFormData());
                    }

                    // 设置超时时间
                    if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                    }

                    task.setCreateBy(SecurityUtils.getUsername());
                    task.setCreateTime(DateUtils.getNowDate());

                    taskMapper.insertApprovalTask(task);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("创建违禁品审批任务失败：" + e.getMessage(), e);
        }
    }

    /**
     * 创建抄送记录
     * 抄送对象包括：发起人、groupLeaderId（如果存在）、质检科所有人员
     */
    private void createCcRecords(ApprovalInstance instance) {
        try {
            // 收集抄送用户ID，使用Set避免重复
            java.util.Set<Long> ccUserIds = new java.util.HashSet<>();

            // 根据业务类型决定抄送对象
            if ("BRIGADE_CHECK".equals(instance.getBusinessType())) {
                createBrigadeCheckCcRecords(instance, ccUserIds);
            } else if ("PERSONAL_CHECK".equals(instance.getBusinessType())) {
                // 个人级别检查：抄送质检科、组长发起人、审批科长
                createPersonalCheckCcRecords(instance, ccUserIds);
            } else {
                // 其他流程：原有逻辑
                createDefaultCcRecords(instance, ccUserIds);
            }

            // 创建抄送记录
            Date ccTime = DateUtils.getNowDate();
            for (Long ccUserId : ccUserIds) {
                SysUser ccUser = sysUserMapper.selectUserById(ccUserId);
                if (ccUser != null) {
                    ApprovalCc cc = new ApprovalCc();
                    cc.setInstanceId(instance.getId());
                    cc.setCcUserId(ccUserId);
                    cc.setCcUserName(ccUser.getNickName());
                    cc.setCcTime(ccTime);
                    cc.setIsRead("0"); // 未读
                    cc.setCreateBy(SecurityUtils.getUsername());
                    cc.setCreateTime(ccTime);

                    ccMapper.insertApprovalCc(cc);
                }
            }

        } catch (Exception e) {
            // 记录错误但不中断流程
            e.printStackTrace();
        }
    }

    /**
     * 为个人级别检查创建抄送记录
     */
    private void createPersonalCheckCcRecords(ApprovalInstance instance, java.util.Set<Long> ccUserIds) {
        // 1. 添加发起人（组长）
        ccUserIds.add(instance.getSubmitterId());

        // 2. 添加质检科所有人员
        List<SysUser> qualityUsers = sysUserMapper.selectUsersByRoleName("质检科");
        for (SysUser user : qualityUsers) {
            ccUserIds.add(user.getUserId());
        }

        // 3. 从business_data中提取sectionLeaderId（审批科长）
        if (StringUtils.isNotEmpty(instance.getBusinessData())) {
            Long sectionLeaderId = extractSectionLeaderIdFromBusinessData(instance.getBusinessData());
            if (sectionLeaderId != null) {
                ccUserIds.add(sectionLeaderId);
            }
        }
    }

    /**
     * 为其他流程创建抄送记录（原有逻辑）
     */
    private void createDefaultCcRecords(ApprovalInstance instance, java.util.Set<Long> ccUserIds) {
        // 1. 添加发起人
        ccUserIds.add(instance.getSubmitterId());

        // 2. 从business_data中提取groupLeaderId
        if (StringUtils.isNotEmpty(instance.getBusinessData())) {
            Long groupLeaderId = extractGroupLeaderIdFromBusinessData(instance.getBusinessData());
            if (groupLeaderId != null) {
                ccUserIds.add(groupLeaderId);
            }
        }

        // 3. 添加质检科所有人员
        List<SysUser> qualityUsers = sysUserMapper.selectUsersByRoleName("质检科");
        for (SysUser user : qualityUsers) {
            ccUserIds.add(user.getUserId());
        }
    }

    /**
     * 从业务数据中提取科长ID
     */
    private Long extractSectionLeaderIdFromBusinessData(String businessData) {
        try {
            if (businessData.contains("\"sectionLeaderId\"")) {
                java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"sectionLeaderId\"\\s*:\\s*(\\d+)");
                java.util.regex.Matcher matcher = pattern.matcher(businessData);
                if (matcher.find()) {
                    return Long.valueOf(matcher.group(1));
                }
            }
        } catch (Exception e) {
            logger.warn("解析sectionLeaderId失败", e);
        }
        return null;
    }

    /**
     * 从业务数据JSON中提取groupLeaderId
     */
    private Long extractGroupLeaderIdFromBusinessData(String businessData) {
        try {
            if (businessData.contains("\"groupLeaderId\"")) {
                java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"groupLeaderId\"\\s*:\\s*(\\d+)");
                java.util.regex.Matcher matcher = pattern.matcher(businessData);
                if (matcher.find()) {
                    return Long.valueOf(matcher.group(1));
                }
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        return null;
    }

    /**
     * 获取用户姓名
     */
    private String getSysUserName(Long userId) {
        if (userId == null) {
            return "未知用户";
        }
        try {
            SysUser user = sysUserMapper.selectUserById(userId);
            return user != null ? user.getNickName() : "未知用户";
        } catch (Exception e) {
            logger.warn("获取用户姓名失败，userId: {}", userId, e);
            return "未知用户";
        }
    }

    /**
     * 检查是否需要流转至班组长
     */
    private boolean shouldRouteToGroupLeader(Map<String, Object> formData) {
        if (formData == null) {
            return false;
        }
        Object routeToGroupLeader = formData.get("routeToGroupLeader");
        if (routeToGroupLeader instanceof Boolean) {
            return (Boolean) routeToGroupLeader;
        }
        if (routeToGroupLeader instanceof String) {
            return Boolean.parseBoolean((String) routeToGroupLeader);
        }
        return false;
    }

    /**
     * 为班组长创建整改任务
     */
    private void createTaskForGroupLeader(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Object groupLeaderIdObj = formData.get("groupLeaderId");
            Long groupLeaderId = null;

            if (groupLeaderIdObj instanceof Number) {
                groupLeaderId = ((Number) groupLeaderIdObj).longValue();
            } else if (groupLeaderIdObj instanceof String) {
                groupLeaderId = Long.parseLong((String) groupLeaderIdObj);
            }

            if (groupLeaderId != null) {
                SysUser groupLeader = sysUserMapper.selectUserById(groupLeaderId);
                if (groupLeader != null) {
                    createSingleApprovalTaskForNode(instance, node, groupLeaderId, groupLeader.getNickName());
                } else {
                    logger.warn("班组长用户不存在，ID: {}", groupLeaderId);
                }
            } else {
                logger.warn("无法从表单数据中提取groupLeaderId");
            }
        } catch (Exception e) {
            logger.error("创建班组长整改任务失败", e);
        }
    }

    /**
     * 为责任人创建审批任务
     */
    private void createTaskForResponsiblePerson(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Long sectionLeaderId = extractSectionLeaderIdFromBusinessData(instance.getBusinessData());
            if (sectionLeaderId != null) {
                SysUser sectionLeader = sysUserMapper.selectUserById(sectionLeaderId);
                if (sectionLeader != null) {
                    createSingleApprovalTaskForNode(instance, node, sectionLeaderId, sectionLeader.getNickName());
                } else {
                    logger.warn("责任人用户不存在，ID: {}", sectionLeaderId);
                }
            } else {
                logger.warn("无法从业务数据中提取sectionLeaderId");
            }
        } catch (Exception e) {
            logger.error("创建责任人审批任务失败", e);
        }
    }

    /**
     * 为发起人创建最终审批任务
     */
    private void createTaskForInitiatorFinalReview(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Long initiatorId = extractInitiatorIdFromBusinessData(instance.getBusinessData());
            if (initiatorId != null) {
                SysUser initiator = sysUserMapper.selectUserById(initiatorId);
                if (initiator != null) {
                    createSingleApprovalTaskForNode(instance, node, initiatorId, initiator.getNickName());
                } else {
                    logger.warn("发起人用户不存在，ID: {}", initiatorId);
                }
            } else {
                logger.warn("无法从业务数据中提取initiatorId");
            }
        } catch (Exception e) {
            logger.error("创建发起人最终审批任务失败", e);
        }
    }

    /**
     * 跳过班组长节点，直接进入发起人审批
     */
    private void skipToInitiatorFinalReview(ApprovalInstance instance, Map<String, Object> formData) {
        try {
            // 查找发起人审批节点
            List<ApprovalNodeDefinition> nodes = nodeDefinitionMapper.selectApprovalNodeDefinitionByWorkflowId(instance.getWorkflowId());
            ApprovalNodeDefinition initiatorNode = null;

            for (ApprovalNodeDefinition node : nodes) {
                if ("INITIATOR_FINAL_REVIEW".equals(node.getNodeCode())) {
                    initiatorNode = node;
                    break;
                }
            }

            if (initiatorNode != null) {
                // 更新实例当前节点
                instance.setCurrentNodeId(initiatorNode.getId());
                instanceMapper.updateApprovalInstance(instance);

                // 创建发起人审批任务
                createTaskForInitiatorFinalReview(instance, initiatorNode, formData);
            } else {
                logger.warn("未找到发起人审批节点");
            }
        } catch (Exception e) {
            logger.error("跳转至发起人审批节点失败", e);
        }
    }

    /**
     * 检查是否为大队级别检查流程
     */
    private boolean isBrigadeCheckWorkflow(ApprovalInstance instance) {
        return "BRIGADE_CHECK".equals(instance.getBusinessType());
    }

    /**
     * 处理科级检查流程的节点分配
     */
    private void handleBrigadeCheckNodeAssignment(ApprovalInstance instance, ApprovalNodeDefinition nextNode, Map<String, Object> formData) {
        String nodeCode = nextNode.getNodeCode();
        switch (nodeCode) {
            case "RESPONSIBLE_PERSON_REVIEW":
                // 质检科 → 责任人（大队行政人员）整改审批
                createTaskForResponsiblePerson(instance, nextNode, formData);
                break;
            case "INITIATOR_FINAL_REVIEW":
                // 责任人（大队行政人员） → 发起人审批
                createTaskForInitiatorFinalReview(instance, nextNode, formData);
                break;
            default:
                // 使用默认分配逻辑
                createTasksForNode(instance, nextNode, formData, null);
                break;
        }
    }

    /**
     * 为大队级别检查创建抄送记录
     */
    private void createBrigadeCheckCcRecords(ApprovalInstance instance, java.util.Set<Long> ccUserIds) {
        Long deptId = extractTargetDeptIdFromBusinessData(instance.getBusinessData());
        List<SysUser> sysUserList = sysUserMapper.selectUserByDeptIdAndRoleKeyList(deptId, Arrays.asList(RoleTypeEnum.jingli.getCode()));
        for (SysUser user : sysUserList) {
            ccUserIds.add(user.getUserId());
        }
    }

    /**
     * 从业务数据中提取目标部门
     */
    private Long extractTargetDeptIdFromBusinessData(String businessData) {
        try {
            if (businessData.contains("\"targetDeptId\"")) {
                java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"targetDeptId\"\\s*:\\s*(\\d+)");
                java.util.regex.Matcher matcher = pattern.matcher(businessData);
                if (matcher.find()) {
                    return Long.valueOf(matcher.group(1));
                }
            }
        } catch (Exception e) {
            logger.warn("解析targetDeptId失败", e);
        }
        return null;
    }

    /**
     * 为违禁品审批节点创建任务（根据提交人分配给其主管）
     */
    private void createTasksForNodeWithKeZhang(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark, Long submitterId) {
        try {
            // 根据提交人查找其主管
            List<Long> assigneeIds = approvalUserService.getKeZhangByUserId(submitterId);
            if (assigneeIds.isEmpty()) {
                throw new RuntimeException("未找到提交人的主管，无法分配审批任务");
            }

            for (Long assigneeId : assigneeIds) {
                SysUser user = sysUserMapper.selectUserById(assigneeId);
                if (user != null) {
                    ApprovalTask task = new ApprovalTask();
                    task.setTaskNo(taskMapper.generateTaskNo());
                    task.setInstanceId(instance.getId());
                    task.setNodeId(node.getId());
                    task.setTaskName(node.getNodeName());
                    task.setAssigneeId(assigneeId);
                    task.setAssigneeName(user.getNickName());
                    task.setAssignTime(DateUtils.getNowDate());
                    task.setStatus("PENDING");

                    // 设置表单数据 - 如果formData为空，使用当前实例的formData
                    try {
                        if (formData != null) {
                            task.setFormData(objectMapper.writeValueAsString(formData));
                        } else {
                            task.setFormData(instance.getFormData());
                        }
                    } catch (Exception e) {
                        // 序列化失败时使用实例的formData
                        task.setFormData(instance.getFormData());
                    }

                    // 设置超时时间
                    if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                        task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                    }

                    task.setCreateBy(SecurityUtils.getUsername());
                    task.setCreateTime(DateUtils.getNowDate());

                    taskMapper.insertApprovalTask(task);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("创建违禁品审批任务失败：" + e.getMessage(), e);
        }
    }

    /**
     * 为大队经理1创建审批任务
     */
    private void createTaskForDept(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Long deptId = extractTargetDeptIdFromBusinessData(instance.getBusinessData());
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            List<SysUser> sysUserList = sysUserMapper.selectUserByDeptIdAndRoleKeyList(sysDept.getParentId(), Arrays.asList(RoleTypeEnum.jingli.getCode()));
            if (CollUtil.isEmpty(sysUserList)) {
                throw new RuntimeException("未找到部门上级领导，无法分配审批任务");
            }
            createSingleApprovalTaskForNode(instance, node, sysUserList.get(0).getUserId(), sysUserList.get(0).getNickName());
        } catch (Exception e) {
            logger.error("创建经理1审批任务失败", e);
        }
    }

    /**
     * 为大队经理2创建审批任务
     */
    private void createTaskForDeptTwo(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData) {
        try {
            Long deptId = extractTargetDeptIdFromBusinessData(instance.getBusinessData());
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            List<SysUser> sysUserList = sysUserMapper.selectUserByDeptIdAndRoleKeyList(sysDept.getParentId(), Arrays.asList(RoleTypeEnum.jingli.getCode()));
            if (CollUtil.isEmpty(sysUserList) || sysUserList.size() < 2) {
                throw new RuntimeException("未找到部门上级领导，无法分配审批任务");
            }
            createSingleApprovalTaskForNode(instance, node, sysUserList.get(1).getUserId(), sysUserList.get(1).getNickName());
        } catch (Exception e) {
            logger.error("创建经理1审批任务失败", e);
        }
    }

    /**
     * 为违禁品审批节点创建任务（根据提交人角色为主管则自动审批通过）
     */
    private void createTasksForNodeWithKeZhangAutoPass(ApprovalInstance instance, ApprovalNodeDefinition node, Map<String, Object> formData, String remark, Long submitterId) {
        try {
            SysUser user = sysUserMapper.selectUserById(submitterId);
            if (user != null) {
                ApprovalTask task = new ApprovalTask();
                task.setTaskNo(taskMapper.generateTaskNo());
                task.setInstanceId(instance.getId());
                task.setNodeId(node.getId());
                task.setTaskName(node.getNodeName());
                task.setAssigneeId(user.getUserId());
                task.setAssigneeName(user.getNickName());
                task.setAssignTime(DateUtils.getNowDate());
                task.setStatus("APPROVED");
                task.setCompleteTime(DateUtils.getNowDate());

                // 设置表单数据 - 如果formData为空，使用当前实例的formData
                try {
                    if (formData != null) {
                        task.setFormData(objectMapper.writeValueAsString(formData));
                    } else {
                        task.setFormData(instance.getFormData());
                    }
                } catch (Exception e) {
                    // 序列化失败时使用实例的formData
                    task.setFormData(instance.getFormData());
                }

                // 设置超时时间
                if (node.getTimeoutHours() != null && node.getTimeoutHours() > 0) {
                    task.setTimeoutTime(DateUtils.addHours(DateUtils.getNowDate(), node.getTimeoutHours()));
                }

                task.setCreateBy(SecurityUtils.getUsername());
                task.setCreateTime(DateUtils.getNowDate());

                taskMapper.insertApprovalTask(task);
            }
        } catch (Exception e) {
            throw new RuntimeException("创建违禁品审批任务失败：" + e.getMessage(), e);
        }
    }
}