package com.ho.flow.service.process.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ho.business.vo.req.inspectionFault.InspectionFaultVo;
import com.ho.common.tools.entity.OrderForm;
import com.ho.common.tools.entity.ProcessOrder;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.entity.file.OrderFile;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.flow.constant.WorkOrderConstant;
import com.ho.flow.entity.ProcessTemplate;
import com.ho.flow.entity.process.PreDoUser;
import com.ho.flow.entity.process.TaskOrderInfo;
import com.ho.flow.feignclient.BusinessFeignClient;
import com.ho.flow.feignclient.UserFeignClient;
import com.ho.flow.mapper.OrderFormMapper;
import com.ho.flow.service.process.service.ProcessFlowNewService;
import com.ho.flow.service.process.service.ProcessManagementService;
import com.ho.flow.util.XmlToJsonUtil;
import com.ho.flow.vo.XmlBean;
import com.ho.flow.vo.process.SequenceText;
import com.ho.flow.vo.process.UserTaskText;
import com.ho.flow.vo.req.workorder.*;
import com.ho.flow.vo.resp.workorder.FallBackTaskResp;
import com.ho.flow.vo.resp.workorder.HisTaskResp;
import com.ho.flow.vo.resp.workorder.TaskDone;
import com.ho.user.api.entity.SysSubDict;
import com.ho.user.api.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.*;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ExecutionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author yule
 * @Date 2023/8/29 10:43
 * @desc ${}
 */
@Service
@Slf4j
public class ProcessFlowNewServiceImpl implements ProcessFlowNewService {

    //工作流 定义的处理类
    @Autowired
    RuntimeService runtimeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    RepositoryService repositoryService;

    //工作流 Task处理类
    @Autowired
    TaskService taskService;

    @Autowired
    ProcessManagementService processManagementService;

    //todo 流程图中的id(暂时写死)
    final String procDefKey = "order_process";

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    Snowflake snowflake;

    @Autowired
    RedisService redisService;

    @Autowired
    OrderFormMapper orderFormMapper;

    @Autowired
    BusinessFeignClient businessFeignClient;

    @Override
    public String deployment(ProcessOrder processOrder) {
        if (null == processOrder.getProcessManagementId()) {
            throw new BusinessException(BaseResponseCode.PROCESS_MANAGEMENT_ID_NOT_EMPTY);
        }
        //根据流程管理id查询对应的流程图
        ProcessTemplate processTemplate = processManagementService.getInfo(processOrder.getProcessManagementId());
        String deploymentId = "";
        if (processTemplate != null) {
            if (processTemplate.getProcessBpmn() == null) {
                throw new BusinessException(BaseResponseCode.PROCESS_TEMPLATE_IS_EMPTY);
            }
            Deployment deployment = repositoryService.createDeployment()
                    .addString(processTemplate.getName(), processTemplate.getProcessBpmn())
                    .name(processTemplate.getName())
                    .tenantId(processOrder.getUserId())
                    //.category("workOrder")
                    .deploy();
            deploymentId = deployment.getId();

            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        }
        return deploymentId;
    }

    @Override
    @Transactional
    public Integer initProcessInstance(ProcessOrder processOrder) {
       /* if (null == processOrder.getProcessManagementId()) {
            throw new BusinessException(BaseResponseCode.PROCESS_MANAGEMENT_ID_NOT_EMPTY);
        }*/
        if (processOrder.getKey() == null) {
            throw new BusinessException(BaseResponseCode.PROCESS_MANAGEMENT_ID_NOT_EMPTY);
        }
        //设置工单编号
        String serialNum = String.valueOf(snowflake.nextId());
        OrderForm orderForm = processOrder.getOrderForm();
        orderForm.setOrderNum(String.valueOf(serialNum));
        orderForm.setUserId(processOrder.getUserId());

        //新增表单数据
        orderForm.setCreateTime(new Date());
        orderForm.setProcessInstanceKey(processOrder.getKey());

        //查询用户是否绑定表单数据
//        OrderForm query = orderFormMapper.selectByUserId(processOrder.getUserId());
        if (processOrder.getOrderForm().getId() == null) {
            int i = orderFormMapper.insertOrderFormOne(orderForm);
            if (i < 0) {
                throw new BusinessException(BaseResponseCode.PROCESS_INSTANCE_ADD_ERROR);
            }
            //新增表单文件数据
            List<OrderFile> orderFiles = orderForm.getOrderFiles();
            if (!orderFiles.isEmpty()) {
                for (OrderFile orderFile : orderFiles) {
                    orderFile.setOrderFormId(orderForm.getId());
                    int j = orderFormMapper.insertOrderFileOne(orderFile);
                    if (j < 0) {
                        throw new BusinessException(BaseResponseCode.PROCESS_INSTANCE_ADD_ERROR);
                    }
                }
            }
        } else {
            orderForm.setId(processOrder.getOrderForm().getId());
            orderFormMapper.update(orderForm);
            //新增表单文件数据
            List<OrderFile> orderFiles = orderForm.getOrderFiles();
            //先删除之前的数据
            orderFormMapper.deleteFile(orderForm.getId());
            if (!orderFiles.isEmpty()) {
                for (OrderFile orderFile : orderFiles) {
                    orderFile.setOrderFormId(orderForm.getId());
                    int j = orderFormMapper.insertOrderFileOne(orderFile);
                    if (j < 0) {
                        throw new BusinessException(BaseResponseCode.PROCESS_INSTANCE_ADD_ERROR);
                    }
                }
            }
        }
        return  orderForm.getId();
        // return getCreateProcess(processOrder, orderForm);
    }

    private String getCreateProcess(ProcessOrder processOrder, OrderForm orderForm) {
        Map<String, Object> variables = new HashMap<>(16);
        //设置表单对象
        variables.put("orderForm", orderForm);
        //设置发起人
        variables.put(WorkOrderConstant.sender, processOrder.getUserId());
        variables.put("assignee", processOrder.getUserId());
        // taskService.setVariableLocal(task.getId(), WorkOrderConstant.candidateUsers, doTaskReq.getCandidateUserList());
        try {
            //为了工单和流程相互关联,先生成流程数据再生成工单数据
            ProcessInstance processInstance = runtimeService
                    .startProcessInstanceByKeyAndTenantId(processOrder.getKey(), orderForm.getOrderNum(), variables, processOrder.getTenantId());
            //流程实例id
            String processInstanceId = processInstance.getId();

            //设置用户
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
            List<String> userIds = processOrder.getUserList();
            for (String userId : userIds) {
                userId = userId.substring(userId.indexOf("_") + 1, userId.length());
                taskService.addCandidateUser(task.getId(), userId);
            }
            return processInstanceId;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException(BaseResponseCode.APPROVAL_ERROR);
        }
    }

    @NotNull
    public List<SysUser> getFristUsers(String processKey) {
        //查询第一节点的候选岗位
        //Integer postId = null;
        // 第一个节点
        Map<String, String> taskUsers = (Map<String, String>) redisService.get(processKey + XmlToJsonUtil.FIRST_USER);

        //if (redisService.hasKey(processKey)) {
        //    String value = (String) redisService.get(processKey);
        //    postId = new Integer(value);
        //}
        String candidateGroups = "";
        if (taskUsers != null) {
            candidateGroups = taskUsers.get("candidateGroups");
        }
        String[] split = candidateGroups.split(",");
        List<Integer> list = new ArrayList<Integer>(0);
        Arrays.asList(split).stream().forEach(s -> list.add(Integer.parseInt(s)));
        List<SysUser> users = new ArrayList<>();
        if (list != null) {
            DataResult<List<SysUser>> result = userFeignClient.selectByPostIds(list);
            if (result != null && !result.getData().isEmpty()) {
                users = result.getData();
            }
        }
        return users;
    }

    @Override
    public List<OrderForm> getInspectionOrders(Integer stationId) {
        List<OrderForm> result = orderFormMapper.getInspectionOrders(stationId);
        return result;
    }

    @Override
    public Map<String, List<Task>> getTodoList(SimpleUser simpleUser) {
        //1.代办人是自己的
        String tenantId = simpleUser.getTenantId();
        String assignee = simpleUser.getUserId();
        List<Task> assigneeTaskList = taskService.createTaskQuery()
                //.processVariableValueEquals(WorkOrderConstant.orderType, "workOrder")
                .taskTenantId(tenantId)
                .taskAssignee(assignee)
                .list();
        //2.查候选人有自己的
        List<Task> candidateTaskList = taskService.createTaskQuery()
                //.processVariableValueEquals(WorkOrderConstant.orderType, "workOrder")
                .taskTenantId(tenantId)
                //候选人有自己的
                .taskCandidateUser(assignee)
                .list();
        //集合合并
        Map<String, List<Task>> taskMap = new HashMap<>();

        taskMap.put(WorkOrderConstant.WorkOrderStatus.notProcessed, candidateTaskList);
        taskMap.put(WorkOrderConstant.WorkOrderStatus.processing, assigneeTaskList);
        return taskMap;
    }

    @Override
    public List<TaskDone> getToDoListFromTask(Map<String, List<Task>> taskMap, DoListTaskReq doListTaskReq) {
        //创建返回结果对象
        List<TaskDone> doneList = new ArrayList<>();

        //对任务的状态分别处理
        List<TaskDone> processingTaskList = new ArrayList<>();
        List<String> processingUserIdList = new ArrayList<>();
        doProcessingTask(taskMap, processingTaskList,processingUserIdList);
        //未处理的任务
        List<TaskDone> notProcessedTaskList = new ArrayList<>();
        List<String> notProcessedUserIdList = new ArrayList<>();
        doNotProcessedTask(taskMap, notProcessedTaskList,notProcessedUserIdList);
        doneList.addAll(processingTaskList);
        doneList.addAll(notProcessedTaskList);
        //根据
        List<TaskDone> startTask = getStartTask(doListTaskReq.getUserId());
        if (startTask != null) {
            doneList.addAll(startTask);
        }
        return doneList;
    }

    @Async
    public void doProcessingTask(Map<String, List<Task>> taskMap, List<TaskDone> processingTaskList,List<String> processingUserIdList) {
        if (taskMap.containsKey(WorkOrderConstant.WorkOrderStatus.processing)) {
            List<Task> processingList = taskMap.get(WorkOrderConstant.WorkOrderStatus.processing);
            //处理中的任务
            for (Task task : processingList) {
                setTaskAssignment(processingTaskList, task,processingUserIdList);
            }
            //去除重复用户id
            setStartUserName(processingTaskList, processingUserIdList);
        }
    }

    @Async
    public void doNotProcessedTask(Map<String, List<Task>> taskMap, List<TaskDone> notProcessedTaskList, List<String> notProcessedUserIdList) {
        if (taskMap.containsKey(WorkOrderConstant.WorkOrderStatus.notProcessed)) {
            List<Task> notProcessedList = taskMap.get(WorkOrderConstant.WorkOrderStatus.notProcessed);
            //处理中的任务

            for (Task task : notProcessedList) {
                setTaskAssignment(notProcessedTaskList, task,notProcessedUserIdList);
            }
            setStartUserName(notProcessedTaskList,notProcessedUserIdList);
        }
    }

    /**
     * 开始人名赋值
     * @param taskDoneList 任务集合
     * @param userIdList  用户Id集合
     */
    private void setStartUserName(List<TaskDone> taskDoneList, List<String> userIdList) {
        Set<String> userIds = userIdList.stream().collect(Collectors.toSet());
        Map<String, List<SysUser>> map = new HashMap<>();
        DataResult<List<SysUser>> result = userFeignClient.getUserByIds(userIds);
        if (result.getData() != null && result.getCode() == 200){
            //根据用户ID分组
            map = result.getData().stream().collect(Collectors.groupingBy(SysUser::getId));
        }
        //遍历查询对应用户名
        for (TaskDone taskDone : taskDoneList) {
            String startUserId = taskDone.getStartUserId();
            if (startUserId != null){
                List<SysUser> users = map.get(startUserId);
                if (!users.isEmpty()){
                    taskDone.setStartUserName(users.get(0).getRealName());
                }
            }
        }
    }

    private List<TaskDone> getStartTask(String userId) {
        List<TaskDone> taskDoneList = new ArrayList<>();
        //查询用户的保存表单信息
        List<OrderForm> orderFormList = orderFormMapper.selectOrderFormList(userId);
        for(OrderForm orderForm:orderFormList){
            if (orderForm != null) {
                //创建返回值
                TaskDone taskDone = new TaskDone();
                taskDone.setStationId(orderForm.getStationId());
                taskDone.setTitle(orderForm.getTitle());
                DataResult<SysSubDict> result = userFeignClient.getDictById(orderForm.getPriority());
                if (result.getCode() == 200 && result.getData() != null) {
                    taskDone.setPriority(result.getData().getValue());
                }
                DataResult<SysUser> userResult = userFeignClient.getUserById(orderForm.getUserId());
                if (userResult.getCode() == 200 && userResult.getData() != null) {
                    taskDone.setStartUserName(userResult.getData().getRealName());
                }
                if (orderForm.getStatus() == 0) {
                    taskDone.setStatus("创建工单");
                } else {
                    taskDone.setStatus("创建工单");
                }
                taskDone.setStartTime(orderForm.getCreateTime());
                taskDone.setId(String.valueOf(orderForm.getId()));
                taskDoneList.add(taskDone);
            }
        }
                return  taskDoneList;
    }

    @Override
    public List<HistoricTaskInstance> getDoneList(SimpleUser simpleUser) {
        //1.代办人是自己的
        String tenantId = simpleUser.getTenantId();
        String assignee = simpleUser.getUserId();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                //.processDefinitionKey(procDefKey)
                //.processVariableValueEquals(WorkOrderConstant.orderType, "workOrder")
                .taskTenantId(tenantId)
                .taskAssignee(assignee)
                .list();

        //集合合并
        List<HistoricTaskInstance> taskList = new ArrayList<>();
        //查询到流程id集合
        List<String> processInstanceIds = new ArrayList<>();
        for (HistoricTaskInstance historicTaskInstance : list) {
            boolean flag = processInstanceIds.contains(historicTaskInstance.getProcessInstanceId());
            if (!flag) {
                processInstanceIds.add(historicTaskInstance.getProcessInstanceId());
            }
        }

        //根据流程id遍历查询
        for (String processInstanceId : processInstanceIds) {
            List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery()
                    //.processDefinitionKey(procDefKey)
                    .taskTenantId(tenantId)
                    .processInstanceId(processInstanceId)
                    .list();
            taskList.addAll(historicTaskInstanceList);
        }
        return taskList;
    }

    @Override
    public List<TaskDone> getDoneListFromTask(List<HistoricTaskInstance> taskList, DoListTaskReq doListTaskReq) {
        // 一个流程实例对应多个任务,汇总拿到流程实例
        Map<String, List<HistoricTaskInstance>> map = taskList.stream().collect(Collectors.groupingBy(HistoricTaskInstance::getProcessInstanceId));
        //获取用户对应的全部流程实例Id集合
        Set<String> strings = map.keySet();
        Set<String> processInstanceIds = new HashSet<>();
        processInstanceIds.addAll(strings);
        //查询开始节点的任务
        List<OrderForm> query = orderFormMapper.selectFinishByUserId(doListTaskReq.getUserId());
        if (query != null) {
            List<String> queryProcessInstanceId = query.stream().map(OrderForm::getProcessInstanceId).collect(Collectors.toList());
            processInstanceIds.addAll(queryProcessInstanceId);
        }
        //创建返回值
        List<TaskDone> taskDoneList = new ArrayList<>();
        //遍历赋值
        for (String processInstanceId : processInstanceIds) {
            TaskDone taskDone = new TaskDone();
            taskDone.setProcessInstanceId(processInstanceId);
            //查询对应的最新任务状态
            Task task = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            if (task != null) {
                taskDone.setStatus(task.getName());
            } else {
                taskDone.setStatus("已完成");
            }
            //查询对应的表单任务
            OrderForm orderForm = orderFormMapper.selectByProcessInstanceId(processInstanceId);
            if (orderForm != null) {
                taskDone.setTitle(orderForm.getTitle());
                taskDone.setStartTime(orderForm.getCreateTime());
                taskDone.setStationId(orderForm.getStationId());
                DataResult<SysSubDict> dictResult = userFeignClient.getDictById(orderForm.getPriority());
                if (dictResult != null && dictResult.getCode() == 200) {
                    SysSubDict dict = dictResult.getData();
                    if (dict != null) {
                        taskDone.setPriority(dict.getValue());
                    }
                }
                DataResult<SysUser> result = userFeignClient.getUserById(orderForm.getUserId());
                if (result != null && result.getCode() == 200) {
                    SysUser user = result.getData();
                    if (user != null) {
                        taskDone.setStartUserName(user.getRealName());
                    }
                }
            }
            taskDoneList.add(taskDone);
        }
        return taskDoneList;
    }

    /**
     * 遍历任务创建返回对象赋值
     *
     * @param doneList
     * @param task
     */
    private void setTaskAssignment(List<TaskDone> doneList, Task task,List<String> userIdList) {
        String processInstanceId = task.getProcessInstanceId();
        HistoricVariableInstance OrderFormVariable = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(processInstanceId)
                .taskId(task.getId())
                .variableName("orderForm")
                .singleResult();
        OrderForm orderForm = new OrderForm();
        if (OrderFormVariable != null && OrderFormVariable.getValue() != null) {
            String value = OrderFormVariable.getValue().toString();
            orderForm = JSONObject.parseObject(value, OrderForm.class);
        }
        if (orderForm != null) {
            TaskDone taskDone = new TaskDone();
            //设置任务创建时间
            taskDone.setStartTime(task.getCreateTime());
            taskDone.setId(task.getId());
            taskDone.setTaskName(task.getName());
            taskDone.setTitle(orderForm.getTitle());
            taskDone.setStatus(task.getName());
            taskDone.setStationId(orderForm.getStationId());
            //查询建议
            HistoricVariableInstance suggestionVariable = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .taskId(task.getId())
                    .variableName("suggestion")
                    .singleResult();
            String suggestion = "";
            if (suggestionVariable != null && suggestionVariable.getValue() != null) {
                suggestion = suggestionVariable.getValue().toString();
            }
            taskDone.setSuggestion(suggestion);
            //根据任务id和流程id查询节点变量
            HistoricVariableInstance senderVariable = historyService.createHistoricVariableInstanceQuery()
                    .taskId(task.getId())
                    .processInstanceId(task.getProcessInstanceId())
                    .variableName(WorkOrderConstant.sender)
                    .singleResult();
            if (senderVariable != null) {
                Object value = senderVariable.getValue();
                if (value.toString() != null) {
                    //根据用户id查询用户名称
                    taskDone.setStartUserId(value.toString());
                    userIdList.add(value.toString());
                    /*DataResult<SysUser> user = userFeignClient.getUserById(value.toString());
                    if (user.getData() != null) {
                        taskDone.setStartUserName(user.getData().getRealName());
                    }*/
                }
            }
            taskDone.setProcessInstanceId(task.getProcessInstanceId());
            Integer priority = orderForm.getPriority();
            if (priority != null) {
                DataResult<SysSubDict> result = userFeignClient.getDictById(priority);
                if (result.getData() != null) {
                    taskDone.setPriority(result.getData().getValue());
                } else {
                    //设置为1，避免空指针
                    taskDone.setPriority("1");
                }
            }
            doneList.add(taskDone);
        }
    }


    @Override
    public void approval(DoTaskReq doTaskReq) {
        //先查这个任务
        Task task = taskService.createTaskQuery()
                //流程id查询
                .processInstanceId(doTaskReq.getProcessInstId())
                //集团id
                .taskTenantId(doTaskReq.getTenantId())
                //要使用责任人查询, 避免去做别人的任务
                //.taskAssignee(taskReq.getAssigneeUser())
                .singleResult();
        //如果没查到任务,报错
        if (task == null) {
            log.error("对应的任务不存在");
            throw new BusinessException(BaseResponseCode.TASK_NOT_EXISTS);
        }

/*
        List<String> candidateUserIds = new ArrayList<>();
        if (flowNode instanceof UserTask) {
            UserTask userTask = (UserTask) flowNode;
            List<String> candidateGroups = userTask.getCandidateGroups();
            List<Integer> postIds = candidateGroups.stream().map(s -> new Integer(s)).collect(Collectors.toList());
            DataResult<List<SysUser>> result = userFeignClient.selectByPostIds(postIds);
            if (200 == result.getCode()) {
                candidateUserIds = result.getData().stream().map(SysUser::getId).collect(Collectors.toList());
            }
                }
        //查询当前节点的流向表达式
        List<SequenceText> sequenceFlowText = getSequenceFlowText(flowNode.getOutgoingFlows());*/
        //指定候选人
        if (doTaskReq.getType().equals("1")) {
            List<String> candidateUserList = doTaskReq.getCandidateUserList();
            if (candidateUserList.isEmpty()) {
                //获取当前节点
                FlowNode flowNode = getFlowNode(doTaskReq.getProcessInstId());
                if (flowNode instanceof UserTask) {
                    UserTask userTask = (UserTask) flowNode;
                    List<String> candidateGroups = userTask.getCandidateGroups();
                    List<Integer> postIds = candidateGroups.stream().map(s -> new Integer(s)).collect(Collectors.toList());
                    DataResult<List<SysUser>> result = userFeignClient.selectByPostIds(postIds);
                    if (200 == result.getCode() && result.getData() != null) {
                        candidateUserList = result.getData().stream().map(SysUser::getId).collect(Collectors.toList());
                        ;
                    }
                }
            }
            taskService.setVariableLocal(task.getId(), "type", doTaskReq.getType());
            taskService.setVariableLocal(task.getId(), WorkOrderConstant.sender, doTaskReq.getSenderId());
            taskService.setVariableLocal(task.getId(), "orderForm", doTaskReq.getOrderForm());
            taskService.setVariableLocal(task.getId(), WorkOrderConstant.suggestion, doTaskReq.getSuggestion());

            try {
                taskService.complete(task.getId());

                //先查这个任务
                Task taskAfter = taskService.createTaskQuery()
                        //流程id查询
                        .processInstanceId(doTaskReq.getProcessInstId())
                        //集团id
                        .taskTenantId(doTaskReq.getTenantId())
                        //要使用责任人查询, 避免去做别人的任务
                        //.taskAssignee(taskReq.getAssigneeUser())
                        .singleResult();
                //下一个任务为空时，代表当前任务流程已结束，更新任务对应的巡检故障状态为已解决
                if(taskAfter == null){
                    updateInspectionFault(doTaskReq.getOrderForm().getId(),2);
                }

                //设置候选人
                taskService.setVariableLocal(taskAfter.getId(), "forward", null);
                taskService.setVariableLocal(taskAfter.getId(), "fallBack", null);
                List<String> userList = new ArrayList<String>(0);
                for (String userId : candidateUserList) {
                    userList.add(userId.substring(userId.indexOf("_") + 1, userId.length()));
                }
                if (taskAfter != null) {
                    for (String s : userList) {
                        taskService.addCandidateUser(taskAfter.getId(), s);
                    }
                }
            } catch (Exception e) {
                log.error("完成任务时出错 ,task:{}, userId: {}", task.getId(), doTaskReq.getAssigneeUser());
                log.error(e.getMessage());
            }
        }


    }

    @Override
    public void approvalFailed(DoTaskReq doTaskReq) {
        //先查这个任务
        Task task = taskService.createTaskQuery()
                //流程id查询
                .processInstanceId(doTaskReq.getProcessInstId())
                //集团id
                .taskTenantId(doTaskReq.getTenantId())
                //要使用责任人查询, 避免去做别人的任务
                //.taskAssignee(taskReq.getAssigneeUser())
                .singleResult();
        //如果没查到任务,报错
        if (task == null) {
            log.error("对应的任务不存在");
            throw new BusinessException(BaseResponseCode.TASK_NOT_EXISTS);
        }


        //先使用local 设置完成标识变量
        //始终用这个名字的变量,不然还需要判断当前是第几节点
        taskService.setVariableLocal(task.getId(), "type", 1);
        taskService.setVariableLocal(task.getId(), WorkOrderConstant.sender, doTaskReq.getSenderId());
        taskService.setVariableLocal(task.getId(), "orderForm", doTaskReq.getOrderForm());
        try {
            taskService.setAssignee(task.getId(), doTaskReq.getAssigneeUser());
            taskService.complete(task.getId());
        } catch (Exception e) {
            log.error("完成任务时出错 ,task:{}, userId: {}", task.getId(), doTaskReq.getAssigneeUser());
            log.error(e.getMessage());
        }
    }

    @Override
    public List<FallBackTaskResp> getFallBackTask(FallBackTaskReq fallBackTaskReq) {
        //创建返回值对象
        List<FallBackTaskResp> fallBackTaskRespList = new ArrayList<>();
        //获取所有历史节点任务
        List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(fallBackTaskReq.getProcessInstId())
                .orderByHistoricTaskInstanceStartTime()
                .asc().list();

        if (historicTaskInstanceList.isEmpty() || historicTaskInstanceList == null) {
            return fallBackTaskRespList;
        }

        //先查这个任务
        Task task = taskService.createTaskQuery()
                //用任务id查询
                .processInstanceId(fallBackTaskReq.getProcessInstId())
                //集团id
                .taskTenantId(fallBackTaskReq.getTenantId())
                //要使用责任人查询, 避免去做别人的任务
                //.taskAssignee(taskReq.getAssigneeUser())
                .singleResult();


        String[] split = task.getProcessDefinitionId().split(":");
        String processKey = split[0];
        //HashMap<String, List<String>> map = (HashMap<String, List<String>>) redisService.get(processKey + "his");        //判断任务是否存在,还要判断任务是否已经被认领了

        //获取当前节点
        FlowNode flowNode = getFlowNode(fallBackTaskReq.getProcessInstId());
        String id = flowNode.getId();
        // 当前任务前面所有节点
        LinkedList<String> preTaskNodes = new LinkedList<>();
        if (redisService.hasKey(processKey)) {
            String bpmnString = (String) redisService.get(processKey);
            preTaskNodes = XmlToJsonUtil.getPreTaskNodes(bpmnString, id);
        }
      /*  List<String> preFlowNodeIds = new ArrayList<>();
        //获取之前节点id
        if (!map.isEmpty() && !map.get(id).isEmpty()) {
            preFlowNodeIds = map.get(id);
        }*/
        if (task != null) {
            try {
                String taskDefinitionKey = task.getTaskDefinitionKey();
                Map<String, List<HistoricTaskInstance>> hisTaskMap = historicTaskInstanceList.stream()
                        //转化为以name分组的map
                        .collect(Collectors.groupingBy(HistoricTaskInstance::getName));
                //遍历map并赋值
                for (String key : hisTaskMap.keySet()) {
                    //排除掉自身
                    if (!task.getName().equals(key)) {
                        List<HistoricTaskInstance> historicTaskInstances = hisTaskMap.get(key);
                        FallBackTaskResp resp = new FallBackTaskResp();
                        resp.setName(key);
                        resp.setProcessInstId(fallBackTaskReq.getProcessInstId());
                        for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
                            resp.setTaskInstId(historicTaskInstance.getId());
                            resp.setTaskDefinitionKey(historicTaskInstance.getTaskDefinitionKey());
                        }
                        fallBackTaskRespList.add(resp);
                    }
                }
                List<String> finalPreFlowNodeIds = preTaskNodes;
                fallBackTaskRespList = fallBackTaskRespList.stream().filter(s -> {
                    return finalPreFlowNodeIds.contains(s.getTaskDefinitionKey());
                }).collect(Collectors.toList());
                return fallBackTaskRespList;
            } catch (Exception e) {
                log.error("获取回退任务列表出错 ,task:{}, processInstanceId: {}", task.getId(), fallBackTaskReq.getProcessInstId());
                log.error(e.getMessage());
            }
        }
        return fallBackTaskRespList;
    }

    @Override
    public void fallBackTask(RejectTaskReq rejectTaskReq) {
        if (null == rejectTaskReq.getTaskInstId()) {
            throw new BusinessException(BaseResponseCode.TASK_NOT_EXISTS);
        }
        if (null == rejectTaskReq.getTaskDefinitionKey()) {
            throw new BusinessException(BaseResponseCode.TASK_NOT_EXISTS);
        }

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = processEngine.getHistoryService();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        TaskService taskService = processEngine.getTaskService();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        //查询指定的回退任务
        Task task = taskService.createTaskQuery().processInstanceId(rejectTaskReq.getProcessInstId()).singleResult();
        //当前节点executionId
        String executionId = task.getExecutionId();
        //查询回退任务
        HistoricTaskInstance hisTask = historyService.createHistoricTaskInstanceQuery()
                .taskId(rejectTaskReq.getTaskInstId()).singleResult();
        FlowNode hisFlowNode = getHisFlowNode(rejectTaskReq.getTaskInstId());
        //获取当前节点的信息
        Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        String activityId = execution.getActivityId();
        FlowNode flowNode = getFlowNode(task.getProcessDefinitionId(), activityId);

        //记录当前节点活动方向
        List<SequenceFlow> outgoingFlows = new ArrayList<>();
        outgoingFlows.addAll(flowNode.getOutgoingFlows());
        //清除当前节点方向
        flowNode.getOutgoingFlows().clear();

        //建立回退节点的新方向
        List<SequenceFlow> newOutgoingFlows = new ArrayList<>();
        SequenceFlow sequenceFlow = new SequenceFlow();
        sequenceFlow.setId("new");
        sequenceFlow.setSourceFlowElement(flowNode);
        sequenceFlow.setTargetFlowElement(hisFlowNode);
        newOutgoingFlows.add(sequenceFlow);
        //设置新方向给当前节点
        flowNode.setOutgoingFlows(newOutgoingFlows);
        //完成任务
        //查询回退节点的变量数据
        taskService.setVariableLocal(task.getId(), WorkOrderConstant.sender, rejectTaskReq.getUserId());
        taskService.setVariableLocal(task.getId(), "orderForm", rejectTaskReq.getOrderForm());
        taskService.setVariableLocal(task.getId(), WorkOrderConstant.suggestion, rejectTaskReq.getSuggestion());
        taskService.complete(task.getId());

        //查询当前任务
        //先查这个任务
        Task taskAfter = taskService.createTaskQuery()
                //流程id查询
                .processInstanceId(rejectTaskReq.getProcessInstId())
                //集团id
                .taskTenantId(rejectTaskReq.getTenantId())
                //要使用责任人查询, 避免去做别人的任务
                //.taskAssignee(taskReq.getAssigneeUser())
                .singleResult();
        //设置候选人
        if (taskAfter != null) {
            taskService.addCandidateUser(taskAfter.getId(), hisTask.getAssignee());
        }

        //恢复方向
        flowNode.setOutgoingFlows(outgoingFlows);
        //设置执行人
        Task nextTask = taskService.createTaskQuery().processInstanceId(rejectTaskReq.getProcessInstId())
                .singleResult();
        taskService.setVariableLocal(nextTask.getId(), "orderForm", rejectTaskReq.getOrderForm());
        taskService.setVariableLocal(nextTask.getId(), "fallBack", true);
        taskService.setVariableLocal(nextTask.getId(), "forward", null);
        if (null != nextTask) {
            taskService.addCandidateUser(nextTask.getId(), hisTask.getAssignee());
        }

    }

    @Override
    public List<HisTaskResp> detailsTask(CirculationTaskReq taskReq) {
        //创建返回对象
        List<HisTaskResp> hisTaskRespList = new ArrayList<>();
        //获取所有历史节点任务
        List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(taskReq.getProcessInstId())
                .orderByHistoricTaskInstanceStartTime().asc().list();
        //查询当前任务
        Task task = taskService.createTaskQuery().processInstanceId(taskReq.getProcessInstId()).singleResult();

        //循环遍历赋值
        for (HistoricTaskInstance historicTaskInstance : historicTaskInstanceList) {
            HisTaskResp hisTaskResp = new HisTaskResp();
            hisTaskResp.setName(historicTaskInstance.getName());
            //查询候选人
            //候选人集合
            Set<String> userIds = new HashSet<>();

            if (task != null && task.getId().equals(historicTaskInstance.getId())){
                List<IdentityLink> identityLinkList = taskService.getIdentityLinksForTask(historicTaskInstance.getId());
                if (identityLinkList != null && identityLinkList.size() > 0) {
                    for (Iterator iterator = identityLinkList.iterator(); iterator
                            .hasNext();) {
                        IdentityLink identityLink = (IdentityLink) iterator.next();
                        if (identityLink.getUserId() != null) {
                            String identityLinkUserIdd = identityLink.getUserId();
                            userIds.add(identityLinkUserIdd);
                        }
                    }
                }
            }
                //查询候选人
            if (!userIds.isEmpty()) {
                DataResult<List<SysUser>> result = userFeignClient.getUserByIds(userIds);
                if (result != null && result.getCode() == 200) {
                    List<SysUser> users = result.getData();
                    if (!users.isEmpty()) {
                        List<String> candidates = users.stream().map(SysUser::getRealName).collect(Collectors.toList());
                        hisTaskResp.setCandidates(candidates);
                    }
                }
            }

            String userId = historicTaskInstance.getAssignee();
            //历史任务中执行人id为不为空直接查询
            if (userId != null) {
                DataResult<SysUser> result = userFeignClient.getUserById(userId);
                SysUser user = result.getData();
                if (user != null) {
                    hisTaskResp.setUserName(user.getRealName());
                    hisTaskResp.setCandidates(null);
                } else {
                    hisTaskResp.setUserName("");
                }
            }
            //根据任务id和流程id查询complete变量
            OrderForm orderForm = getHisOrderForm(historicTaskInstance, taskReq.getProcessInstId());
            HistoricVariableInstance suggestionVariable = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(taskReq.getProcessInstId())
                    .taskId(historicTaskInstance.getId())
                    .variableName("suggestion")
                    .singleResult();
            String suggestion = "";
            if (suggestionVariable != null && suggestionVariable.getValue() != null) {
                suggestion = suggestionVariable.getValue().toString();
            }
            hisTaskResp.setSuggestion(suggestion);
            Date endTime = historicTaskInstance.getEndTime();
            if (endTime != null) {
                hisTaskResp.setEndTime(endTime);
            } else {
                hisTaskResp.setSuggestion(null);
            }

            HistoricVariableInstance fallBackVariable = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(taskReq.getProcessInstId())
                    .taskId(historicTaskInstance.getId())
                    .variableName("fallBack")
                    .singleResult();
            if (fallBackVariable != null && fallBackVariable.getValue() != null) {
                hisTaskResp.setName(historicTaskInstance.getName()+ "(回退)");
            }
            HistoricVariableInstance forwardVariable = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(taskReq.getProcessInstId())
                    .taskId(historicTaskInstance.getId())
                    .variableName("forward")
                    .singleResult();
            if (forwardVariable != null && forwardVariable.getValue() != null) {
                hisTaskResp.setName(historicTaskInstance.getName() + "(转发)");
            }
            HistoricVariableInstance cancelVariable = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(taskReq.getProcessInstId())
                    .taskId(historicTaskInstance.getId())
                    .variableName("cancel")
                    .singleResult();
            if (cancelVariable != null && cancelVariable.getValue() != null) {
                if (hisTaskResp.getName() != null) {
                    hisTaskResp.setName(hisTaskResp.getName() + "(作废)");
                }else {
                    hisTaskResp.setName(historicTaskInstance.getName() + "(作废)");
                }
                hisTaskResp.setSuggestion(historicTaskInstance.getDeleteReason());
            }
            hisTaskResp.setOrderForm(orderForm);
            hisTaskRespList.add(hisTaskResp);
        }
        //查询开始节点
        HisTaskResp startEvent = getStartEvent(taskReq.getProcessInstId());
        if (startEvent != null) {
            hisTaskRespList.add(startEvent);
        }
        hisTaskRespList = hisTaskRespList.stream()
                .sorted(Comparator.comparing((Function<HisTaskResp, Date>) hisTaskResp -> hisTaskResp.getEndTime(), Comparator.nullsLast(Date::compareTo)))
                .collect(Collectors.toList());
        return hisTaskRespList;
    }


    @Override
    public void forward(TaskDone taskDone) {
        //查询当前任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(taskDone.getProcessInstanceId())
                .singleResult();
        //查询当前节点
        FlowNode flowNode = getFlowNode(taskDone.getProcessInstanceId());
        //指向元素
        List<SequenceFlow> outgoingFlows = flowNode.getOutgoingFlows();
        //创建指向当前节点的箭头元素
        SequenceFlow sequenceFlow = new SequenceFlow();
        sequenceFlow.setSourceFlowElement(flowNode);
        sequenceFlow.setTargetFlowElement(flowNode);
        List<SequenceFlow> newSequenceFlows = new ArrayList<>();
        newSequenceFlows.add(sequenceFlow);
        flowNode.setOutgoingFlows(newSequenceFlows);
        taskService.setVariableLocal(task.getId(), WorkOrderConstant.sender, taskDone.getSender());
        taskService.setVariableLocal(task.getId(), WorkOrderConstant.suggestion, taskDone.getSuggestion());
        taskService.setAssignee(task.getId(), taskDone.getSender());
        //完成任务
        taskService.complete(task.getId());
        //恢复方向
        flowNode.setOutgoingFlows(outgoingFlows);
        //查询转发后任务
        Task forwardTask = taskService.createTaskQuery()
                .processInstanceId(taskDone.getProcessInstanceId())
                .singleResult();
        taskService.setVariableLocal(forwardTask.getId(), "forward", true);
        taskService.setVariableLocal(forwardTask.getId(), "fallBack", null);
        List<String> userIds = taskDone.getCandidateUserList();
        for (String userId : userIds) {
            String candidateUserId = userId.substring(userId.indexOf("_") + 1, userId.length());
            taskService.addCandidateUser(forwardTask.getId(), candidateUserId);
        }

    }

    @Override
    public List<PreDoUser> getPreDo(TaskUserReq taskUserReq) {
        List<PreDoUser> users = new ArrayList<>();
        String processInstId = taskUserReq.getProcessInstId();
        //获取当前节点
        FlowNode flowNode = getFlowNode(processInstId);
        //查询当前任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstId).singleResult();
        String[] keys = task.getProcessDefinitionId().split(":");
        Object o = redisService.get(keys[0] + XmlToJsonUtil.AS_NODE);
        List<XmlBean> xmlBeans = new ArrayList<>(0);
        if (o != null) {
            xmlBeans = (List<XmlBean>) o;
        }
        String nextKey = null;
        boolean flag = true;
        for (XmlBean xmlBean : xmlBeans) {
            if (flag && !xmlBean.getNodeKey().equals(flowNode.getId())) {
                continue;
            }
            flag = false;
            if (!xmlBean.isAfterEnd() && !xmlBean.isAfterGateway()) {
                nextKey = xmlBean.getAfterNodeKey();
            }
        }
        Map<String, Map<String, String>> allUserMap = (Map<String, Map<String, String>>) redisService.get(keys[0] + XmlToJsonUtil.ALL_USER);
        Map<String, String> nodeMap = allUserMap.get(nextKey);
        String candidateGroups = "";
        if (nodeMap != null) {
            candidateGroups = nodeMap.get("candidateGroups");
        }
        String[] split = candidateGroups.split(",");
        List<Integer> list = new ArrayList<Integer>(0);
        if (split.length > 0) {
            Arrays.asList(split).stream().forEach(s ->
                    {
                        if (!StringUtils.isEmpty(s))
                            list.add(Integer.parseInt(s));
                    }
            );

            //if (flowNode instanceof UserTask) {

            UserTask userTask = (UserTask) flowNode;
            //List<String> candidateGroups = userTask.getCandidateGroups();
            //List<Integer> postIds = candidateGroups.stream().map(s -> new Integer(s)).collect(Collectors.toList());

            DataResult<List<SysUser>> result = userFeignClient.selectByPostIds(list);
            if (200 == result.getCode()) {
                List<SysUser> userList = result.getData();
                //过滤其他公司的人
                if (!taskUserReq.getDeptId().equals("155")) {
                    userList = userList.stream().filter(s -> {
                        if (s.getDeptId().toString().equals(taskUserReq.getDeptId())) {
                            return true;
                        } else {
                            return false;
                        }
                    }).collect(Collectors.toList());
                }
                users = getPreDoUsers(userList);
            }
            //}
        }
        return users;
    }

    private String getOutGoingFlow(FlowNode flowNode, String key) {
        // 查询后面的节点
        List<SequenceFlow> outgoingFlows = flowNode.getOutgoingFlows();
        for (SequenceFlow outgoingFlow : outgoingFlows) {
            String targetRef = outgoingFlow.getTargetRef();
            if (targetRef.equals(key)) {
                return key;
            }
        }
        return null;
    }

    private List<PreDoUser> getPreDoUsers(List<SysUser> userList) {
        List<PreDoUser> users = new ArrayList<>();
        if (!userList.isEmpty()) {
            Map<String, List<SysUser>> map = userList.stream().collect(Collectors.groupingBy(SysUser::getPostName));
            map.forEach((k, v) -> {
                PreDoUser preDoUser = new PreDoUser();
                preDoUser.setRealName(k);
                if (!v.isEmpty()) {
                    preDoUser.setId(v.get(0).getPostId());
                }
                for (SysUser sysUser : v) {
                    sysUser.setId(v.get(0).getPostId() + "_" + sysUser.getId());
                }
                preDoUser.setUserList(v);
                users.add(preDoUser);
            });
        }
        return users;
    }

    @Override
    public List<PreDoUser> preForward(SimpleUser simpleUser) {
        List<PreDoUser> users = new ArrayList<>();
        DataResult<List<SysUser>> result = userFeignClient.selectAllPostUser();
        if (200 == result.getCode()) {
            List<SysUser> userList = result.getData();
            //过滤其他公司的人
            if (!simpleUser.getDeptId().equals(155)) {
                userList = userList.stream().filter(s -> {
                    if (s.getDeptId().equals(simpleUser.getDeptId())) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
            }
            users = getPreDoUsers(userList);
        }
        return users;
    }

    @Override
    public List<PreDoUser> getFristPreDo(TaskUserReq taskUserReq) {
        ProcessOrder processOrder = new ProcessOrder();
        processOrder.setTenantId(String.valueOf(taskUserReq.getTenantId()));
        processOrder.setUserId(taskUserReq.getUserId());
        //根据用户id查询对应表单数据
        OrderForm orderForm = new OrderForm();
        if(taskUserReq.getOrderForm() != null ){
            orderForm = orderFormMapper.selectByOrderId(taskUserReq.getOrderForm().getId());
        }else{
            //根据用户id查询对应表单数据
            orderForm = orderFormMapper.selectByUserId(taskUserReq.getUserId());
        }

        List<SysUser> users = getFristUsers(orderForm.getProcessInstanceKey());
        //过滤其他公司的人
        if (!taskUserReq.getDeptId().equals("155")) {
            users = users.stream().filter(s -> {
                if (s.getDeptId().toString().equals(taskUserReq.getDeptId())) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        List<PreDoUser> preDoUsers = getPreDoUsers(users);
        return preDoUsers;
    }

    @Override
    public void getFristApproval(DoTaskReq doTaskReq) {
        OrderForm orderForm = new OrderForm();
        if(doTaskReq.getOrderForm() != null ){
            orderForm = orderFormMapper.selectByOrderId(doTaskReq.getOrderForm().getId());
        }else{
            //根据用户id查询对应表单数据
            orderForm = orderFormMapper.selectByUserId(doTaskReq.getSenderId());
        }
        ProcessOrder processOrder = new ProcessOrder();
        processOrder.setUserList(doTaskReq.getCandidateUserList());
        processOrder.setUserId(doTaskReq.getSenderId());
        processOrder.setKey(orderForm.getProcessInstanceKey());
        processOrder.setTenantId(doTaskReq.getTenantId());

        String createProcess = getCreateProcess(processOrder, orderForm);

        orderForm.setProcessInstanceId(createProcess);
        orderForm.setSuggestion(doTaskReq.getSuggestion());
        orderFormMapper.updateStatus(orderForm);
        orderFormMapper.update(orderForm);
        //更新巡检故障表对应故障状态至1-已分配未处理
        updateInspectionFault(orderForm.getId(),1);
    }

    @Override
    public TaskOrderInfo firstTaskInfo(CirculationTaskReq taskReq) {
        TaskOrderInfo taskOrderInfo = new TaskOrderInfo();
        //根据用户id查询对应表单数据
        OrderForm orderForm = new OrderForm();
        if(taskReq.getOrderFormId()!= null){
            orderForm = orderFormMapper.selectByOrderId(taskReq.getOrderFormId());
        }else{
            orderForm = orderFormMapper.selectByUserId(taskReq.getAssigneeUser());
        }
        taskOrderInfo.setOrderForm(orderForm);
        taskOrderInfo.setUser(true);
        taskOrderInfo.setBack(false);
        taskOrderInfo.setCirculation(1);
        taskOrderInfo.setAccept(false);
        taskOrderInfo.setForward(false);
        taskOrderInfo.setCancel(false);
        taskOrderInfo.setUpdateTitle(true);
        if (orderForm != null) {
            taskOrderInfo.setTitle(orderForm.getTitle());
            if (orderForm.getOrderFiles().isEmpty()) {
                List<OrderFile> orderFiles = orderForm.getOrderFiles();
                orderFiles = orderFiles.stream()
                        .sorted(Comparator.comparing(OrderFile::getSort, Comparator.nullsLast(Integer::compare)))
                        .collect(Collectors.toList());
                orderForm.setOrderFiles(orderFiles);
                taskOrderInfo.setOrderForm(orderForm);
            }
        }
        return taskOrderInfo;
    }

    @Override
    public void saveOrderForm(TaskUserReq taskReq) {
        OrderForm orderForm = taskReq.getOrderForm();
        if (orderForm != null) {
            orderFormMapper.update(taskReq.getOrderForm());
            //先删除之前的数据
            orderFormMapper.deleteFile(orderForm.getId());
            if (!orderForm.getOrderFiles().isEmpty()) {
                List<OrderFile> orderFiles = orderForm.getOrderFiles();
                if (!orderFiles.isEmpty()) {
                    for (OrderFile orderFile : orderFiles) {
                        orderFile.setOrderFormId(orderForm.getId());
                        int j = orderFormMapper.insertOrderFileOne(orderFile);
                        if (j < 0) {
                            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_UPDATE_ERROR);
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<HisTaskResp> detailsFirstTask(CirculationTaskReq taskReq) {
        List<HisTaskResp> list = new ArrayList<>();
        OrderForm orderForm = new OrderForm();
        if(taskReq.getOrderFormId()!= null){
            orderForm = orderFormMapper.selectByOrderId(taskReq.getOrderFormId());
        }else{
            orderForm = orderFormMapper.selectByUserId(taskReq.getAssigneeUser());
        }
        HisTaskResp hisTaskResp = new HisTaskResp();
        if (orderForm != null) {
            hisTaskResp.setName("发起工单");
            hisTaskResp.setOrderForm(orderForm);
            String userId = orderForm.getUserId();
            if (!StringUtils.isEmpty(userId)) {
                DataResult<SysUser> result = userFeignClient.getUserById(userId);
                if (result.getCode() == 200 && result.getData() != null) {
                    SysUser user = result.getData();
                    if (user != null) {
                        hisTaskResp.setUserName(user.getRealName());
                    }
                }
            }
            hisTaskResp.setStartTime(orderForm.getCreateTime());
            hisTaskResp.setEndTime(orderForm.getCreateTime());
            hisTaskResp.setSuggestion(orderForm.getSuggestion());
            list.add(hisTaskResp);
        }
        return list;
    }

    @Override
    public TaskOrderInfo taskInfo(CirculationTaskReq taskReq) {
        //查询该流程实例的实时任务节点
        Task task = taskService.createTaskQuery()
                .processInstanceId(taskReq.getProcessInstId())
                .singleResult();

        //创建返回对象
        TaskOrderInfo taskOrderInfo = new TaskOrderInfo();
        if (task != null) {
            //查询执行人
            String assignee = task.getAssignee();
            //查询当前节点
            FlowNode flowNode = getFlowNode(taskReq.getProcessInstId());
            //查询任务表单数据
            HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery()
                    .taskId(task.getId())
                    .variableName("orderForm")
                    .singleResult();
            String value = "";
            if (historicVariableInstance != null && historicVariableInstance.getValue() != null) {
                value = historicVariableInstance.getValue().toString();
            }
            OrderForm orderForm = JSONObject.parseObject(value, OrderForm.class);
            //获取任务code
            String taskCode = getTaskCode(task.getName());

            taskOrderInfo.setCode(taskCode);
            taskOrderInfo.setOrderForm(orderForm);
            taskOrderInfo.setUpdateTitle(false);
            taskOrderInfo.setTitle(orderForm != null ? orderForm.getTitle() : null);
            taskOrderInfo.setAccept(assignee == null ? true : false);
            taskOrderInfo.setCancel(assignee != null ? true : false);
            taskOrderInfo.setForward(true);
            //流转节点
            if (assignee != null) {
                //挂任务节点的流向方向
                List<SequenceFlow> outgoingFlows = flowNode.getOutgoingFlows();
                //判断流向方向的个数
                if (outgoingFlows.size() > 1) {
                    taskOrderInfo.setCirculation(2);
                } else {
                    taskOrderInfo.setCirculation(1);
                }
            } else {
                taskOrderInfo.setCirculation(0);
            }
            //回退节点
            if (flowNode != null) {
                //所有节点
                FlowElementsContainer parentContainer = flowNode.getParentContainer();
                //回退
                List<SequenceFlow> incomingFlows = flowNode.getIncomingFlows();
                List<String> BeforeNodeNames = new ArrayList<>();
                for (SequenceFlow incomingFlow : incomingFlows) {
                    BeforeNodeNames.add(incomingFlow.getSourceRef());
                }
                //遍历判断是否有开始节点
                for (String flowNodeName : BeforeNodeNames) {
                    FlowElement flowElement = parentContainer.getFlowElement(flowNodeName);
                    if (flowElement instanceof StartEvent) {
                        taskOrderInfo.setBack(false);
                        break;
                    } else {
                        taskOrderInfo.setBack(assignee == null ? false : true);
                    }
                }
                //前进
                List<SequenceFlow> outgoingFlows = flowNode.getOutgoingFlows();
                List<String> afterNodeNames = new ArrayList<>();
                for (SequenceFlow outgoingFlow : outgoingFlows) {
                    afterNodeNames.add(outgoingFlow.getTargetRef());
                }
                for (String flowNodeName : afterNodeNames) {
                    FlowElement flowElement = parentContainer.getFlowElement(flowNodeName);
                    if (flowElement instanceof EndEvent) {
                        taskOrderInfo.setUser(false);
                        break;
                    } else if (flowElement instanceof Gateway) {
                        Gateway gateway = (Gateway) flowElement;
                        List<SequenceFlow> gatewayOutgoingFlows = gateway.getOutgoingFlows();
                        List<String> gatewayAfterNodeNames = new ArrayList<>();
                        for (SequenceFlow gatewayOutgoingFlow : gatewayOutgoingFlows) {
                            gatewayAfterNodeNames.add(gatewayOutgoingFlow.getTargetRef());
                        }
                        for (String nodeName : gatewayAfterNodeNames) {
                            FlowElement element = parentContainer.getFlowElement(nodeName);
                            if (element instanceof EndEvent) {
                                taskOrderInfo.setUser(false);
                                break;
                            } else {
                                taskOrderInfo.setUser(true);
                            }
                        }
                    } else {
                        taskOrderInfo.setUser(true);
                    }
                }
            } else {
                taskOrderInfo.setBack(false);
            }
            //返回文件排序
            if (orderForm != null && !orderForm.getOrderFiles().isEmpty()) {
                List<OrderFile> orderFiles = orderForm.getOrderFiles();
                orderFiles = orderFiles.stream()
                        .sorted(Comparator.comparing(OrderFile::getSort, Comparator.nullsLast(Integer::compare)))
                        .collect(Collectors.toList());
                orderForm.setOrderFiles(orderFiles);
                taskOrderInfo.setOrderForm(orderForm);
            }
        } else {
            List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(taskReq.getProcessInstId())
                    .finished()
                    .orderByHistoricTaskInstanceEndTime()
                    .desc()
                    .list();
            HistoricTaskInstance historicTaskInstance = historicTaskInstances.get(0);
            //查询任务表单数据
            HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery()
                    .taskId(historicTaskInstance.getId())
                    .variableName("orderForm")
                    .singleResult();
            String value = "";
            if (historicVariableInstance != null && historicVariableInstance.getValue() != null) {
                value = historicVariableInstance.getValue().toString();
            }
            OrderForm orderForm = JSONObject.parseObject(value, OrderForm.class);
            taskOrderInfo.setOrderForm(orderForm);
            taskOrderInfo.setUser(false);
            taskOrderInfo.setBack(false);
            taskOrderInfo.setCirculation(0);
            taskOrderInfo.setAccept(false);
            taskOrderInfo.setForward(false);
            taskOrderInfo.setCancel(false);
            taskOrderInfo.setUpdateTitle(false);
            taskOrderInfo.setTitle(orderForm.getTitle());
            if (orderForm != null && !orderForm.getOrderFiles().isEmpty()) {
                List<OrderFile> orderFiles = orderForm.getOrderFiles();
                orderFiles = orderFiles.stream()
                        .sorted(Comparator.comparing(OrderFile::getSort, Comparator.nullsLast(Integer::compare)).reversed())
                        .collect(Collectors.toList());
                orderForm.setOrderFiles(orderFiles);
                taskOrderInfo.setOrderForm(orderForm);
            }
        }
        return taskOrderInfo;
    }

    @Override
    public void doClaimTask(TaskUserReq taskReq) {
        Task task = taskService.createTaskQuery().processInstanceId(taskReq.getProcessInstId())
                //集团Id一定要带着
                .taskTenantId(taskReq.getTenantId())
                .singleResult();
        //判断任务是否存在,还要判断任务是否已经被认领了
        String assignee = task.getAssignee();
        if (assignee != null) {
            throw new BusinessException(BaseResponseCode.TASK_ALREADY_CLAIM_BY_OTHER);
        }
        if (task != null) {
            try {
                taskService.claim(task.getId(), taskReq.getUserId());
            } catch (Exception e) {
                log.error("认领任务时出错 ,task:{}, userId: {}", task.getId(), taskReq.getUserId());
                log.error(e.getMessage());
                //throw new BusinessException(BaseResponseCode.TASK_ALREADY_CLAIM_BY_OTHER);
            }
        }
    }

    @Override
    public void save(TaskUserReq taskReq) {
        Task task = taskService.createTaskQuery().processInstanceId(taskReq.getProcessInstId())
                //集团Id一定要带着
                .taskTenantId(taskReq.getTenantId())
                .singleResult();

        taskService.setVariableLocal(task.getId(), "orderForm", taskReq.getOrderForm());
    }

    @Override
    public void cancel(TaskUserReq taskReq) {
        //查询当前任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(taskReq.getProcessInstId())
                .singleResult();
        taskService.setVariableLocal(task.getId(), "cancel", true);
        runtimeService.deleteProcessInstance(taskReq.getProcessInstId(), taskReq.getSuggestion());
    }


    private OrderForm getHisOrderForm(HistoricTaskInstance historicTaskInstance, String pocessInstId) {
        HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery()
                .taskId(historicTaskInstance.getId())
                .processInstanceId(pocessInstId)
                .variableName("orderForm")
                .singleResult();
        OrderForm orderForm = new OrderForm();
        if (historicVariableInstance != null) {
            String value = historicVariableInstance.getValue().toString();
            orderForm = JSONObject.parseObject(value, OrderForm.class);
        }
        return orderForm;
    }


    public FlowElement getNextUserFlowElement(String processInstanceId) {
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        if (task == null) {
            throw new BusinessException(5000, "流程未启动或已执行完成");
        }
        // 取得已提交的任务
        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery()
                .taskId(task.getId()).singleResult();
        // 取得正在流转的流程实例,若已完成则为null

        ProcessInstance processInstance = getRuntimeProcessInstance(historicTaskInstance.getProcessInstanceId());
        //每个流程实例只有一个executionId
        //获得流程定义
        ProcessDefinition processDefinition = repositoryService.getProcessDefinition(historicTaskInstance.getProcessDefinitionId());

        //获得当前流程的活动ID
        ExecutionQuery executionQuery = runtimeService.createExecutionQuery();
        Execution execution = executionQuery.executionId(historicTaskInstance.getExecutionId()).singleResult();
        String activityId = execution.getActivityId();
        UserTask userTask = null;
        while (true) {
            //根据活动节点获取当前的组件信息
            FlowNode flowNode = getFlowNode(processDefinition.getId(), activityId);
            //获取该流程组件的之后/之前的组件信息
            List<SequenceFlow> sequenceFlowListOutGoing = flowNode.getOutgoingFlows();
//        List<SequenceFlow> sequenceFlowListIncoming=flowNode.getIncomingFlows();

            //获取的下个节点不一定是userTask的任务节点，所以要判断是否是任务节点
            //sequenceFlowListOutGoing数量可能大于1,可以自己做判断,此处只取第一个
            FlowElement flowElement = sequenceFlowListOutGoing.get(0).getTargetFlowElement();
            if (flowElement instanceof UserTask) {
                userTask = (UserTask) flowElement;
                System.out.println("获取该任务节点的审批信息...");
                break;
            } else {
                //下一节点不是任务userTask的任务节点,所以要获取再下一个节点的信息,直到获取到userTask任务节点信息
                String flowElementId = flowElement.getId();
                activityId = flowElementId;
                continue;
            }
        }
        return null;
    }

    /**
     * 流程实例对象
     *
     * @param processInstanceId 流程实例id
     * @return
     */
    private ProcessInstance getRuntimeProcessInstance(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        return processInstance;
    }


    /**
     * 获取所有流向元素
     *
     * @param processDefinitionId
     * @return
     */
    public List<SequenceFlow> getSequenceFlow(String processDefinitionId) {
        List<SequenceFlow> list = new ArrayList<>();
        Collection<FlowElement> flowElements = getAllElements(processDefinitionId);
        for (FlowElement flowElement : flowElements) {
            SequenceFlow sequenceFlow = new SequenceFlow();
            if (flowElement instanceof SequenceFlow) {
                sequenceFlow = (SequenceFlow) flowElement;
                list.add(sequenceFlow);
            }
        }
        return list;
    }

    /**
     * 获取流向元素中的表达式内容
     *
     * @param list 流向元素集合
     * @return
     */
    public List<SequenceText> getSequenceFlowText(List<SequenceFlow> list) {
        List<SequenceText> textList = new ArrayList<>();
        for (SequenceFlow sequenceFlow : list) {
            SequenceText text = new SequenceText();
            text.setSource(sequenceFlow.getSourceRef());
            text.setTarget(sequenceFlow.getTargetRef());
            text.setExpression(sequenceFlow.getConditionExpression());
            textList.add(text);
        }
        return textList;
    }

    /**
     * 获取所有用户任务元素
     *
     * @param processDefinitionId
     * @return
     */
    public List<UserTask> getUserTask(String processDefinitionId) {
        List<UserTask> list = new ArrayList<>();
        Collection<FlowElement> flowElements = getAllElements(processDefinitionId);
        for (FlowElement flowElement : flowElements) {
            UserTask userTask = new UserTask();
            if (flowElement instanceof UserTask) {
                userTask = (UserTask) flowElement;
                list.add(userTask);
            }
        }
        return list;
    }

    /**
     * 获取用户任务文本信息
     *
     * @param list 用户任务元素集合
     * @return
     */
    public List<UserTaskText> getUserTask(List<UserTask> list) {
        List<UserTaskText> textList = new ArrayList<>();
        for (UserTask userTask : list) {
            UserTaskText text = new UserTaskText();
            text.setUserTaskId(userTask.getId());
            text.setCode(userTask.getCandidateGroups());
        }
        return textList;
    }

    /**
     * 获取流程中所有元素
     *
     * @param processDefinitionId
     * @return
     */
    private Collection<FlowElement> getAllElements(String processDefinitionId) {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        Process mainProcess = bpmnModel.getMainProcess();
        Collection<FlowElement> flowElements = mainProcess.getFlowElements();
        return flowElements;
    }

    private FlowNode getHisFlowNode(String taskId) {
        HistoricTaskInstance hisTask = historyService.createHistoricTaskInstanceQuery()
                .taskId(taskId).singleResult();
        //回退节点的executionId
        String hisExecutionId = hisTask.getExecutionId();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(hisTask.getProcessDefinitionId());
        //找出退回节点act
        String hisActivityId = null;
        List<HistoricActivityInstance> hisFinishList = historyService.createHistoricActivityInstanceQuery()
                .executionId(hisExecutionId)
                .finished()
                .list();

        for (HistoricActivityInstance historicActivityInstance : hisFinishList) {
            if (historicActivityInstance.getTaskId() != null &&
                    historicActivityInstance.getTaskId().equals(hisTask.getId())) {
                hisActivityId = historicActivityInstance.getActivityId();
                break;
            }
        }
        //获取节点的信息
        FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(hisActivityId);
        return flowNode;
    }

    /**
     * 获取当前节点
     *
     * @param processInstId
     * @return
     */
    private FlowNode getFlowNode(String processInstId) {
        //查询指定的回退任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstId).singleResult();
        //当前节点executionId
        String executionId = task.getExecutionId();
        //获取当前节点的信息
        Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        String activityId = execution.getActivityId();

        FlowNode flowNode = getFlowNode(task.getProcessDefinitionId(), activityId);
        return flowNode;
    }

    /**
     * 节点
     *
     * @param processDefinitionId 流程默认id
     * @param activityId
     * @return
     */
    public FlowNode getFlowNode(String processDefinitionId, String activityId) {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId);
        return flowNode;
    }

    /**
     * 映射对应任务节点的code
     */
    public String getTaskCode(String taskName) {
        String code = "";
        switch (taskName) {
            case "主管审批":
                code = "task001";
                break;
            case "运维审批":
                code = "task002";
                break;
            case "经理审批":
                code = "task003";
                break;
        }
        return code;
    }

    /**
     * 返回表达式里的所有key(去重)
     *
     * @param s 表达式字符串
     * @return
     */
    public static HashSet<String> getKeys(String s) {
        HashSet<String> list = new HashSet<String>();
        String pattern = "[a-zA-Z]+(==|>=|<=|<|>)";
        String pattern1 = "[a-zA-Z]+";
        Pattern p = Pattern.compile(pattern);
        Pattern p1 = Pattern.compile(pattern1);
        Matcher m = p.matcher(s.replaceAll(" ", ""));
        while (m.find()) {
            Matcher matcher = p1.matcher(m.group());
            while (matcher.find()) {
                list.add(matcher.group());
            }
        }
        return list;
    }


    /**
     * 获取开始节点
     *
     * @param processInstId
     * @return
     */
    private HisTaskResp getStartEvent(String processInstId) {
        OrderForm orderForm = orderFormMapper.selectByProcessInstanceId(processInstId);
        if (orderForm != null) {
            HisTaskResp hisTaskResp = new HisTaskResp();
            hisTaskResp.setName("发起工单");
            hisTaskResp.setOrderForm(orderForm);
            String userId = orderForm.getUserId();
            if (!StringUtils.isEmpty(userId)) {
                DataResult<SysUser> result = userFeignClient.getUserById(userId);
                if (result.getCode() == 200 && result.getData() != null) {
                    SysUser user = result.getData();
                    if (user != null) {
                        hisTaskResp.setUserName(user.getRealName());
                    }
                }
            }
            hisTaskResp.setStartTime(orderForm.getCreateTime());
            hisTaskResp.setEndTime(orderForm.getCreateTime());
            hisTaskResp.setSuggestion(orderForm.getSuggestion());
            return hisTaskResp;
        } else {
            return null;
        }
    }

    private List<HistoricTaskInstance> getBeforeUserTask(String processInstId) {
        //查询当前任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstId)
                .singleResult();
        //当前节点executionId
        String executionId = task.getExecutionId();
        //获取当前节点的信息
        Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        Execution execution1 = runtimeService.createExecutionQuery().executionId(execution.getParentId()).singleResult();
        String activityId = execution.getActivityId();
        String activityId1 = execution1.getActivityId();

        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId);
        FlowNode flowNode1 = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId1);

        //查询被指向节点
        Collection<FlowElement> flowElements = bpmnModel.getMainProcess().getFlowElements();
        List<String> flowIds = new ArrayList<>();
        List<SequenceFlow> incomingFlows = flowNode.getIncomingFlows();


        //所有任务节点
        List<UserTask> userTask = getUserTask(task.getProcessDefinitionId());


        //查询历史任务
        List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstId)
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();

        return null;

    }

    private void updateInspectionFault(Integer orderId,Integer status){
        InspectionFaultVo vo = new InspectionFaultVo();
        vo.setOrderId(orderId);
        vo.setStatus(status);
        try {
            businessFeignClient.updateInspectionFault(vo);
        }catch (Exception e){
            log.error("exec updateInspectionFault error:{}",e.getMessage());
        }
    }
}
