package com.trade.admin.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.trade.admin.system.domain.entity.SysUser;
import com.trade.admin.system.security.utils.SecurityUtils;
import com.trade.admin.system.service.ISysUserService;
import com.trade.admin.workflow.util.FlowableConstantUtil;
import com.trade.admin.workflow.domain.BusinessProcessingLog;
import com.trade.admin.workflow.dto.*;
import com.trade.admin.workflow.service.FlowActivityDefinitionService;
import com.trade.admin.workflow.service.FlowableService;
import com.trade.admin.workflow.domain.FlowActivityDefinition;
import com.trade.admin.workflow.domain.Project;
import com.trade.admin.workflow.mapper.FlowActivityDefinitionMapper;
import com.trade.admin.workflow.service.BusinessProcessingLogService;
import com.trade.admin.workflow.util.FlowableUtil;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.page.GridPage;
import com.trade.common.exception.ServiceException;
import com.trade.common.exception.ValidatorException;
import com.trade.service.filestorage.entity.TFileStorage;
import com.trade.service.filestorage.service.TFileStorageService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.NativeTaskQuery;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipInputStream;

@Service
public class FlowableServiceImpl implements FlowableService {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private FlowActivityDefinitionService flowActDefService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private BusinessProcessingLogService processingLogService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private FlowActivityDefinitionMapper flowActivityDefinitionMapper;
    @Autowired
    private TFileStorageService fileStorageService;

    @Override
    public GridPage<ProcessDefinitionEntityVo> findLatestProcdef(SearchProcessDefinition search) {
        if (null == search) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "列表分页条件不能为空！");
        }
        List<ProcessDefinition> procdefList = repositoryService.createProcessDefinitionQuery()
                .listPage((search.getPage() - 1) * search.getRows(), search.getPage() * search.getRows());
        Map<String, ProcessDefinition> filterMap = new HashMap<>();
        if (CollUtil.isNotEmpty(procdefList)) {
            filterMap = procdefList.stream().collect(Collectors.toMap(ProcessDefinition::getId, Function.identity(), (v1, v2) -> v2));
        }
        List<ProcessDefinitionEntityVo> rows = new ArrayList<>();
        for (ProcessDefinition pd : filterMap.values()) {
            rows.add(new ProcessDefinitionEntityVo(pd));
        }

        long count = repositoryService.createProcessDefinitionQuery().count();
        return new GridPage<>(search.getRows(), search.getPage(), count, rows);
    }

    @Override
    @Transactional
    public Deployment deploy(DeployRequest deployRequest) {
        TFileStorage fileStorage = fileStorageService.getFileStorageById(deployRequest.getId());
        if (fileStorage == null) {
            throw new ServiceException("部署文件不存在", HttpStatus.ERROR);
        }
        ZipInputStream zipIn = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(fileStorage.getAbsolutePath());
            zipIn = new ZipInputStream(fileInputStream);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), HttpStatus.ERROR);
        }
        Deployment deployment = repositoryService.createDeployment().name(deployRequest.getDeployName())
                .addZipInputStream(zipIn).deploy();
        if (null != deployment) {
            // 部署结束后，还需要根据流程定义key、版本、id过滤，后台设置流程节点，区别是否允许设置之前版本的节点办理人问题
            ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery()
                    .deploymentId(deployment.getId()).singleResult();
            if (null != procDef) {
                BpmnModel model = repositoryService.getBpmnModel(procDef.getId());
                if (model != null) {
                    Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
                    for (FlowElement e : flowElements) {
                        // 过滤用户任务
                        if (e instanceof UserTask) {
                            FlowActivityDefinition flowActDef = new FlowActivityDefinition();
                            flowActDef.setProcessDefinitionId(procDef.getId());
                            flowActDef.setProcessDefinitionKey(procDef.getKey());
                            flowActDef.setProcessDefinitionVersion(procDef.getVersion());
                            flowActDef.setActivityKey(e.getId());
                            flowActDef.setActivityName(e.getName());
                            flowActDef.setActivityType(FlowableConstantUtil.FLOWABLE_ACTTYPE_USERTASK);
                            flowActDefService.add(flowActDef);
                        }
                    }
                }
            }
        }
        return deployment;
    }

    @Override
    public void viewImg(HttpServletResponse response, String deploymentId, String resourceName) {
        InputStream input = repositoryService.getResourceAsStream(deploymentId, resourceName);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.close();
            input.close();
        } catch (IOException e) {
            throw new ServiceException(e.getMessage(), HttpStatus.ERROR);
        }
    }

    @Override
    @Transactional
    public ProcessInstance startProcessInstance(Project entity, Map<String, Object> procVariables, String queryBusiness,
                                                Map<String, Object> msgVariables, String key) {
        if (null == entity || null == entity.getId()) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "流程业务实体信息不能为空！");
        }
        if (null == procVariables || procVariables.isEmpty()) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "流程变量map不能为空！");
        }
        if (StrUtil.isEmpty(queryBusiness)) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "流程businessKey信息不能为空！");
        }

        // 1.开启流程实例
        ProcessInstance procInst = runtimeService.startProcessInstanceByKey(key, queryBusiness, procVariables);
        if (null != procInst && StrUtil.isNotEmpty(procInst.getId())) {
            List<Task> pendingTasks = taskService.createTaskQuery().processInstanceId(procInst.getId()).list();
            if (CollUtil.isNotEmpty(pendingTasks)) {
                for (Task task : pendingTasks) {
                    BusinessProcessingLog processingLog = new BusinessProcessingLog();
                    if (task.getAssignee() != null) {
                        Long assignee = Long.parseLong(task.getAssignee());
                        processingLog.setAssignee(sysUserService.selectUserById(assignee));
                    }
                    // 2.添加业务处理日志
                    processingLog.setBusinessKey(entity.getId());
                    processingLog.setBusinessType(key);
                    processingLog.setHistoricTaskId(task.getId());
                    processingLog.setAssigneeType(FlowableConstantUtil.PROCESS_TASK);
                    processingLog.setTaskDefKey(task.getTaskDefinitionKey());
                    processingLog.setTaskName(task.getName());
                    processingLog.setStartTime(task.getCreateTime());
                    processingLogService.add(processingLog);
                }
            }
        }
        return procInst;
    }

    @Override
    public List<Task> findMyPendingListPage(SearchBusinessProcessingTask search, String procDefinitionKey) {
        // procDefinitionKey：由于业务流程比较多，可能存在不同业务上的待我办任务，故查询时，就要结合业务KEY，查询具体业务上的“我的任务”
        if (null == search || StrUtil.isEmpty(procDefinitionKey)) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "列表分页条件不能为空！");
        }
        // 直接分配给当前人或者已签收的任务，银科业务系统目前是直接办理人，故暂时这么coding
        List<Task> doingTasks;
        if (StrUtil.isNotEmpty(search.getTaskId())) {
            // 系统待办消息跳转查询指定taskId的任务
            doingTasks = taskService.createTaskQuery().taskId(search.getTaskId()).list();
        } else {
            String sql = "SELECT DISTINCT RES.* FROM ACT_RU_TASK RES " +
                    "LEFT JOIN ACT_RU_IDENTITYLINK I ON I.TASK_ID_ = RES.ID_ AND I.USER_ID_ = #{assignee} " +
                    "INNER JOIN ACT_RE_PROCDEF D ON RES.PROC_DEF_ID_ = D.ID_ " +
                    "INNER JOIN ACT_RU_EXECUTION E ON RES.PROC_INST_ID_ = E.ID_ " +
                    "WHERE D.KEY_ LIKE #{procDefinitionKey}" +
                    "AND (RES.ASSIGNEE_ = #{assignee} OR (RES.ASSIGNEE_ IS NULL AND I.TYPE_ = 'candidate' AND ( I.USER_ID_ = #{assignee} )))";

            StringBuffer stringBuffer = new StringBuffer();
            NativeTaskQuery nativeTaskQuery = getNativeTaskQuery(search, procDefinitionKey, stringBuffer, sql);
            stringBuffer.append("ORDER BY RES.CREATE_TIME_ DESC ");
            doingTasks = nativeTaskQuery.sql(stringBuffer.toString())
                    .listPage((search.getPage() - 1) * search.getRows(), search.getPage() * search.getRows());
        }
        // 多种实现方式，5.16之后版本提供如下简化查询方式，查询
        // doingTasks =
        // taskService.createTaskQuery().taskCandidateOrAssigned(ThreadLocalUtil.getUserId().toString()).list();
        return doingTasks;
    }

    @Override
    public long countMyPendingListPage(SearchBusinessProcessingTask search, String procDefinitionKey) {
        if (null == search || StrUtil.isEmpty(procDefinitionKey)) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "列表分页条件不能为空！");
        }
        long count;
        if (StrUtil.isNotEmpty(search.getTaskId())) {
            count = taskService.createTaskQuery().taskId(search.getTaskId()).count();
        } else {
            String sql = "SELECT COUNT(*) FROM ACT_RU_TASK RES " +
                    "LEFT JOIN ACT_RU_IDENTITYLINK I ON I.TASK_ID_ = RES.ID_ AND I.USER_ID_ = #{assignee} " +
                    "INNER JOIN ACT_RE_PROCDEF D ON RES.PROC_DEF_ID_ = D.ID_ " +
                    "INNER JOIN ACT_RU_EXECUTION E ON RES.PROC_INST_ID_ = E.ID_ " +
                    "WHERE D.KEY_ LIKE #{procDefinitionKey}" +
                    "AND (RES.ASSIGNEE_ = #{assignee} OR (RES.ASSIGNEE_ IS NULL AND I.TYPE_ = 'candidate' AND ( I.USER_ID_ = #{assignee} )))";
            StringBuffer stringBuffer = new StringBuffer();
            NativeTaskQuery nativeTaskQuery = getNativeTaskQuery(search, procDefinitionKey, stringBuffer, sql);
            count = nativeTaskQuery.sql(stringBuffer.toString()).count();
        }
        return count;
    }

    private NativeTaskQuery getNativeTaskQuery(SearchBusinessProcessingTask search, String procDefinitionKey, StringBuffer stringBuffer, String sql) {
        String userId = SecurityUtils.getUserId().toString();
        NativeTaskQuery nativeTaskQuery = taskService.createNativeTaskQuery()
                .parameter("assignee", userId)
                .parameter("procDefinitionKey", procDefinitionKey + "%");

        stringBuffer.append(sql);
        if (StrUtil.isNotEmpty(search.getFastSearch())) {
            stringBuffer.append("AND E.BUSINESS_KEY_ LIKE #{fastSearch} ");
            nativeTaskQuery.parameter("fastSearch", "%" + search.getFastSearch() + "%");
        }
        if (search.getStartDate() != null) {
            stringBuffer.append("AND DATE(RES.CREATE_TIME_) >= DATE(#{startDate}) ");
            nativeTaskQuery.parameter("startDate", search.getStartDate());
        }
        if (search.getEndDate() != null) {
            stringBuffer.append("AND DATE(RES.CREATE_TIME_) <= DATE(#{endDate}) ");
            nativeTaskQuery.parameter("endDate", search.getEndDate());
        }
        return nativeTaskQuery;
    }

    @Override
    public List<HistoricTaskInstance> findMyCompletedListPage(SearchBusinessProcessingTask search,
                                                              String processDefinitionKey) {

        HistoricTaskInstanceQuery historicTaskInstanceQuery = getHistoricTaskInstanceQuery(search, processDefinitionKey);
        return historicTaskInstanceQuery
                .listPage((search.getPage() - 1) * search.getRows(), search.getPage() * search.getRows());
    }

    @Override
    public long countMyCompletedListPage(SearchBusinessProcessingTask search, String procDefinitionKey) {
        HistoricTaskInstanceQuery historicTaskInstanceQuery = getHistoricTaskInstanceQuery(search, procDefinitionKey);
        return historicTaskInstanceQuery.count();
    }

    private HistoricTaskInstanceQuery getHistoricTaskInstanceQuery(SearchBusinessProcessingTask search, String procDefinitionKey) {
        if (null == search || StrUtil.isEmpty(procDefinitionKey)) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "列表分页条件不能为空！");
        }
        String userId = SecurityUtils.getUserId().toString();
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery()
                .finished() //表示已办理完
                .taskAssignee(userId)
                .processDefinitionKey(procDefinitionKey);
        if (StrUtil.isNotEmpty(search.getSourceBusinessId())) {
            if (StrUtil.isNotEmpty(search.getFastSearch())) {
                historicTaskInstanceQuery
                        .processInstanceBusinessKeyLike(search.getSourceBusinessId() + "%")
                        .processInstanceBusinessKeyLike("%" + search.getFastSearch() + "%");
            } else {
                historicTaskInstanceQuery
                        .processInstanceBusinessKeyLike(search.getSourceBusinessId() + "%");
            }
        } else {
            if (StrUtil.isNotEmpty(search.getFastSearch())) {
                historicTaskInstanceQuery
                        .processInstanceBusinessKeyLike("%" + search.getFastSearch() + "%");
            }
        }
        return historicTaskInstanceQuery;
    }

    @Override
    public Object getBusinessDataByProcessInst(String processInstId) {
        // 1.根据流程实例ID查询正在执行的对象表，返回流程实例对象
        ProcessInstance procInst = null;
        if (StrUtil.isNotEmpty(processInstId)) {
            procInst = runtimeService.createProcessInstanceQuery().processInstanceId(processInstId).singleResult();
        }
        // 2.根据流程实例关联的业务key，查询业务数据信息
        if (null != procInst) {
            String businessKey = procInst.getBusinessKey();
            return FlowableUtil.getBusinessDateById(businessKey);
        }
        return null;
    }

    @Override
    public Task getByTaskQuery(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    @Override
    public boolean duplicateAssigneeByTaskQuery(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        // 若task为null，可能任务已经完成
        if (task == null || StrUtil.isEmpty(task.getAssignee())) { // 该任务已经完成
            return false;
        }
        return task.getAssignee().equals(SecurityUtils.getUserId().toString());
    }

    @Override
    public HistoricTaskInstance getHistoricByTaskId(String taskId) {
        return historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
    }

    @Override
    public List<Task> findRuntimeTaskByProcessInstId(String processInstId) {
        return taskService.createTaskQuery().processInstanceId(processInstId).list();
    }

    @Override
    public ProcessInstance getRuntimeProcessInstById(String processInstId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstId).singleResult();
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstById(String processInstId) {
        return historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstId).singleResult();
    }

    @Override
    public ProcessInstance getRuntimeProcessInstByBusinessKey(String processDefKey, String processInstBusinessKey) {
        return runtimeService.createProcessInstanceQuery().processDefinitionKey(processDefKey)
                .processInstanceBusinessKey(processInstBusinessKey).singleResult();
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstByBusinessKey(String processDefKey,
                                                                       String processInstBusinessKey) {
        return historyService.createHistoricProcessInstanceQuery().processDefinitionKey(processDefKey)
                .processInstanceBusinessKey(processInstBusinessKey).singleResult();
    }

    @Override
    @Transactional
    public Boolean assignManager(Task assignableTask, Long assignee) {
        // 1.验证任务是否完成或者结束
        if (null == assignableTask) {
            throw new ValidatorException(HttpStatus.ERROR, "业务已完成，无法进行分配！");
        }
        if (StrUtil.isNotEmpty(assignableTask.getAssignee()) && null != assignee) {
            // 2.验证办理人是否重合
            if (assignableTask.getAssignee().equals(assignee.toString())) {
                throw new ValidatorException(HttpStatus.ERROR, "所选用户即为此业务跟进执行人，请重选！");
            }
            // 3.分配
            taskService.setAssignee(assignableTask.getId(), assignee.toString());
            // 4.设置流程变量
            // 说明:setVariable针对流程实例(ACT_HI_VARINST表TASK_ID_字段为null),即相同流程变量名，后一次的值会替换之前的，setVariableLocal仅针对指定taskId有效.
            taskService.setVariable(assignableTask.getId(),
                    assignableTask.getTaskDefinitionKey() + FlowableConstantUtil.ASSIGNEE,
                    assignee);// 注意：要求与业务中设置流程变量类型一致，字符串的为字符串，数值类型为数值类型。
            // 5.验证分配是否成功
            Task task = taskService.createTaskQuery().taskId(assignableTask.getId()).singleResult();
            if (null != task && Objects.equals(task.getAssignee(), assignee.toString())) {
                return true;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public Boolean completeMyTask(String taskId, Project entity, Map<String, Object> procVariables, String result,
                                  Long formBusinessId, String key) {
        if (StrUtil.isEmpty(taskId)) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "任务ID为空");
        }
        if (entity == null || entity.getId() == null) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "流程业务ID为空");
        }
        if (formBusinessId == null) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "流程表单业务ID为空");
        }
        // 查看处理人最新的日志
        BusinessProcessingLog log = processingLogService.getLatestByTask(entity.getId(), key, taskId,
                FlowableConstantUtil.PROCESS_TASK);
        if (log == null) {
            throw new ValidatorException(HttpStatus.ERROR, "数据错误，处理人业务日志信息为空！");
        }
        String procInstId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        if (null == procVariables) {
            procVariables = new HashMap<>();
        }
        if (StrUtil.isNotEmpty(result)) {
            procVariables.put("result", result);
        } else {
            result = "提交";// 默认状态提交，不保存到流程变量中，记入业务处理日志状态中
        }
        Task processingtask = getByTaskQuery(taskId);
        if (null != processingtask) {
            if (!processingtask.getAssignee().equals(SecurityUtils.getUserId().toString())) {
                throw new ValidatorException(HttpStatus.ERROR, "提交失败，您并不是该业务处理人！");
            }
            FlowActivityDefinition flowActDef = flowActDefService.getByProcActKey(
                    processingtask.getProcessDefinitionId(), processingtask.getTaskDefinitionKey());
            if (StrUtil.isNotEmpty(log.getTaskDefKey())) {
                log.setStatus(result);
                log.setEndTime(new Date());
                Float overdue = null;
                if (flowActDef.getWorkingDay()) {
                    overdue = FlowableUtil.getBusinessDeadlineByWorkingDay(log.getGmtCreate(),
                            flowActDef.getTimeLimit());
                } else {
                    overdue = FlowableUtil.getBusinessOverdueByNatureDay(log.getGmtCreate(), flowActDef.getTimeLimit());
                }
                log.setFormBusinessId(formBusinessId);
                if (null != overdue && overdue < 0) {// 只展示逾期，故直接转换为正数
                    log.setOverdueDays(Math.abs(overdue));
                    log.setWorkingDay(flowActDef.getWorkingDay());
                }
                log.setEndTime(new Date());
                // 完成当前任务
                taskService.complete(taskId, procVariables);
                // 更新业务处理日志
                processingLogService.update(log);
            }
        }
        // 判断是否结束，更新业务数据状态
        ProcessInstance procInst = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId)
                .singleResult();

        // 1.当前节点为最后一个节点，故办理完任务后，流程实例结束
        if (null == procInst || StrUtil.isEmpty(procInst.getId())) {
            return true;
        } else {
            List<Task> pendingTasks = taskService.createTaskQuery().processInstanceId(procInst.getId()).list();
            if (CollUtil.isNotEmpty(pendingTasks)) {
                for (Task task : pendingTasks) {
                    // 流程业务待处理任务日志集合，注：一定要在循环内，同时过滤正在新增过的日志
                    List<String> pendingTaskIds = processingLogService.findPendingTaskByBusiness(entity.getId(), key);
                    // a.过滤掉已存在的并列或会签任务节点的日志信息
                    if (CollUtil.isNotEmpty(pendingTaskIds) && pendingTaskIds.contains(task.getId())) {
                        continue;
                    }
                    // 任务办理人
                    // b.添加业务处理日志
                    BusinessProcessingLog processingLog = new BusinessProcessingLog();
                    processingLog.setBusinessKey(entity.getId());
                    processingLog.setBusinessType(key);
                    processingLog.setHistoricTaskId(task.getId());
                    SysUser assignee = sysUserService.selectUserById(Long.parseLong(task.getAssignee())) == null ?
                            sysUserService.selectUserById(1L) :
                            sysUserService.selectUserById(Long.parseLong(task.getAssignee()));
                    if (task.getAssignee() != null) {
                        processingLog.setAssignee(assignee);
                    }
                    processingLog.setAssigneeType(FlowableConstantUtil.PROCESS_TASK);
                    processingLog.setTaskDefKey(task.getTaskDefinitionKey());
                    processingLog.setTaskName(task.getName());
                    processingLog.setStartTime(task.getCreateTime());
                    processingLogService.add(processingLog);
                }
                return true;
            } else {
                // 2.若当前节点不是最后一个节点，但办理条件，并不流转到下一个节点，这时候需要主动结束流程实例
                runtimeService.deleteProcessInstance(procInstId, result);
            }
        }

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void claimTask(String taskId, Long userId, String roleKey) {
        claimTask(taskId, userId, Collections.singletonList(roleKey));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void claimTask(String taskId, Long userId, List<String> roleKeys) {
        Boolean hasRole = sysUserService.checkUserHasRoles(userId, roleKeys);
        if (hasRole) {
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task.getAssignee() == null && task.getClaimTime() == null) {
                taskService.claim(taskId, userId.toString());
                BusinessProcessingLog processingLog = processingLogService.findByHistoricTaskId(taskId);
                if (processingLog != null) {
                    processingLog.setAssignee(sysUserService.selectUserById(userId));
                    processingLogService.updateAssigneeId(processingLog);
                }
            }
        } else {
            throw new ServiceException("当前用户没有办理该任务权限!", HttpStatus.UNAUTHORIZED);
        }

    }

    @Override
    public Boolean existTask(String historicTaskId) {
        Integer num = flowActivityDefinitionMapper.existTask(historicTaskId);
        return num > 0;
    }

    @Override
    public List<Task> findMyPendingList(String sourceBusinessId, String procDefinitionKey) {
        if (StrUtil.isEmpty(sourceBusinessId) || StrUtil.isEmpty(procDefinitionKey)) {
            throw new ValidatorException(HttpStatus.ERROR, "默认条件不能为空！");
        }
        return taskService.createTaskQuery().taskAssignee(SecurityUtils.getUserId().toString())
                .processDefinitionKey(procDefinitionKey).processInstanceBusinessKey(sourceBusinessId).list();
    }
}
