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.ProjectApprovalVo;
import com.ruoyi.invest.mapper.ApprovalMapper;
import com.ruoyi.invest.mapper.TProjectPoolMapper;
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 ApprovalServiceImpl extends FlowServiceFactory implements IApprovalService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private ApprovalMapper approvalMapper;
    @Autowired
    private ITProjectApprovalService tProjectApprovalService;
    @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 ITProjectMeetingService tProjectMeetingService;
    @Autowired
    private ITProjectScoringService tProjectScoringService;
    @Autowired
    private TProjectScoringMapper tProjectScoringMapper;
    @Autowired
    private ISysFormService sysFormService;
    @Override
    public List<ProjectApprovalVo> selectAllApprovalList(TProjectApproval tProjectApproval){
        return approvalMapper.selectAllApprovalList(tProjectApproval);
    }
    @Override
    public List<ProjectApprovalVo> getMyTaskList(String userId, TProjectApproval tProjectApproval){
        return approvalMapper.getMyTaskList(userId, tProjectApproval);
    }
    @Override
    public List<ProjectApprovalVo> getMyDoneTaskList(String userId, TProjectApproval tProjectApproval){
        return approvalMapper.getMyDoneTaskList(userId, tProjectApproval);
    }
    @Override
    public List<ProjectApprovalVo> getMyList(String userId,TProjectApproval tProjectApproval){
        return approvalMapper.getMyList(userId, tProjectApproval);
    }


    /**
     * 查询项目池
     * 
     * @param pInstId 流程实例Id
     * @return 项目池
     */
    @Override
    public TProjectApproval selectTProjectApprovalByProcInstId(String pInstId)
    {
        return approvalMapper.selectTProjectApprovalByProcInstId(pInstId);
    }

    @Override
    public AjaxResult start(TProjectApproval tProjectApproval) {

        // 根据key值获取最新的流程部署id
        String pDefId = null;
        ProcessInstance pInst = null;
        try {
            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionKey("dgt-project-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",tProjectApproval.isFlag()?true:false);
                //暂存
                formProperties.put(ProcessConstants.PROCESS_INITIATOR, sysUser.getUserId());
                //投资部负责人
                String leader=sysDeptMapper.selectDeptLeader("投资部");
                formProperties.put("MANAGER",sysUserService.selectUserByUserName(leader).getUserId());
                pInst = runtimeService.startProcessInstanceById(pDefId, formProperties);
               // ProcessInstance p = runtimeService.startProcessInstanceById(procDefId, variables);
                if(pInst!=null){
                    String nickName= SecurityUtils.getLoginUser().getUser().getNickName();
                    String userId=SecurityUtils.getLoginUser().getUserId().toString();
                    //保存信息
                    tProjectApproval.setId(IdUtils.fastSimpleUUID());
                    tProjectApproval.setProcInstId(pInst.getProcessInstanceId());
                    tProjectApproval.setCreateBy(userId);
                    if(tProjectApproval.isFlag()){
                        tProjectApproval.setStatus(1);//提交
                    }else{
                        tProjectApproval.setStatus(0);//暂存
                    }
                    // todo 保存立项资料
                    tUnifyFileService.insertTUnifyFileLists(tProjectApproval.getListFile(),
                            tProjectApproval.getProjectPoolId(),
                            tProjectApproval.getId(),
                            String.valueOf(FileType.APPROVAL.ordinal()),
                            nickName, "l","3");
                    // todo 保存其他附件信息
                    tUnifyFileService.insertTUnifyFileLists(tProjectApproval.getOtherFile(),
                            tProjectApproval.getProjectPoolId(),
                            tProjectApproval.getId(),
                            String.valueOf(FileType.OTHER.ordinal()),
                            nickName,"k","3");
                    // todo 更改立项状态
                    tProjectPoolService.updateTProjectPoolByApprovalFlag(tProjectApproval.getProjectPoolId(),"1");

                    // todo 短信提醒
                    /*if(StringUtils.isNotEmpty(tProjectApproval.getParticipantsId())){
                        StringUtils.str2List(tProjectApproval.getParticipantsId(),",",true,true).stream().forEach(str -> {
                            SysUser user = sysUserService.selectUserById(Long.valueOf(str));
                            String contents = "您好，"+user.getNickName()+"，" + tProjectApproval.getProjectName() + "已发起立项申请。";
                            try {
                                SmsSenderUtils.sendSms(user.getPhonenumber(),contents);
                            } catch (IOException e) {
                                logger.error("短信发送失败"+e.getMessage());
                            }
                        });
                    }*/

                    // todo 增加项目创建记录
                    tProjectCirculationService.insertTProjectCirculation(tProjectApproval.getProjectPoolId(),"立项申请",nickName);

                    tProjectApprovalService.insertTProjectApproval(tProjectApproval);

                    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(tProjectApproval.isFlag() ? "[提交]" : "[暂存]");
                    flowBaseInfo.setStatus(FlowStatusEnum.STARTED.getName());
                    flowBaseInfo.setFlag(tProjectApproval.isFlag());

                    activitiBaseInfoService.addActivitiBaseInfo(flowBaseInfo);
                    TProjectPool tProjectPool=new TProjectPool();
                    tProjectPool.setId(tProjectApproval.getProjectPoolId());
                    tProjectPool.setProjectStage("3");//项目阶段-项目立项
                    tProjectPool.setProjectState("d");//项目状态-项目立项
                    tProjectPool.setProjectStatus("0");//项目机会状态-正常
                    tProjectPoolService.updateTProjectPool(tProjectPool);
                    if(flowBaseInfo.isFlag()){
                        getAssignee(tProjectApproval,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(TProjectApproval tProjectApproval, TProjectMeeting tProjectMeeting,TProjectScoring tProjectScoring, 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", tProjectApproval.isFlag());
        //会议投决人
        if("meeting".equals(task.getTaskDefinitionKey())) {
            //立项审批人
            List<String> userIds = Arrays.asList(tProjectApproval.getParticipantsId().split(","));
            //List<String> userIds = Arrays.asList(tProjectMeeting.getParticipantsId().split(","));//会议人
            formProperties.put("decisionList", userIds);
        }
        if(StringUtils.isNotBlank(tProjectApproval.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(), tProjectApproval.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(tProjectApproval.getProjectPoolId());
            if ("modifyApply".equals(task.getTaskDefinitionKey())) {
                // todo 立项申请报告
                tUnifyFileService.insertTUnifyFileLists(tProjectApproval.getListFile(),
                        tProjectApproval.getProjectPoolId(),
                        tProjectApproval.getId(),
                        String.valueOf(FileType.APPROVAL.ordinal()),
                        userInfo.getNickName(), "l", "3");
                // todo 保存其他附件信息
                tUnifyFileService.insertTUnifyFileLists(tProjectApproval.getOtherFile(),
                        tProjectApproval.getProjectPoolId(),
                        tProjectApproval.getId(),
                        String.valueOf(FileType.OTHER.ordinal()),
                        userInfo.getNickName(), "k", "3");
            }
            //发起会议
            if ("meeting".equals(task.getTaskDefinitionKey())) {
                if(tProjectMeeting!=null&&StringUtils.isNotBlank(tProjectMeeting.getId())){
                    // todo 保存附件信息
                    tUnifyFileService.insertTUnifyFileList(tProjectMeeting.getListFile(),
                            tProjectMeeting.getProjectPoolId(),
                            tProjectMeeting.getId(),//会议ID
                            String.valueOf(FileType.MEETING.ordinal()),//文件类型:会议
                            userInfo.getNickName());
                    tProjectMeetingService.updateTProjectMeeting(tProjectMeeting);
                }else {
                    if ("0".equals(tProjectApproval.getNeedMeeting())) {

                    }
                    tProjectMeeting.setId(IdUtils.fastSimpleUUID());
                    tProjectMeeting.setCreateBy(userInfo.getNickName());
                    tProjectMeeting.setProjectPoolId(tProjectApproval.getProjectPoolId());
                    if (tProjectMeeting.getMeetingType().equals("LX") || tProjectMeeting.getMeetingType().equals("TJ")) {
                        int number = tProjectMeetingService.selectTProjectMeetingCode(DateUtils.lastTwoDigits() + "-");
                        tProjectMeeting.setMeetingCode(tProjectMeeting.getProjectGroup() + "-" + DateUtils.lastTwoDigits() + "-" + tProjectMeeting.getMeetingType() + "-" + String.format("%03d", number + 1));
                    } else {
                        int number = tProjectMeetingService.selectTProjectMeetingCode(DateUtils.dateTimeNow("YYYY"));
                        tProjectMeeting.setMeetingCode(DateUtils.dateNow() + String.format("%03d", number + 1));
                    }
                    // todo 保存附件信息
                    tUnifyFileService.insertTUnifyFileList(tProjectMeeting.getListFile(),
                            tProjectMeeting.getProjectPoolId(),
                            tProjectMeeting.getId(),//会议ID
                            String.valueOf(FileType.MEETING.ordinal()),//文件类型:会议
                            userInfo.getNickName());
                    if(StringUtils.isNotBlank(tProjectMeeting.getMeetingTheme())){
                        // todo 增加会议创建记录
                        tProjectCirculationService.insertTProjectCirculation(tProjectMeeting.getProjectPoolId(), tProjectMeeting.getMeetingTheme() + "(会议)", userInfo.getNickName());
                    }
                    // todo 发送短信-参与人-发起人
                    if (tProjectMeeting.getMeetingType().equals("LX") || tProjectMeeting.getMeetingType().equals("TJ")) {
                        // todo 参与人
                    /*if(StringUtils.isNotEmpty(tProjectMeeting.getParticipantsId())){
                        StringUtils.str2List(tProjectMeeting.getParticipantsId(),",",true,true).stream().forEach(str -> {
                            SysUser user = sysUserService.selectUserById(Long.valueOf(str));
                            String contents = "您好，" + user.getNickName() + "，兹定于 " +
                                    DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getStartTime()) + "至" + DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getEndTime()) +
                                    "在" + tProjectMeeting.getPlace() + "召开" + tProjectMeeting.getMeetingTheme() + "会议,请提前做好准备按时参加。";
                            try {
                                SmsSenderUtils.sendSms(user.getPhonenumber(),contents);
                            } catch (IOException e) {
                                logger.error("短信发送失败"+e.getMessage());
                            }
                        });
                    }*/

                        // todo 发起人
                    /*if(StringUtils.isNotEmpty(tProjectMeeting.getPromoterId())){
                        SysUser user = sysUserService.selectUserById(Long.valueOf(tProjectMeeting.getPromoterId()));
                        String contents = "您好，" + user.getNickName() + "，兹定于 " +
                                DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getStartTime()) + "至" + DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getEndTime()) +
                                "在" + tProjectMeeting.getPlace() + "召开" + tProjectMeeting.getMeetingTheme() + "会议,请提前做好准备按时参加。";
                        try {
                            SmsSenderUtils.sendSms(user.getPhonenumber(),contents);
                        } catch (IOException e) {
                            logger.error("短信发送失败"+e.getMessage());
                        }
                    }*/
                    }

                    tProjectMeetingService.insertTProjectMeeting(tProjectMeeting);
                }
            }
            //上传打分表
            if("decision".equals(task.getTaskDefinitionKey())){
                tProjectScoring.setCreateBy(userInfo.getNickName());
                tProjectScoring.setProjectPoolId(tProjectApproval.getProjectPoolId());
                // todo 增加项目创建记录
                tProjectCirculationService.insertTProjectCirculation(tProjectScoring.getProjectPoolId(),"上传打分表", userInfo.getNickName());

                tProjectScoringService.insertTProjectScoring(tProjectScoring);
            }
            if("industryResearch".equals(task.getTaskDefinitionKey())){

                // todo 保存项目行研报告
                tUnifyFileService.insertTUnifyFileLists(tProjectApproval.getListFile(),
                        tProjectApproval.getProjectPoolId(),
                        tProjectApproval.getId(),//附件业务Id
                        String.valueOf(FileType.INDUSTRY.ordinal()),//文件类型:项目行研报告
                        userInfo.getNickName(),"m","3");
                // todo 增加文件创建记录
                //tProjectCirculationService.insertTProjectCirculation(tProjectApproval.getProjectPoolId(),tProjectApproval.getListFile().get(0).getNewUploadName()+"(项目行研报告)",userInfo.getNickName());
            }
            if("technicalResearch".equals(task.getTaskDefinitionKey())){
                // todo 保存项目技术报告
                tUnifyFileService.insertTUnifyFileLists(tProjectApproval.getListFile(),
                        tProjectApproval.getProjectPoolId(),
                        tProjectApproval.getId(),//附件业务Id
                        String.valueOf(FileType.TECHNICAL.ordinal()),//文件类型:项目技术报告
                        userInfo.getNickName(),"n","3");
                // todo 增加文件创建记录
                //tProjectCirculationService.insertTProjectCirculation(tProjectApproval.getProjectPoolId(),tProjectApproval.getListFile().get(0).getNewUploadName()+"(项目技术报告)",userInfo.getNickName());

            }
            if("president".equals(task.getTaskDefinitionKey())){
                tProjectPool.setProjectStage("3");//项目阶段-项目立项
                tProjectPool.setProjectState("e");//项目状态-立项通过
            }
            //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 = tProjectApproval.isFlag() ? "[同意]" : "[驳回]";
            if ("modifyApply".equals(task.getTaskDefinitionKey())) {
                tProjectApproval.setStatus(tProjectApproval.isFlag() ? 1 : 4);
                isOk = tProjectApproval.isFlag() ? "[提交]" : "[关闭]";
            } else {
                tProjectApproval.setStatus(tProjectApproval.isFlag() ? 2 : 0);
                if("president".equals(task.getTaskDefinitionKey())){//总裁室
                    if(!tProjectApproval.isFlag()&&StringUtils.isNotBlank(tProjectApproval.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(tProjectApproval.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(tProjectApproval.isFlag()) {//审批通过
                        tProjectApproval.setStatus(3);
                        tProjectPool.setProjectStage("4");//项目阶段-尽调背调
                        tProjectPool.setProjectState("f");//项目状态-尽调背调
                        tProjectPool.setUpdateBy(userInfo.getNickName());
                        tProjectPool.setProjectDate(new Date());//立项通过日期
                        // todo 增加项目创建记录
                        tProjectCirculationService.insertTProjectCirculation(tProjectPool.getId(), "项目立项完成", userInfo.getNickName());
                    }else{//终止和观望
                        if(StringUtils.isNotBlank(tProjectApproval.getIsTerminate())) {
                            tProjectApproval.setStatus(4);//流程状态为关闭
                            if ("1".equals(tProjectApproval.getIsTerminate())) {
                                result="【终止】";
                                tProjectPool.setProjectStatus("1");//终止
                            } else {
                                result="【观望】";
                                tProjectPool.setProjectStatus("2");//观望
                            }
                            tProjectPool.setProjectStage("3");//项目阶段-项目立项
                            tProjectPool.setProjectState("c");//项目状态-准备立项材料
                            tProjectPool.setApprovalFlag("0");
                            tProjectPool.setUpdateBy(userInfo.getNickName());
                        }
                    }
                }else{//暂存的关闭
                    tProjectPool.setProjectStage("3");//项目阶段-项目立项
                    tProjectPool.setProjectState("c");//项目状态-准备立项材料
                    tProjectPool.setApprovalFlag("0");
                    tProjectPool.setUpdateBy(userInfo.getNickName());
                }
                tProjectPoolService.updateTProjectPool(tProjectPool);
            }
            tProjectApprovalService.updateTProjectApproval(tProjectApproval);
            activitiBaseInfoService.addActivitiBaseInfo(flow);
            if(flow.isFlag()){
                getAssignee(tProjectApproval,flow);
            }
            if (Objects.equals(active, "druid")) {
                // todo 短信提醒
                sendMessage(flow,result);
            }
        }
        return AjaxResult.success();
    }
    public TProjectMeeting selectTProjectMeetingByProcInstId(String pInstId){
        TProjectApproval tProjectApproval=this.selectTProjectApprovalByProcInstId(pInstId);
        TProjectMeeting tProjectMeeting=null;
        if(tProjectApproval!=null){
            tProjectMeeting=tProjectMeetingService.selectTProjectMeetingByProjectPoolId(tProjectApproval.getProjectPoolId());
        }
        return tProjectMeeting;
    }
    /**
     * 根据流程Id查询汇总分数和平均分数
     * @param pInstId
     * @return
     */
    @Override
    public Map<String, String> selectSumScore(String pInstId) {
        TProjectApproval tProjectApproval=this.selectTProjectApprovalByProcInstId(pInstId);
        Map<String, String> sumScore=new HashMap<>();
        if(tProjectApproval!=null){
            TProjectMeeting tProjectMeeting=tProjectMeetingService.selectTProjectMeetingByProjectPoolId(tProjectApproval.getProjectPoolId());
            if(tProjectMeeting!=null) {
                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();
        // 对应业务单据
        ProjectApprovalVo projectApproval = approvalMapper.selectProjectApprovalByProcInstId(procInsId);
        if (projectApproval == null) {
            return;
        }
        // 申请人
        SysUser applyUserInfo = sysUserService.selectUserById(Long.valueOf(projectApproval.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) {
                        // 如果是申请人暂存或者关闭或者自己驳回，不用给自己发审批短信
                    } else {
                        // 申请人提交，给下一个审批人发短信
                        // 审批人同意，给下一个审批人发短信
                        if (flag) { //给审批人发送短信
                            if (tasks.size()<2
                                    &&("industryResearch".equals(task.getTaskDefinitionKey())||"technicalResearch".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() + ",您好。投资系统中" + projectApproval.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()+"，您好。你在投资系统中提交" + projectApproval.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()+"，您好。你在投资系统中提交" + projectApproval.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()+"，您好。你在投资系统中提交" + projectApproval.getProjectName() + "的项目立项申请已审核，结果为"+result+"，请查看！";
                    if (applyUserInfo != null && StringUtils.isNotBlank(applyUserInfo.getPhonenumber())) {
                        try{
                            SmsSenderUtils.sendSms(applyUserInfo.getPhonenumber(), completeContents);
                        } catch (IOException e) {
                            logger.error("短信发送失败"+e.getMessage());
                        }
                    }
                }
            }

        }
    }
    /**
     * 跳节点
     * @param projectApproval
     * @param flow
     * @throws Exception
     */
    public void getAssignee(TProjectApproval projectApproval, FlowBaseInfo flow) throws Exception {
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();//当前登陆人
        if (sysUser == null) {
            sysUser=sysUserService.selectUserById(Long.parseLong(projectApproval.getCreateBy()));
        }
        //Task task = taskService.createTaskQuery().processInstanceId(flow.getProcInsId()).singleResult();
        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) || projectApproval.getCreateBy().equals(assignee))) {
                JumpNode(projectApproval, flow);
            }
        }
    }
    public Map<String, Object> JumpNode(TProjectApproval projectApproval, 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("投资部");
            formProperties.put("MANAGER",sysUserService.selectUserByUserName(leader).getUserId());
            if(StringUtils.isNotBlank(projectApproval.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(projectApproval,flow);
            }

        }
        return rs;
    }
}
