package com.ruoyi.flowable.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.FileType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sms.SmsSenderUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.flowable.common.constant.UUIDGenerator;
import com.ruoyi.flowable.common.enums.FlowStatusEnum;
import com.ruoyi.flowable.factory.FlowServiceFactory;
import com.ruoyi.flowable.service.*;
import com.ruoyi.invest.domain.*;
import com.ruoyi.invest.domain.vo.ProjectInvestigateVo;
import com.ruoyi.invest.mapper.InvestigateMapper;
import com.ruoyi.invest.mapper.TProjectScoringMapper;
import com.ruoyi.invest.service.*;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tool.service.ITUnifyFileService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 项目池Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-02-21
 */
@Service
public class InvestigateServiceImpl extends FlowServiceFactory implements IInvestigateService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private InvestigateMapper investigateMapper;
    @Autowired
    private ITProjectInvestigateService tProjectInvestigateService;
    @Autowired
    private ITProjectInvestigatePersonService tProjectInvestigatePersonService;
    @Autowired
    private ITProjectPoolService tProjectPoolService;
    @Autowired
    private ITProjectCirculationService tProjectCirculationService;

    @Autowired
    private ITUnifyFileService tUnifyFileService;

    @Autowired
    private IFlowBaseInfoService activitiBaseInfoService;
    @Autowired
    private IFlowInstanceService flowInstanceService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private IFlowService flowService;

    @Autowired
    private ISysFormService sysFormService;
    @Override
    public List<ProjectInvestigateVo> selectAllInvestigateList(TProjectInvestigate tProjectInvestigate){
        return investigateMapper.selectAllInvestigateList(tProjectInvestigate);
    }
    @Override
    public List<ProjectInvestigateVo> getMyTaskList(String userId, TProjectInvestigate tProjectInvestigate){
        return investigateMapper.getMyTaskList(userId, tProjectInvestigate);
    }
    @Override
    public List<ProjectInvestigateVo> getMyDoneTaskList(String userId, TProjectInvestigate tProjectInvestigate){
        return investigateMapper.getMyDoneTaskList(userId, tProjectInvestigate);
    }
    @Override
    public List<ProjectInvestigateVo> getMyList(String userId,TProjectInvestigate tProjectInvestigate){
        return investigateMapper.getMyList(userId, tProjectInvestigate);
    }
    /**
     * 查询项目池
     * 
     * @param pInstId 流程实例Id
     * @return 项目池
     */
    @Override
    public TProjectInvestigate selectTProjectInvestigateByProcInstId(String pInstId)
    {
        return investigateMapper.selectTProjectInvestigateByProcInstId(pInstId);
    }

    @Override
    public AjaxResult start(TProjectInvestigate tProjectInvestigate) {

        // 根据key值获取最新的流程部署id
        String pDefId = null;
        ProcessInstance pInst = null;
        try {
            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionKey("dgt-due-workflow")
                    .orderByProcessDefinitionVersion().desc().list();
            if(list.size()==0){
                return AjaxResult.error("未找到该流程，无法开启流程！");
            }
            pDefId = list.get(0).getId();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(pDefId)
                    .latestVersion().singleResult();
            if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
                return AjaxResult.error("流程已被挂起,请先激活流程");
            }
            if(StringUtils.isNotBlank(pDefId)){

                //设置参数
                Map<String, Object> formProperties = new HashMap<String, Object>();
                // 设置流程发起人Id到流程中
                SysUser sysUser = SecurityUtils.getLoginUser().getUser();
                identityService.setAuthenticatedUserId(sysUser.getUserId().toString());
                formProperties.put("auditPass",tProjectInvestigate.isFlag()?true:false);
                //暂存
                formProperties.put(ProcessConstants.PROCESS_INITIATOR, sysUser.getUserId());
                //投资部负责人
                String leader=sysDeptMapper.selectDeptLeader("投资部");
                formProperties.put("MANAGER",sysUserService.selectUserByUserName(leader).getUserId());
                //尽职背调上传人
                /*List<String> userIds = Arrays.asList(tProjectInvestigate.getInvestigatePersonId().split(","));
                formProperties.put("uploadList", userIds);*/
                pInst = runtimeService.startProcessInstanceById(pDefId, formProperties);
                if(pInst!=null){
                    String nickName= SecurityUtils.getLoginUser().getUser().getNickName();
                    String userId=SecurityUtils.getLoginUser().getUserId().toString();
                    //保存信息
                    tProjectInvestigate.setId(IdUtils.fastSimpleUUID());
                    tProjectInvestigate.setProcInstId(pInst.getProcessInstanceId());
                    tProjectInvestigate.setCreateBy(userId);
                    if(tProjectInvestigate.isFlag()){
                        tProjectInvestigate.setStatus(1);//提交
                    }else{
                        tProjectInvestigate.setStatus(0);//暂存
                    }
                    // todo 保存尽职背调附件信息
                    tUnifyFileService.insertTUnifyFileList(tProjectInvestigate.getListFile(),
                            tProjectInvestigate.getProjectPoolId(),
                            tProjectInvestigate.getId(),//尽调ID
                            String.valueOf(FileType.INVESTIGATE.ordinal()),//文件类型:尽调
                            nickName);

                    // todo 增加尽调创建记录
                    tProjectCirculationService.insertTProjectCirculation(tProjectInvestigate.getProjectPoolId(),tProjectInvestigate.getInvestigateName()+"(尽职背调)",nickName);

                    // todo 更改尽调状态
                    tProjectPoolService.updateTProjectPoolByInvestigateFlag(tProjectInvestigate.getProjectPoolId(),"1");

                    // todo 短信提醒
                    /*if(StringUtils.isNotEmpty(tProjectInvestigate.getInvestigatePersonId())){
                        StringUtils.str2List(tProjectInvestigate.getInvestigatePersonId(),",",true,true).stream().forEach(str -> {
                            SysUser user = sysUserService.selectUserById(Long.valueOf(str));
                            String contents = "您好，"+user.getNickName()+"，" + tProjectInvestigate.getProjectName() + "已开启尽职背调。";
                            try {
                                SmsSenderUtils.sendSms(user.getPhonenumber(),contents);
                            } catch (IOException e) {
                                logger.error("短信发送失败"+e.getMessage());
                            }
                        });
                    }*/
                    tProjectInvestigateService.insertTProjectInvestigate(tProjectInvestigate);

                    FlowBaseInfo flowBaseInfo = new FlowBaseInfo();
                    flowBaseInfo.setCreateBy(userId);
                    flowBaseInfo.setId(UUIDGenerator.uuid());
                    flowBaseInfo.setFormProperties(flowInstanceService.getFormProperties(pInst));
                    flowBaseInfo.setProcDefId(pDefId);
                    flowBaseInfo.setProcInsId(pInst.getId());
                    flowBaseInfo.setTaskName("申请人");
                    flowBaseInfo.setFlag(true);
                    flowBaseInfo.setComment(tProjectInvestigate.isFlag() ? "[提交]" : "[暂存]");
                    flowBaseInfo.setStatus(FlowStatusEnum.STARTED.getName());
                    flowBaseInfo.setFlag(tProjectInvestigate.isFlag());
                    activitiBaseInfoService.addActivitiBaseInfo(flowBaseInfo);

                    TProjectPool tProjectPool=new TProjectPool();
                    tProjectPool.setId(tProjectInvestigate.getProjectPoolId());
                    tProjectPool.setProjectStage("4");//项目阶段-尽职背调
                    tProjectPool.setProjectState("f");//项目状态-尽职背调
                    tProjectPool.setProjectStatus("0");//项目机会状态-正常
                    tProjectPoolService.updateTProjectPool(tProjectPool);
                    if(flowBaseInfo.isFlag()){
                        getAssignee(tProjectInvestigate,flowBaseInfo);
                    }
                    if (Objects.equals(active, "druid")) {
                        //todo 短信
                        sendMessage(flowBaseInfo,"");
                    }
                    //更新代办任务数量
                    sysFormService.updateToDoNumber();
                    return AjaxResult.success();
                }
                return AjaxResult.error();
            }
            return AjaxResult.error();
        } catch (Exception e) {
            /*res.put("status",false);
            res.put("msg", "流程定义id为空, 无法开启流程！");*/
            e.printStackTrace();
            return AjaxResult.error("msg", "流程定义id为空, 无法开启流程！");

        }


    }
    @Override
    public AjaxResult complete(TProjectInvestigate tProjectInvestigate, TProjectInvestigatePerson tProjectInvestigatePerson, FlowBaseInfo flow,HttpServletRequest request) throws Exception {
        //Task task=taskService.createTaskQuery().processInstanceId(tProjectApproval.getProcInstId()).singleResult();
        Task task = taskService.createTaskQuery().taskId(flow.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            return AjaxResult.error("任务不存在");
        }
        //当前你登录人
        SysUser userInfo=SecurityUtils.getLoginUser().getUser();
        Map<String, Object> rs = new HashMap<String, Object>();
        rs.put("status",true);
        Map<String, Object> formProperties = new HashMap<>();
        formProperties.put("auditPass", tProjectInvestigate.isFlag());
        //尽职背调上传人
        /*if("modifyApply".equals(task.getTaskDefinitionKey())) {
            //尽职背调上传人
            List<String> userIds = Arrays.asList(tProjectInvestigate.getInvestigatePersonId().split(","));
            formProperties.put("uploadList", userIds);
        }*/
        if(StringUtils.isNotBlank(tProjectInvestigate.getIsTerminate())) {//不为空代表结束流程
            formProperties.put("whetherToEnd", true);
        }else{
            formProperties.put("whetherToEnd", false);
        }
        Map<String, Object> fpMap = flowService.getFormProperties(task.getProcessDefinitionId(), task.getId());
        try {
            rs = flowService.taskComplete( task.getId(), tProjectInvestigate.isFlag(), formProperties, userInfo.getUserId().toString());
        } catch (Exception e) {
            e.printStackTrace();
            rs.put("status", false);
            rs.put("msg", "流程审批失败");
        }
        boolean status = (boolean) rs.get("status");
        // 审核成功, 则记录审核信息
        if (status) {
            TProjectPool tProjectPool=new TProjectPool();
            tProjectPool.setId(tProjectInvestigate.getProjectPoolId());
            //上传尽职背调报告
            if ("upload".equals(task.getTaskDefinitionKey())) {
                if(StringUtils.isNull(tProjectInvestigatePerson.getId())){
                    tProjectInvestigatePerson.setId(IdUtils.fastSimpleUUID());
                }
                tProjectInvestigatePerson.setInvestigatePerson(userInfo.getNickName());
                tProjectInvestigatePerson.setInvestigatePersonId(userInfo.getUserId().toString());
                tProjectInvestigatePerson.setDeptId(userInfo.getDeptId());
                // todo 保存附件信息
                tUnifyFileService.insertTUnifyFileList(tProjectInvestigatePerson.getListFile(),
                        tProjectInvestigatePerson.getProjectPoolId(),
                        tProjectInvestigatePerson.getId(),//尽调ID
                        String.valueOf(FileType.INVESTIGATE.ordinal()),//文件类型:尽调
                        userInfo.getNickName());

                // todo 增加项目创建记录
                tProjectCirculationService.insertTProjectCirculation(tProjectInvestigatePerson.getProjectPoolId(),"上传尽调报告", userInfo.getNickName());

                tProjectInvestigatePersonService.insertTProjectInvestigatePerson(tProjectInvestigatePerson);
            }
            if("approve".equals(task.getTaskDefinitionKey())){//背调审批节点
                //查询当前人员所在部门
                if(userInfo.getDept().getDeptName().contains("财务")) {
                    // todo 保存财务评估报告
                    tUnifyFileService.insertTUnifyFileLists(tProjectInvestigate.getListFile(),
                            tProjectInvestigate.getProjectPoolId(),
                            tProjectInvestigate.getId(),//附件业务Id
                            String.valueOf(FileType.FINANCE.ordinal()),//文件类型:财务评估报告
                            userInfo.getNickName(),"o","4");
                    // todo 增加文件创建记录
                    //tProjectCirculationService.insertTProjectCirculation(tProjectInformation.getProjectPoolId(),tProjectInformation.getFileName()+"(财务评估报告)",userInfo.getNickName());
                }else if(userInfo.getDept().getDeptName().contains("法务")) {
                    // todo 保存法务评估报告
                    tUnifyFileService.insertTUnifyFileLists(tProjectInvestigate.getListFile(),
                            tProjectInvestigate.getProjectPoolId(),
                            tProjectInvestigate.getId(),//附件业务Id
                            String.valueOf(FileType.LEGAL.ordinal()),//文件类型:法务评估报告
                            userInfo.getNickName(),"p","4");
                    // todo 增加文件创建记录
                    //tProjectCirculationService.insertTProjectCirculation(tProjectInformation.getProjectPoolId(),tProjectInformation.getFileName()+"(法务评估报告)",userInfo.getNickName());
                }else{
                    // todo 保存其他附件
                    tUnifyFileService.insertTUnifyFileLists(tProjectInvestigate.getListFile(),
                            tProjectInvestigate.getProjectPoolId(),
                            tProjectInvestigate.getId(),//附件业务Id
                            String.valueOf(FileType.OTHER.ordinal()),//文件类型:其他附件
                            userInfo.getNickName(),"k","4");
                    // todo 增加文件创建记录
                    //tProjectCirculationService.insertTProjectCirculation(tProjectInformation.getProjectPoolId(),tProjectInformation.getFileName()+"(立项其他附件)",userInfo.getNickName());
                }
            }
            if("president".equals(task.getTaskDefinitionKey())){
//                tProjectPool.setProjectStage("5");//项目阶段-项目投决
//                tProjectPool.setProjectState("i");//项目状态-项目投决通过
            }
            //FlowBaseInfo flow = new FlowBaseInfo();
            if(flow==null){
                flow = new FlowBaseInfo();
            }
            flow.setId(UUIDGenerator.uuid());
            flow.setFormProperties(flowService.getFormProperties(fpMap, request.getParameterMap()));
            flow.setStatus(FlowStatusEnum.RUNNING.getName());
            flow.setProcDefId(task.getProcessDefinitionId());
            flow.setProcInsId(task.getProcessInstanceId());
            flow.setTaskDefKey(task.getTaskDefinitionKey());
            String isOk = tProjectInvestigate.isFlag() ? "[同意]" : "[驳回]";
            if ("modifyApply".equals(task.getTaskDefinitionKey())) {
                tProjectInvestigate.setStatus(tProjectInvestigate.isFlag() ? 1 : 4);
                isOk = tProjectInvestigate.isFlag() ? "[提交]" : "[关闭]";
            } else {
                tProjectInvestigate.setStatus(tProjectInvestigate.isFlag() ? 2 : 0);
                if("president".equals(task.getTaskDefinitionKey())){//总裁室
                    if(!tProjectInvestigate.isFlag()&&StringUtils.isNotBlank(tProjectInvestigate.getIsTerminate())){//如果不为空代表可能是驳回（终止）或者观望
                        isOk= "[关闭]";
                    }
                }
            }
            if (null != flow.getComment()) {
                flow.setComment(isOk + flow.getComment());
            } else {
                flow.setComment(isOk);
            }
            flow.setTaskName(task.getName());
            flow.setCreateBy(SecurityUtils.getLoginUser().getUserId().toString());
            flow.setFlag(tProjectInvestigate.isFlag());
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).active().singleResult();
            String result="";
            // 表示流程已经审批结束了
            if (processInstance == null) {
                flow.setStatus(FlowStatusEnum.ENDED.getName());
                if (!"modifyApply".equals(task.getTaskDefinitionKey())) {
                    if(tProjectInvestigate.isFlag()) {//审批通过
                        tProjectInvestigate.setStatus(3);
                        tProjectPool.setProjectStage("5");//项目阶段-项目投决
                        tProjectPool.setProjectState("h");//项目状态-准备项目投决材料
                        tProjectPool.setUpdateBy(userInfo.getNickName());
                        // todo 增加项目创建记录
                        tProjectCirculationService.insertTProjectCirculation(tProjectPool.getId(), "尽职背调完成", userInfo.getNickName());
                    }else{//终止和观望
                        if(StringUtils.isNotBlank(tProjectInvestigate.getIsTerminate())) {
                            tProjectInvestigate.setStatus(4);//流程状态为关闭
                            if ("1".equals(tProjectInvestigate.getIsTerminate())) {
                                result="【终止】";
                                tProjectPool.setProjectStatus("1");//终止
                            } else {
                                result="【观望】";
                                tProjectPool.setProjectStatus("2");//观望
                            }
                            tProjectPool.setProjectStage("4");//项目阶段-尽职背调
                            tProjectPool.setProjectState("f");//项目状态-尽职背调
                            tProjectPool.setInvestigateFlag("0");
                            tProjectPool.setUpdateBy(userInfo.getNickName());
                        }
                    }
                }else{
                    tProjectPool.setProjectStage("4");//项目阶段-尽职背调
                    tProjectPool.setProjectState("f");//项目状态-尽职背调
                    tProjectPool.setInvestigateFlag("0");
                    tProjectPool.setUpdateBy(userInfo.getNickName());
                }
                tProjectPoolService.updateTProjectPool(tProjectPool);
            }

            tProjectInvestigateService.updateTProjectInvestigate(tProjectInvestigate);
            activitiBaseInfoService.addActivitiBaseInfo(flow);
            if(flow.isFlag()){
                getAssignee(tProjectInvestigate,flow);
            }
            if (Objects.equals(active, "druid")) {
                // todo 短信
                sendMessage(flow,result);
            }
        }
        return AjaxResult.success();
    }
    public TProjectMeeting selectTProjectMeetingByProcInstId(String pInstId){
        TProjectInvestigate tProjectInvestigate=this.selectTProjectInvestigateByProcInstId(pInstId);
        TProjectMeeting tProjectMeeting=null;
        if(tProjectInvestigate!=null){
            //tProjectMeeting=tProjectMeetingService.selectTProjectMeetingByProjectPoolId(tProjectInvestigate.getProjectPoolId());
        }
        return tProjectMeeting;
    }
    /**
     * 根据流程Id查询汇总分数和平均分数
     * @param pInstId
     * @return
     */
    @Override
    public Map<String, String> selectSumScore(String pInstId) {
        TProjectInvestigate tProjectInvestigate=this.selectTProjectInvestigateByProcInstId(pInstId);
        Map<String, String> sumScore=new HashMap<>();
        if(tProjectInvestigate!=null){
            //TProjectMeeting tProjectMeeting=tProjectMeetingService.selectTProjectMeetingByProjectPoolId(tProjectInvestigate.getProjectPoolId());
            //sumScore=tProjectScoringMapper.selectMeetingId(tProjectMeeting.getId());
        }
        return sumScore;
    }
    // todo 短信
    public void sendMessage(FlowBaseInfo flowBaseInfo,String result) {
        boolean flag = flowBaseInfo.isFlag();
        String procInsId = flowBaseInfo.getProcInsId();
        // 待办任务
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(procInsId).list();
        // 对应业务单据
        ProjectInvestigateVo projectInvestigate =investigateMapper.selectProjectInvestigateByProcInstId(procInsId);
        if (projectInvestigate == null) {
            return;
        }
        // 申请人
        SysUser applyUserInfo = sysUserService.selectUserById(Long.valueOf(projectInvestigate.getCreateBy()));
        // 当前登录人
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();

        if(tasks.size()>0) {
            for (int i = 0; i < tasks.size(); i++) {
                Task task = tasks.get(i);
                if (task != null) {
                    if (Objects.equals(applyUserInfo.getUserId(), loginUser.getUserId()) && !flag) {
                        // 如果是申请人暂存或者关闭或者自己驳回，不用给自己发审批短信
                        continue;
                    } else {
                        // 申请人提交，给下一个审批人发短信
                        // 审批人同意，给下一个审批人发短信
                        if (flag) { //给审批人发送短信
                            if ("approve".equals(flowBaseInfo.getTaskDefKey())&&("approve".equals(task.getTaskDefinitionKey()))){
                                continue;
                            }
                            String assignee = task.getAssignee();
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(assignee)) { // 给审批人发送短信
                                SysUser auditUser = sysUserService.selectUserById(Long.valueOf(assignee));
                                String auditContents = auditUser.getNickName() + ",您好。投资系统中" + projectInvestigate.getProjectName() + "的项目背调流程待处理，请查看！";
                                if (auditUser != null && StringUtils.isNotBlank(auditUser.getPhonenumber())) {
                                    try{
                                        SmsSenderUtils.sendSms(auditUser.getPhonenumber(), auditContents);
                                    } catch (IOException e) {
                                        logger.error("短信发送失败"+e.getMessage());
                                    }
                                }
                            }
                        } else { // 审批人驳回，给申请人发短信
                            String rejectContents = applyUserInfo.getNickName()+"，您好。你在投资系统中提交" + projectInvestigate.getProjectName() + "的项目背调申请已审核，结果为【驳回】，请查看！";
                            if (applyUserInfo != null && StringUtils.isNotBlank(applyUserInfo.getPhonenumber())) {
                                try{
                                    SmsSenderUtils.sendSms(applyUserInfo.getPhonenumber(), rejectContents);
                                } catch (IOException e) {
                                    logger.error("短信发送失败"+e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }else{
            String completeContents ="";
            if(flag) {
                // 审批完成，给申请人发短信
                //XXX，您好。你在投资系统中提交“XXX”的项目背调申请已审核，结果为【通过】/【驳回】/【观望】！
                completeContents = applyUserInfo.getNickName()+"，您好。你在投资系统中提交" + projectInvestigate.getProjectName() + "的项目背调申请已审核，结果为【同意】，请查看！";
                if (applyUserInfo != null && StringUtils.isNotBlank(applyUserInfo.getPhonenumber())) {
                    try{
                        SmsSenderUtils.sendSms(applyUserInfo.getPhonenumber(), completeContents);
                    } catch (IOException e) {
                        logger.error("短信发送失败"+e.getMessage());
                    }
                }

            }else{
                if(StringUtils.isNotEmpty(result)){//代表是终止或者观望
                    completeContents = applyUserInfo.getNickName()+"，您好。你在投资系统中提交" + projectInvestigate.getProjectName() + "的项目背调申请已审核，结果为"+result+"，请查看！";
                    if (applyUserInfo != null && StringUtils.isNotBlank(applyUserInfo.getPhonenumber())) {
                        try{
                            SmsSenderUtils.sendSms(applyUserInfo.getPhonenumber(), completeContents);
                        } catch (IOException e) {
                            logger.error("短信发送失败"+e.getMessage());
                        }
                    }
                }
            }

        }
    }
    /**
     * 跳节点
     * @param projectInvestigate
     * @param flow
     * @throws Exception
     */
    public void getAssignee(TProjectInvestigate projectInvestigate, FlowBaseInfo flow) throws Exception {
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();//当前登陆人
        if (sysUser == null) {
            sysUser=sysUserService.selectUserById(Long.parseLong(projectInvestigate.getCreateBy()));
        }
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(flow.getProcInsId()).list();
        Long userId=sysUser.getUserId();
        for(int i = 0; i < tasks.size(); i++) {
            Task task = tasks.get(i);
            if (task == null || StringUtils.isBlank(task.getAssignee())) {
                return;
            }
            Long assignee = Long.parseLong(task.getAssignee());
            if ("deptLeader".equals(task.getTaskDefinitionKey()) && (userId.equals(assignee) || projectInvestigate.getCreateBy().equals(assignee))) {
                JumpNode(projectInvestigate, flow);
            }
        }
    }
    public Map<String, Object> JumpNode(TProjectInvestigate projectInvestigate, FlowBaseInfo flow) throws Exception{
        List<Task> list = taskService.createTaskQuery().processInstanceId(flow.getProcInsId()).list();
        String taskId=null;
        Map<String, Object> rs = new HashMap<String, Object>();
        rs.put("status",true);
        if (list.size()>0) {
            taskId = list.get(0).getId();
            flow.setTaskId(taskId);
            boolean flag = flow.isFlag();
            //当前流程节点Id信息
//            ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(flow.getProcInsId()).singleResult();
//            String activitiId = execution.getActivityId();
            Map<String, Object> formProperties = new HashMap<>();
            formProperties.put("auditPass", flow.isFlag());
            //部门负责人
            String leader=sysDeptMapper.selectDeptLeader("投资部");
            SysUser sysUser=sysUserService.selectUserByUserName(leader);
            formProperties.put("MANAGER",sysUser.getUserId());
            if(StringUtils.isNotBlank(projectInvestigate.getIsTerminate())) {//不为空代表结束流程
                formProperties.put("whetherToEnd", true);
            }else{
                formProperties.put("whetherToEnd", false);
            }
            //当前登陆人
            Long userId=SecurityUtils.getUserId();
            try {
                //表单审核
                rs = flowService.taskComplete(taskId, flag, formProperties, userId.toString());
            } catch (Exception e) {
                e.printStackTrace();
                rs.put("status", false);
                rs.put("msg", "流程审批失败");
            }
            if (flow.isFlag()){
                getAssignee(projectInvestigate,flow);
            }

        }
        return rs;
    }

}
