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.ProjectDecisionVo;
import com.ruoyi.invest.mapper.DecisionMapper;
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 DecisionServiceImpl extends FlowServiceFactory implements IDecisionService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private DecisionMapper decisionMapper;
    @Autowired
    private ITProjectDecisionService tProjectDecisionService;
    @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<ProjectDecisionVo> selectAllDecisionList(TProjectDecision tProjectDecision){
        return decisionMapper.selectAllDecisionList(tProjectDecision);
    }
    @Override
    public List<ProjectDecisionVo> getMyTaskList(String userId, TProjectDecision tProjectDecision){
        return decisionMapper.getMyTaskList(userId, tProjectDecision);
    }
    @Override
    public List<ProjectDecisionVo> getMyDoneTaskList(String userId, TProjectDecision tProjectDecision){
        return decisionMapper.getMyDoneTaskList(userId, tProjectDecision);
    }
    @Override
    public List<ProjectDecisionVo> getMyList(String userId,TProjectDecision tProjectDecision){
        return decisionMapper.getMyList(userId, tProjectDecision);
    }


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

    @Override
    public AjaxResult start(TProjectDecision tProjectDecision) {

        // 根据key值获取最新的流程部署id
        String pDefId = null;
        ProcessInstance pInst = null;
        try {
            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionKey("dgt-decision-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",tProjectDecision.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();
                    //保存信息
                    tProjectDecision.setId(IdUtils.fastSimpleUUID());
                    tProjectDecision.setProcInstId(pInst.getProcessInstanceId());
                    tProjectDecision.setCreateBy(userId);
                    if(tProjectDecision.isFlag()){
                        tProjectDecision.setStatus(1);//提交
                    }else{
                        tProjectDecision.setStatus(0);//暂存
                    }
                    // todo 保存投决资料
                    tUnifyFileService.insertTUnifyFileLists(tProjectDecision.getListFile(),
                            tProjectDecision.getProjectPoolId(),
                            tProjectDecision.getId(),
                            String.valueOf(FileType.DECISION.ordinal()),
                            nickName,"q","5");
                    // todo 保存其他附件
                    tUnifyFileService.insertTUnifyFileLists(tProjectDecision.getOtherFile(),
                            tProjectDecision.getProjectPoolId(),
                            tProjectDecision.getId(),
                            String.valueOf(FileType.OTHER.ordinal()),
                            nickName,"k","5");

                    // todo 更改投决状态
                    tProjectPoolService.updateTProjectPoolByDecisionFlag(tProjectDecision.getProjectPoolId(),"1");

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

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

                    tProjectDecisionService.insertTProjectDecision(tProjectDecision);


                    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(tProjectDecision.isFlag() ? "[提交]" : "[暂存]");
                    flowBaseInfo.setStatus(FlowStatusEnum.STARTED.getName());
                    flowBaseInfo.setFlag(tProjectDecision.isFlag());
                    activitiBaseInfoService.addActivitiBaseInfo(flowBaseInfo);
                    TProjectPool tProjectPool=new TProjectPool();
                    tProjectPool.setId(tProjectDecision.getProjectPoolId());
                    tProjectPool.setProjectStage("5");//项目阶段-项目投决
                    tProjectPool.setProjectState("h");//项目状态-准备项目投决材料
                    tProjectPool.setProjectStatus("0");//项目机会状态-正常
                    tProjectPoolService.updateTProjectPool(tProjectPool);
                    if(flowBaseInfo.isFlag()){
                        getAssignee(tProjectDecision,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(TProjectDecision tProjectDecision, 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", tProjectDecision.isFlag());
        //会议投决人
        if("meeting".equals(task.getTaskDefinitionKey())&&tProjectDecision.isFlag()) {
            //立项审批人
            List<String> userIds = Arrays.asList(tProjectDecision.getParticipantsId().split(","));
            //List<String> userIds = Arrays.asList(tProjectMeeting.getParticipantsId().split(","));//会议人
            formProperties.put("decisionList", userIds);
        }
        if(StringUtils.isNotBlank(tProjectDecision.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(), tProjectDecision.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(tProjectDecision.getProjectPoolId());
            if("modifyApply".equals(task.getTaskDefinitionKey())) {
                // todo 保存投决资料
                tUnifyFileService.insertTUnifyFileLists(tProjectDecision.getListFile(),
                        tProjectDecision.getProjectPoolId(),
                        tProjectDecision.getId(),
                        String.valueOf(FileType.DECISION.ordinal()),
                        userInfo.getNickName(), "q", "5");
                // todo 保存其他附件
                tUnifyFileService.insertTUnifyFileLists(tProjectDecision.getOtherFile(),
                        tProjectDecision.getProjectPoolId(),
                        tProjectDecision.getId(),
                        String.valueOf(FileType.OTHER.ordinal()),
                        userInfo.getNickName(), "k", "5");
            }
            //发起会议
            if ("meeting".equals(task.getTaskDefinitionKey())&&tProjectDecision.isFlag()) {
                tProjectMeeting.setId(IdUtils.fastSimpleUUID());
                tProjectMeeting.setCreateBy(userInfo.getNickName());
                tProjectMeeting.setProjectPoolId(tProjectDecision.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(tProjectDecision.getProjectPoolId());
                // todo 增加项目创建记录
                tProjectCirculationService.insertTProjectCirculation(tProjectScoring.getProjectPoolId(),"上传打分表", userInfo.getNickName());

                tProjectScoringService.insertTProjectScoring(tProjectScoring);
            }
            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 = tProjectDecision.isFlag() ? "[同意]" : "[驳回]";
            if ("modifyApply".equals(task.getTaskDefinitionKey())) {
                tProjectDecision.setStatus(tProjectDecision.isFlag() ? 1 : 4);
                isOk = tProjectDecision.isFlag() ? "[提交]" : "[关闭]";
            } else {
                tProjectDecision.setStatus(tProjectDecision.isFlag() ? 2 : 0);
                if("president".equals(task.getTaskDefinitionKey())){//总裁室
                    if(!tProjectDecision.isFlag()&&StringUtils.isNotBlank(tProjectDecision.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(tProjectDecision.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())&&!"president".equals(task.getTaskDefinitionKey())) {
                    tProjectDecision.setStatus(3);
                    tProjectPool.setProjectStage("6");//项目阶段-项目签约
                    tProjectPool.setProjectState("j");//项目状态-签约协议沟通中
                    tProjectPool.setUpdateBy(userInfo.getNickName());
                    tProjectPool.setDecisionDate(new Date());//投决通过日期
                    // todo 增加项目创建记录
                    tProjectCirculationService.insertTProjectCirculation(tProjectPool.getId(),"项目投决完成", userInfo.getNickName());
                }else{
                    tProjectPool.setProjectStage("5");//项目阶段-项目投决
                    tProjectPool.setProjectState("c");//项目状态-
                    tProjectPool.setDecisionFlag("0");
                    tProjectPool.setUpdateBy(userInfo.getNickName());
                    if("president".equals(task.getTaskDefinitionKey())){//终止和观望
                        if(StringUtils.isNotBlank(tProjectDecision.getIsTerminate())) {
                            tProjectDecision.setStatus(4);//流程状态为关闭
                            if ("1".equals(tProjectDecision.getIsTerminate())) {
                                result="【终止】";
                                tProjectPool.setProjectStatus("1");//终止
                            } else {
                                result="【观望】";
                                tProjectPool.setProjectStatus("2");//观望
                            }
                        }
                    }
                }
                tProjectPoolService.updateTProjectPool(tProjectPool);
            }

            tProjectDecisionService.updateTProjectDecision(tProjectDecision);
            activitiBaseInfoService.addActivitiBaseInfo(flow);
            if(flow.isFlag()){
                getAssignee(tProjectDecision,flow);
            }
            if (Objects.equals(active, "druid")) {
                //todo 短信
                sendMessage(flow,result);
            }
        }
        return AjaxResult.success();
    }
    public TProjectMeeting selectTProjectMeetingByProcInstId(String pInstId){
        TProjectDecision tProjectDecision=this.selectTProjectDecisionByProcInstId(pInstId);
        TProjectMeeting tProjectMeeting=null;
        if(tProjectDecision!=null){
            tProjectMeeting=tProjectMeetingService.selectTProjectMeetingByProjectPoolId(tProjectDecision.getProjectPoolId());
        }
        return tProjectMeeting;
    }
    /**
     * 根据流程Id查询汇总分数和平均分数
     * @param pInstId
     * @return
     */
    @Override
    public Map<String, String> selectSumScore(String pInstId) {
        TProjectDecision tProjectDecision=this.selectTProjectDecisionByProcInstId(pInstId);
        Map<String, String> sumScore=new HashMap<>();
        if(tProjectDecision!=null){
            TProjectMeeting tProjectMeeting=tProjectMeetingService.selectTProjectMeetingByProjectPoolId(tProjectDecision.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();
        // 对应业务单据
        ProjectDecisionVo projectDecision = decisionMapper.selectProjectDecisionByProcInstId(procInsId);
        if (projectDecision == null) {
            return;
        }
        // 申请人
        SysUser applyUserInfo = sysUserService.selectUserById(Long.valueOf(projectDecision.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 ("decision".equals(flowBaseInfo.getTaskDefKey())&&"decision".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() + ",您好。投资系统中" + projectDecision.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()+"，您好。你在投资系统中提交" + projectDecision.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()+"，您好。你在投资系统中提交" + projectDecision.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()+"，您好。你在投资系统中提交" + projectDecision.getProjectName() + "的项目投决申请已审核，结果为"+result+"，请查看！";
                    if (applyUserInfo != null && StringUtils.isNotBlank(applyUserInfo.getPhonenumber())) {
                        try{
                            SmsSenderUtils.sendSms(applyUserInfo.getPhonenumber(), completeContents);
                        } catch (IOException e) {
                            logger.error("短信发送失败"+e.getMessage());
                        }
                    }
                }
            }

        }
    }

    /**
     * 跳节点
     * @param projectDecision
     * @param flow
     * @throws Exception
     */
    public void getAssignee(TProjectDecision projectDecision, FlowBaseInfo flow) throws Exception {
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();//当前登陆人
        if (sysUser == null) {
            sysUser=sysUserService.selectUserById(Long.parseLong(projectDecision.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) || projectDecision.getCreateBy().equals(assignee))) {
                JumpNode(projectDecision, flow);
            }
        }
    }
    public Map<String, Object> JumpNode(TProjectDecision projectDecision, 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();
            Task task=list.get(0);
            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("meeting".equals(task.getTaskDefinitionKey())) {
                //立项审批人
                List<String> userIds = Arrays.asList(projectDecision.getParticipantsId().split(","));
                formProperties.put("decisionList", userIds);
            }
            if(StringUtils.isNotBlank(projectDecision.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(projectDecision,flow);
            }

        }
        return rs;
    }

}
