package com.ruoyi.project.ehs.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpContextUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.apply.domain.TApplyOfflinevalve;
import com.ruoyi.project.apply.domain.TApplySafetychange;
import com.ruoyi.project.apply.service.ITApplyOfflinevalveService;
import com.ruoyi.project.apply.service.ITApplySafetychangeService;
import com.ruoyi.project.approve.damain.DevProcess;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.common.service.ITCommonfileService;
import com.ruoyi.project.ehs.domain.TApproveAccident;
import com.ruoyi.project.ehs.domain.TApproveDanger;
import com.ruoyi.project.ehs.service.ITApproveAccidentService;
import com.ruoyi.project.ehs.service.ITApproveDangerService;
import com.ruoyi.project.intact.domain.TApproveMaintenance;
import com.ruoyi.project.intact.domain.TIntactApprove;
import com.ruoyi.project.intact.service.ITApproveMaintenanceService;
import com.ruoyi.project.intact.service.ITIntactApproveService;
import com.ruoyi.project.invoice.domain.TApproveReserveInvoice;
import com.ruoyi.project.invoice.service.ITApproveReserveInvoiceService;
import com.ruoyi.project.listener.EndSucessListener;
import com.ruoyi.project.listener.ExecutorTaskCreateListener;
import com.ruoyi.project.listener.RecorderTaskCreateListener;
import com.ruoyi.project.listener.VerificationTaskCreateListener;
import com.ruoyi.project.production.domain.TSaiApply;
import com.ruoyi.project.production.service.ITSaiApplyService;
import com.ruoyi.project.pssr.domain.TPssrAboveall;
import com.ruoyi.project.pssr.domain.TPssrApprove;
import com.ruoyi.project.pssr.domain.TPssrSubcontent;
import com.ruoyi.project.pssr.service.ITPssrAboveallService;
import com.ruoyi.project.pssr.service.ITPssrApproveService;
import com.ruoyi.project.pssr.service.ITPssrSubcontentService;
import com.ruoyi.project.reliability.domain.TKekaoApprove;
import com.ruoyi.project.reliability.service.ITKekaoApproveService;
import com.ruoyi.project.sems.domain.TApprove;
import com.ruoyi.project.sems.his.domain.TApproveSpecModify;
import com.ruoyi.project.sems.his.service.ITApproveSpecModifyService;
import com.ruoyi.project.sems.safecheck.domain.TSpecWeekcheck;
import com.ruoyi.project.sems.safecheck.service.ITSpecWeekcheckService;
import com.ruoyi.project.sems.service.ITApproveService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.SysUserRole;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.training.bccnew.domain.TTsApprove;
import com.ruoyi.project.training.bccnew.service.ITTsApproveService;
import com.ruoyi.project.training.spec.domain.TStApprove;
import com.ruoyi.project.training.spec.service.ITStApproveService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患申请Controller
 *
 * @author ruoyi
 * @date 2021-02-20
 */
@RestController
@RequestMapping("/ehs/approvedanger")
public class TApproveDangerController extends BaseController {
    @Autowired
    private ITApproveDangerService tApproveDangerService;

    @Autowired
    private ITApproveAccidentService tApproveAccidentService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITCommonfileService tCommonfileService;
    @Autowired
    private ITApproveService tApproveService;
    @Autowired
    private ITApproveSpecModifyService tApproveSpecModifyService;
    @Autowired
    private ITStApproveService tStApproveService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ITApproveMaintenanceService tApproveMaintenanceService;
    @Autowired
    private ITIntactApproveService tIntactApproveService;
    @Autowired
    private ITKekaoApproveService tKekaoApproveService;
    @Autowired
    private ITApproveReserveInvoiceService tApproveReserveInvoiceService;

    @Autowired
    private ITApplyOfflinevalveService tApplyOfflinevalveService;

    @Autowired
    private ITApplySafetychangeService tApplySafetychangeService;

    @Autowired
    private ITSaiApplyService tSaiApplyService;
    @Autowired
    private ITSpecWeekcheckService tSpecWeekcheckService;
    @Autowired
    private ITTsApproveService tTsApproveService;
    @Autowired
    private ITPssrApproveService tPssrApproveService;
    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;
    @Autowired
    private ITPssrAboveallService tPssrAboveallService;

    /**
     * 任务申请
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody TApproveDanger tApprove) {
        try {
            logger.info("任务申请" + JSON.toJSONString(tApprove));
            Long userid = getUserId();
            //审批编号
            Date dt = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String data = sdf.format(dt) + userid;
            tApprove.setApproveNo(data);
            tApprove.setRecorderId(userid);
            logger.info("tApprove:" + tApprove);
            tApproveDangerService.insertTApproveDanger(tApprove);

            Map<String, Object> variables = new HashMap<>();
            //执行人、验证人确认
            Long verificationId = null;
            Long deptId = sysUserService.selectUserById(userid).getDeptId();
            List<SysUser> deptPerson = sysUserService.selectUserByDept(deptId);
            for (SysUser s : deptPerson) {
                SysUserRole userRole = sysUserService.selectRoleByUserId(s.getUserId());
                if (userRole.getRoleId() == 100) {
                    verificationId = userRole.getUserId();
                }
            }
            tApprove.setVerificationId(verificationId);

            //开始工作流、监听
            variables.put("endSucessListener", new EndSucessListener());
            variables.put("recorderTaskCreateListener", new RecorderTaskCreateListener());
            variables.put("executorTaskCreateListener", new ExecutorTaskCreateListener());
            variables.put("verificationTaskCreateListener", new VerificationTaskCreateListener());

            //审批人员设置
            variables.put("recorder", userid);
            variables.put("executor", tApprove.getExecutorId());
            variables.put("verification", verificationId);
            logger.info("executor:" + tApprove.getExecutorId());
            logger.info("verification:" + verificationId);

            long bussniseeKey = tApprove.getId();
            logger.info("bussniseeKey:" + bussniseeKey);
            Authentication.setAuthenticatedUserId(userid.toString());
            //采用key来启动流程定义并设置流程变量，返回流程实例
            ProcessInstance pi = null;
            if (tApprove.getHiddendangerLevel() == 2) {
                pi = runtimeService.startProcessInstanceByKey("commonProcess", String.valueOf(bussniseeKey), variables);
            } else if (tApprove.getHiddendangerLevel() == 3) {
                //初始化会签人员
                List<Long> confirmlist = new ArrayList<>();
                confirmlist.add(tApprove.getConfirmoneId());
                confirmlist.add(tApprove.getConfirmtwoId());
                //条件表达式方法 一定要序列号
                variables.put("confirmlist", confirmlist);
                pi = runtimeService.startProcessInstanceByKey("majorProcess", String.valueOf(bussniseeKey), variables);
            }

            logger.info("流程部署id：" + pi.getDeploymentId());
            logger.info("流程定义id：" + pi.getProcessDefinitionId());
            logger.info("流程实例id：" + pi.getProcessInstanceId());
            logger.info("流程定义对象：" + pi.getProcessVariables());
            tApprove.setProcessId(Long.parseLong(pi.getProcessInstanceId()));

            logger.info("tApprove:" + tApprove);
            tApproveDangerService.updateTApproveDanger(tApprove);
        } catch (Exception e) {
            logger.info("e:" + e);
        }
        return AjaxResult.success("申请成功", tApprove);
    }

    /**
     * 一般隐患任务申请
     */
    @PostMapping("/savegeneral")
    public AjaxResult saveGeneral(@RequestBody TApproveDanger tApprove) {
        try {
            Long userid = getUserId();
            tApprove.setRecorderId(userid);
            logger.info("tApprove:" + tApprove);
            //tApproveDangerService.insertTApproveDanger(tApprove);
        } catch (Exception e) {
            logger.info("e:" + e);
            return AjaxResult.error(e.toString());
        }
        return AjaxResult.success("申请成功");
    }

    /**
     * 我的申请列表
     */
    @GetMapping("/myApprovelist")
    public TableDataInfo myApprovelist(@RequestParam Map<String, Object> params) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //查询发起流程
        List<HistoricProcessInstance> historicProcessInstanceList = null;
        Long count;
        if (StringUtils.isEmpty(params.getOrDefault("definitionKey", "").toString())) {
            historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery()
                    .startedBy(getUserId().toString()).orderByProcessInstanceStartTime().desc()//参与者，组任务查询
                    .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
            count = historyService.createHistoricProcessInstanceQuery()
                    .startedBy(getUserId().toString()).count();
        } else {
            historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery()
                    .startedBy(getUserId().toString()).orderByProcessInstanceStartTime().desc()//参与者，组任务查询
                    .processDefinitionKeyIn(JSON.parseArray(params.get("definitionKey").toString(), String.class))
                    .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
            count = historyService.createHistoricProcessInstanceQuery()
                    .processDefinitionKeyIn(JSON.parseArray(params.get("definitionKey").toString(), String.class))
                    .startedBy(getUserId().toString()).count();
        }
        logger.info(JSON.toJSONString(historicProcessInstanceList));
        //整合我的申请数据
        List<DevProcess> list = new ArrayList<>();
        if (historicProcessInstanceList.size() > 0)
            for (HistoricProcessInstance h : historicProcessInstanceList
            ) {
                HistoricProcessInstance pi = processEngine.getHistoryService()
                        .createHistoricProcessInstanceQuery().processInstanceId(h.getId()).singleResult();
                logger.info(JSON.toJSONString(pi));
                if (pi == null) {
                    continue;
                }
                DevProcess devProcess = new DevProcess();
                logger.info("审批类型" + pi.getProcessDefinitionName());
                devProcess.setBusinessKey(pi.getBusinessKey());
                devProcess.setProcessCreateTime(pi.getStartTime());
                devProcess.setProcessId(pi.getId());
                devProcess.setProcessName(pi.getProcessDefinitionName());
                try {
                    if (pi.getProcessDefinitionName().equals("特种设备审核")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(h.getBusinessKey()));
                        devProcess.setSpecApprove(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("年度检查报告申请")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(h.getBusinessKey()));
                        devProcess.setSpecApprove(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("月度检查")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(h.getBusinessKey()));
                        devProcess.setSpecApprove(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备修改/删除审核") || pi.getProcessDefinitionName().equals("设备新增/删除审核")) {
                        TApproveSpecModify approve = tApproveSpecModifyService.selectTApproveSpecModifyById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveSpecModify(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("事件审批流程")) {
                        TApproveDanger approveDanger = tApproveDangerService.selectTApproveDangerById(Long.parseLong(h.getBusinessKey()));
                        devProcess.settApprove(approveDanger);
                        devProcess.setApNo(approveDanger.getApproveNo());
                    } else if (pi.getProcessDefinitionName().equals("重大隐患审批流程") || pi.getProcessDefinitionName().equals("普通隐患审批流程")) {
                        TApproveDanger approveDanger = tApproveDangerService.selectTApproveDangerById(Long.parseLong(h.getBusinessKey()));
                        devProcess.settApprove(approveDanger);
                        devProcess.setApNo(approveDanger.getApproveNo());
                    } else if (pi.getProcessDefinitionName().equals("专项培训计划审核")) {
                        TStApprove approve = tStApproveService.selectTStApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备维修审批流程")) {
                        TApproveMaintenance approve = tApproveMaintenanceService.selectTApproveMaintenanceById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备变更申请")) {
                        TIntactApprove approve = tIntactApproveService.selectTIntactApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("可靠性管理申请")) {
                        TKekaoApprove approve = tKekaoApproveService.selectTKekaoApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("预约开票审批流程")) {
                        TApproveReserveInvoice approve = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("安全阀离线/切出申请流程")) {
                        TApplyOfflinevalve approve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("组织保护措施状态变更申请流程")) {
                        TApplySafetychange approve = tApplySafetychangeService.selectTApplySafetychangeById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("SAI开项申请流程")) {
                        TSaiApply approve = tSaiApplyService.selectTSaiApplyById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("每周安全排查报告")) {
                        TSpecWeekcheck t = tSpecWeekcheckService.selectTSpecWeekcheckById(Long.parseLong(pi.getBusinessKey()));
                        SysUser user = sysUserService.selectUserById(Long.valueOf(t.getCreaterCode()));
                        devProcess.setApNo(t.getId().toString());
                        devProcess.setApName(user.getNickName());
                        devProcess.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().equals("导师带徒经理审批")) {
                        TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().equals("导师带徒学员成绩不合格审批")) {
                        TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().equals("PSSR装置经理审批")) {
                        TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                        TPssrAboveall tPssrAboveall = tPssrAboveallService.selectTPssrAboveallById(t.getAboveallId());
                        devProcess.setProcessName(pi.getProcessDefinitionName()+"_"+tPssrAboveall.getUnit());
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().contains("PSSR")&&!pi.getProcessDefinitionName().equals("PSSR装置经理审批")) {
                        TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                        TPssrSubcontent tPssrSubcontent = tPssrSubcontentService.selectTPssrSubcontentById(t.getSubId());
                        t.setSn(tPssrSubcontent.getForShort());
                        devProcess.setProcessName(pi.getProcessDefinitionName()+"_"+tPssrSubcontent.getUnit()+"_"+tPssrSubcontent.getItem());
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    }
                } catch (Exception e) {
                    logger.error(e.toString());
                }

                if (pi.getEndActivityId() != null) {
                    devProcess.setEnd(true);
                } else {
                    devProcess.setEnd(false);
                }
                ;
                logger.info("devProcess:" + devProcess);
                list.add(devProcess);
            }
        return getDataTable(list, count);
    }

    /**
     * 我的待办列表
     */
    @GetMapping("/backlogList")
    public TableDataInfo backlogList(@RequestParam Map<String, Object> params) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        List<Task> taskList;
        //分页数据
        Long count;
        if (StringUtils.isEmpty(params.getOrDefault("definitionKey", "").toString())) {
            taskList = processEngine.getTaskService()//获取任务service
                    .createTaskQuery()//创建查询对象
                    .taskCandidateOrAssigned(getUserId().toString())
                    //                .taskAssignee(getUserId().toString())
                    .orderByTaskCreateTime().desc()//参与者，组任务查询
                    .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
            count = processEngine.getTaskService().createTaskQuery().taskCandidateOrAssigned(getUserId().toString()).count();
        } else {
            taskList = processEngine.getTaskService()//获取任务service
                    .createTaskQuery()//创建查询对象
                    .taskCandidateOrAssigned(getUserId().toString())
                    .processDefinitionKeyIn(JSON.parseArray(params.get("definitionKey").toString(), String.class))
                    //                .taskAssignee(getUserId().toString())
                    .orderByTaskCreateTime().desc()//参与者，组任务查询
                    .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
            count = processEngine.getTaskService().createTaskQuery().taskCandidateOrAssigned(getUserId().toString()).
                    processDefinitionKeyIn(JSON.parseArray(params.get("definitionKey").toString(), String.class)).count();
        }
        List<DevTask> list = new ArrayList<>();
        if (taskList.size() > 0) {
            try {
                for (Task task : taskList) {
                    ProcessInstance pi = processEngine.getRuntimeService()/**表示正在执行的流程实例和执行对象*/
                            .createProcessInstanceQuery()/**创建流程实例查询*/
                            .processInstanceId(task.getProcessInstanceId())/**使用流程实例ID查询*/
                            .singleResult();
                    logger.info("待办任务ID:" + task.getId());
                    logger.info("待办任务name:" + task.getName());
                    logger.info("待办任务创建时间:" + task.getCreateTime());
                    logger.info("待办任务办理人:" + task.getAssignee());
                    logger.info("流程实例ID:" + task.getProcessInstanceId());
                    logger.info("执行对象ID:" + task.getExecutionId());
                    logger.info(task.getTenantId());
                    logger.info(task.getCategory());
                    logger.info(task.getFormKey());
                    logger.info("流程实例Name:" + pi.getProcessDefinitionName());
                    DevTask devTask = new DevTask();
                    devTask.setTaskId(task.getId());
                    devTask.setTaskName(task.getName());
                    devTask.setTaskCreateTime(task.getCreateTime());
                    devTask.setProcessId(task.getProcessInstanceId());
                    devTask.setProcessName(pi.getProcessDefinitionName());
                    devTask.setProcessCreateTime(pi.getStartTime());
                    devTask.setBusinessKey(pi.getBusinessKey());
                    if (pi.getProcessDefinitionName().equals("重大隐患审批流程") || pi.getProcessDefinitionName().equals("普通隐患审批流程")) {
                        TApproveDanger approveDanger = tApproveDangerService.selectTApproveDangerById(Long.parseLong(pi.getBusinessKey()));
                        devTask.settApprove(approveDanger);
                        devTask.setApNo(approveDanger.getApproveNo());
                    } else if (pi.getProcessDefinitionName().equals("事件审批流程")) {
                        TApproveAccident approveAccident = tApproveAccidentService.selectTApproveAccidentById(Long.parseLong(pi.getBusinessKey()));
                        devTask.settApproveAccident(approveAccident);
                        devTask.setApNo(approveAccident.getApproveNo());
                    } else if (pi.getProcessDefinitionName().equals("特种设备审核")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setSpecApprove(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("年度检查报告申请")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setSpecApprove(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("月度检查")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setSpecApprove(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备修改/删除审核") || pi.getProcessDefinitionName().equals("设备新增/删除审核")) {
                        TApproveSpecModify approve = tApproveSpecModifyService.selectTApproveSpecModifyById(Long.parseLong(pi.getBusinessKey()));
                        logger.info("设备修改/删除审核" + JSON.toJSONString(approve));
                        devTask.setApproveSpecModify(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("专项培训计划审核")) {
                        TStApprove approve = tStApproveService.selectTStApproveById(Long.parseLong(pi.getBusinessKey()));
                        logger.info("专项培训计划审核" + JSON.toJSONString(approve));
                        devTask.setApproveObj(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备维修审批流程")) {
                        TApproveMaintenance approve = tApproveMaintenanceService.selectTApproveMaintenanceById(Long.parseLong(pi.getBusinessKey()));
                        logger.info("设备维修审批流程" + JSON.toJSONString(approve));
                        devTask.setApproveObj(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备变更申请")) {
                        TIntactApprove approve = tIntactApproveService.selectTIntactApproveById(Long.parseLong(pi.getBusinessKey()));
                        logger.info("设备变更申请" + JSON.toJSONString(approve));
                        devTask.setApproveObj(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("可靠性管理申请")) {
                        TKekaoApprove approve = tKekaoApproveService.selectTKekaoApproveById(Long.parseLong(pi.getBusinessKey()));
                        logger.info("可靠性管理申请" + JSON.toJSONString(approve));
                        devTask.setApproveObj(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("预约开票审批流程")) {
                        TApproveReserveInvoice approve = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApproveObject(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("安全阀离线/切出申请流程")) {
                        TApplyOfflinevalve approve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApproveObject(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("组织保护措施状态变更申请流程")) {
                        TApplySafetychange approve = tApplySafetychangeService.selectTApplySafetychangeById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApproveObject(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("SAI开项申请流程")) {
                        TSaiApply approve = tSaiApplyService.selectTSaiApplyById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApproveObject(approve);
                        devTask.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("每周安全排查报告")) {
                        TSpecWeekcheck t = tSpecWeekcheckService.selectTSpecWeekcheckById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApproveObject(t);
                        devTask.setApNo(t.getId().toString());
                    } else if (pi.getProcessDefinitionName().equals("导师带徒经理审批")) {
                        TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApNo(t.getApNo());
                        devTask.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().equals("导师带徒学员成绩不合格审批")) {
                        TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                        devTask.setApNo(t.getApNo());
                        devTask.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().equals("PSSR装置经理审批")) {
                        TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                        TPssrAboveall tPssrAboveall = tPssrAboveallService.selectTPssrAboveallById(t.getAboveallId());
                        devTask.setProcessName(pi.getProcessDefinitionName()+"_"+tPssrAboveall.getUnit());
                        devTask.setApNo(t.getApNo());
                        devTask.setApproveObject(t);
                    }  else if (pi.getProcessDefinitionName().contains("PSSR")&&!pi.getProcessDefinitionName().equals("PSSR装置经理审批")) {
                        TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                        TPssrSubcontent tPssrSubcontent = tPssrSubcontentService.selectTPssrSubcontentById(t.getSubId());
                        t.setSn(tPssrSubcontent.getForShort());
                        devTask.setProcessName(pi.getProcessDefinitionName()+"_"+tPssrSubcontent.getUnit()+"_"+tPssrSubcontent.getItem());
                        devTask.setApNo(t.getApNo());
                        devTask.setApproveObject(t);
                    }
                    list.add(devTask);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getDataTable(list, count);
    }

    /**
     * 已办任务列表
     */
    @GetMapping("/doneTaskList")
    public TableDataInfo doneTaskList(@RequestParam Map<String, Object> params) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        List<HistoricTaskInstance> taskList;
        //分页数据
        Long count;
        if (StringUtils.isEmpty(params.getOrDefault("definitionKey", "").toString())) {
            taskList = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(getUserId().toString())
                    .finished().orderByHistoricTaskInstanceEndTime().desc()
                    .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
            count = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(getUserId().toString())
                    .finished().count();
        } else {
            taskList = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(getUserId().toString())
                    .processDefinitionKeyIn(JSON.parseArray(params.get("definitionKey").toString(), String.class))
                    .finished().orderByHistoricTaskInstanceEndTime().desc()
                    .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
            count = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(getUserId().toString())
                    .processDefinitionKeyIn(JSON.parseArray(params.get("definitionKey").toString(), String.class))
                    .finished().count();
        }
        logger.info(JSON.toJSONString(taskList));
        List<DevProcess> list = new ArrayList<>();
        if (taskList.size() > 0) {
            for (HistoricTaskInstance h : taskList) {
                //logger.info("HistoricTaskInstance:" + JSON.toJSONString(h));
                HistoricProcessInstance pi = processEngine.getHistoryService()
                        .createHistoricProcessInstanceQuery().processInstanceId(h.getProcessInstanceId()).singleResult();
                logger.info(JSON.toJSONString(pi));
                if (pi == null) {
                    continue;
                }
                DevProcess devProcess = new DevProcess();
                devProcess.setBusinessKey(pi.getBusinessKey());
                devProcess.setProcessCreateTime(pi.getStartTime());
                devProcess.setProcessId(pi.getId());
                devProcess.setProcessName(pi.getProcessDefinitionName());

                if (pi.getProcessDefinitionName().equals("特种设备审核")) {
                    TApprove approve = tApproveService.selectTApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setSpecApprove(approve);
                } else if (pi.getProcessDefinitionName().equals("年度检查报告申请")) {
                    TApprove approve = tApproveService.selectTApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setSpecApprove(approve);
                } else if (pi.getProcessDefinitionName().equals("月度检查")) {
                    TApprove approve = tApproveService.selectTApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setSpecApprove(approve);
                } else if (pi.getProcessDefinitionName().equals("设备修改/删除审核") || pi.getProcessDefinitionName().equals("设备新增/删除审核")) {
                    TApproveSpecModify approve = tApproveSpecModifyService.selectTApproveSpecModifyById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveSpecModify(approve);
                } else if (pi.getProcessDefinitionName().equals("专项培训计划审核")) {
                    TStApprove approve = tStApproveService.selectTStApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("设备维修审批流程")) {
                    TApproveMaintenance approve = tApproveMaintenanceService.selectTApproveMaintenanceById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("设备变更申请")) {
                    TIntactApprove approve = tIntactApproveService.selectTIntactApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("可靠性管理申请")) {
                    TKekaoApprove approve = tKekaoApproveService.selectTKekaoApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("预约开票审批流程")) {
                    TApproveReserveInvoice approve = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approve.getUserId());
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("安全阀离线/切出申请流程")) {
                    TApplyOfflinevalve approve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(Long.valueOf(approve.getCreaterCode()));
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("组织保护措施状态变更申请流程")) {
                    TApplySafetychange approve = tApplySafetychangeService.selectTApplySafetychangeById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(Long.valueOf(approve.getCreaterCode()));
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("SAI开项申请流程")) {
                    TSaiApply approve = tSaiApplyService.selectTSaiApplyById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(Long.valueOf(approve.getCreateBy()));
                    devProcess.setApNo(approve.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(approve);
                } else if (pi.getProcessDefinitionName().equals("每周安全排查报告")) {
                    TSpecWeekcheck t = tSpecWeekcheckService.selectTSpecWeekcheckById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(Long.valueOf(t.getCreaterCode()));
                    devProcess.setApNo(t.getId().toString());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(t);
                } else if (pi.getProcessDefinitionName().equals("导师带徒经理审批")) {
                    TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(Long.valueOf(t.getCreaterCode()));
                    devProcess.setApNo(t.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(t);
                } else if (pi.getProcessDefinitionName().equals("导师带徒学员成绩不合格审批")) {
                    TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(Long.valueOf(t.getCreaterCode()));
                    devProcess.setApNo(t.getApNo());
                    devProcess.setApName(user.getNickName());
                    devProcess.setApproveObject(t);
                } else if (pi.getProcessDefinitionName().equals("PSSR装置经理审批")) {
                    TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                    TPssrAboveall tPssrAboveall = tPssrAboveallService.selectTPssrAboveallById(t.getAboveallId());
                    devProcess.setProcessName(pi.getProcessDefinitionName()+"_"+tPssrAboveall.getUnit());
                    devProcess.setApNo(t.getApNo());
                    devProcess.setApproveObject(t);
                }  else if (pi.getProcessDefinitionName().contains("PSSR")&&!pi.getProcessDefinitionName().equals("PSSR装置经理审批")) {
                    TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                    TPssrSubcontent tPssrSubcontent = tPssrSubcontentService.selectTPssrSubcontentById(t.getSubId());
                    t.setSn(tPssrSubcontent.getForShort());
                    devProcess.setProcessName(pi.getProcessDefinitionName()+"_"+tPssrSubcontent.getUnit()+"_"+tPssrSubcontent.getItem());
                    SysUser user = sysUserService.selectUserById(Long.valueOf(t.getCreaterCode()));
                    devProcess.setApName(user.getNickName());
                    devProcess.setApNo(t.getApNo());
                    devProcess.setApproveObject(t);
                } else {
                    TApproveDanger approveDanger = tApproveDangerService.selectTApproveDangerById(Long.parseLong(pi.getBusinessKey()));
                    SysUser user = sysUserService.selectUserById(approveDanger.getRecorderId());
                    approveDanger.setRecorderName(user.getNickName());
                    devProcess.settApprove(approveDanger);
                    devProcess.setApNo(approveDanger.getApproveNo());
                    devProcess.setApName(user.getNickName());
                }
                logger.info("devProcess:" + devProcess);
                if (pi.getEndActivityId() != null) {
                    devProcess.setEnd(true);
                } else {
                    devProcess.setEnd(false);
                }
                list.add(devProcess);
            }
        }
        return getDataTable(list, count);
    }

    /**
     * 审核处理
     */
    @Log(title = "隐患审核处理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        logger.info("devTask:" + devTask);
        Map<String, Object> param = new HashMap<>();
        param.put("submitType", devTask.getSubmitType());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        logger.info("Assignee:" + task.getAssignee());
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        System.out.println(processInstancesId);
        //认领任务
        processEngine.getTaskService()//
                .claim(taskId, getUserId().toString());
//        Authentication.setAuthenticatedUserId("cmc"); // 添加批注时候的审核人
        if (devTask.getComment() == null) {
            devTask.setComment("");
        }
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        //业务监听处理
//        tApproveService.handleApprove(task ,devTask);
        taskService.complete(taskId, param);

        //执行人上传措施前后照片
        if (devTask.getTaskName().equals("执行人") && devTask.getSubmitType().equals("1")) {
            TApproveDanger updatepicture = devTask.gettApprove();
            updatepicture.setBeforeUrl(devTask.getBeforeUrl());
            updatepicture.setBeforeFilename(devTask.getBeforeFilename());
            updatepicture.setAfterUrl(devTask.getAfterUrl());
            updatepicture.setAfterFilename(devTask.getAfterFilename());
            tApproveDangerService.updateTApproveDanger(updatepicture);
        }
        //流程结束，approveDanger实体类实际完成时间字段更新
        if (devTask.getTaskName().equals("验证人") && devTask.getSubmitType().equals("1")) {
            TApproveDanger updateEndTime = devTask.gettApprove();
            updateEndTime.setEndtime(new Date());
            tApproveDangerService.updateTApproveDanger(updateEndTime);
        }
        return AjaxResult.success();
    }

    /**
     * 流转列表
     */
    @GetMapping("/hiTaskList")
    public TableDataInfo hiTaskList(@RequestParam Map<String, Object> params) {
        String pid = (String) params.get("processId");
        logger.info("processId：" + JSON.toJSONString(pid));
        HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
        List<HistoricTaskInstance> htiLists = htiq.processInstanceId(pid).finished().orderByHistoricTaskInstanceEndTime().asc().list();


        logger.info("历史任务：" + JSON.toJSONString(htiLists));
        List<DevTask> devTaskList = new ArrayList<>();
        if (htiLists.size() > 0) {
            for (HistoricTaskInstance hi : htiLists
            ) {
                List<Comment> commentList = taskService.getTaskComments(hi.getId());
                logger.info("评论列表：" + JSON.toJSONString(commentList));
                DevTask devTask = new DevTask();
                devTask.setTaskName(hi.getName());
                devTask.setTaskCreateTime(hi.getCreateTime());
                devTask.setTaskEndTime(hi.getEndTime());
                if (commentList.size() > 0) {
                    devTask.setComment(commentList.get(0).getFullMessage());
                }
                SysUser user = sysUserService.selectUserById(Long.parseLong(hi.getAssignee()));
                devTask.setUserName(user.getNickName());
                devTaskList.add(devTask);
            }
        }
        //当前任务
        try {
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(pid).active().list();
            if (CollectionUtils.isNotEmpty(tasks)) {
                tasks.forEach(task -> {
                    task.getName();
                    task.getCreateTime();
                    DevTask devTask = new DevTask();
                    devTask.setTaskName(task.getName());
                    devTask.setTaskCreateTime(task.getCreateTime());
                    if (task.getAssignee() != null) {
                        SysUser user = sysUserService.selectUserById(Long.parseLong(task.getAssignee()));
                        devTask.setUserName(user.getNickName());
                    }
                    devTaskList.add(devTask);
                });
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return getDataTable(devTaskList);
    }

    /**
     * 查询隐患申请列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:approvedanger:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApproveDanger tApproveDanger) {
        startPage();
        List<TApproveDanger> list = tApproveDangerService.selectTApproveDangerList(tApproveDanger);
        return getDataTable(list);
    }

    /**
     * 导出隐患申请列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:approvedanger:export')")
    @Log(title = "隐患申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproveDanger tApproveDanger) {
        List<TApproveDanger> list = tApproveDangerService.selectTApproveDangerList(tApproveDanger);
        ExcelUtil<TApproveDanger> util = new ExcelUtil<TApproveDanger>(TApproveDanger.class);
        return util.exportExcel(list, "approvedanger");
    }

    /**
     * 获取隐患申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:approvedanger:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tApproveDangerService.selectTApproveDangerById(id));
    }

    /**
     * 新增隐患申请
     */
    @PreAuthorize("@ss.hasPermi('ehs:approvedanger:add')")
    @Log(title = "隐患申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveDanger tApproveDanger) {
        return toAjax(tApproveDangerService.insertTApproveDanger(tApproveDanger));
    }

    /**
     * 修改隐患申请
     */
    @PreAuthorize("@ss.hasPermi('ehs:approvedanger:edit')")
    @Log(title = "隐患申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveDanger tApproveDanger) {
        return toAjax(tApproveDangerService.updateTApproveDanger(tApproveDanger));
    }

    /**
     * 删除隐患申请
     */
    @PreAuthorize("@ss.hasPermi('ehs:approvedanger:remove')")
    @Log(title = "隐患申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApproveDangerService.deleteTApproveDangerByIds(ids));
    }

    @GetMapping("processImg/{processId}")
    public void currentProcessInstanceImage(@PathVariable("processId") String processId, HttpServletResponse response) throws IOException {
        InputStream inputStream = currentProcessInstanceImage(processId);
        OutputStream outputStream = response.getOutputStream();
        HttpContextUtils.copyImageStream(inputStream, outputStream);
    }

    /**
     * 获取当前任务流程图
     *
     * @param processId
     * @return
     */
    public InputStream currentProcessInstanceImage(String processId) {
//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
//        ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processId);
        HistoricProcessInstance hi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();
        ProcessDefinition processDefinition = repositoryService.getProcessDefinition(hi.getProcessDefinitionId());

        BpmnModel bpmnModel = repositoryService.getBpmnModel(hi.getProcessDefinitionId());
        // ID 为 流程定义Key
        Process process = bpmnModel.getProcessById(processDefinition.getKey());

        // 流程节点ID
        // 获取历史流程实例
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();
        // 获取流程中已经执行的节点，按照执行先后顺序排序
        List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId)
                .orderByHistoricActivityInstanceId().asc().list();
        // 高亮已经执行流程节点ID集合
        List<String> highLightedActivitiIds = new ArrayList<>();
        for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
            highLightedActivitiIds.add(historicActivityInstance.getActivityId());
        }
        //获取已完成的节点
        List<HistoricActivityInstance> finished = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processId)
                .finished().list();
        //高亮线路id集合
//        List<String> highLightedFlowIds = getHighLightedFlows(bpmnModel, historicActivityInstances);
        List<String> highLightedFlowIds = getHighLine(bpmnModel, historicActivityInstances, finished);
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();

//     生成流程图
//        InputStream inputStream = generator.generateJpgDiagram(bpmnModel);
//        InputStream inputStream = generator.generatePngDiagram(bpmnModel);
//        InputStream inputStream = generator.generateDiagram(bpmnModel, "jpg", highLightedActivities);

// 生成图片
        InputStream inputStream = generator.generateDiagram(bpmnModel, "jpg", highLightedActivitiIds, highLightedFlowIds, "宋体", "宋体", "宋体", null, 2.0);
        return inputStream;
    }

    /**
     * 获取流程定义图片
     *
     * @param processDefinitionId
     * @return
     */
    public InputStream getDefinitionImage(String processDefinitionId) {

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
        return inputStream;
    }


    /**
     * 获取已经流转的线
     *
     * @param bpmnModel
     * @param historicActivityInstances
     * @return
     */
    private static List<String> getHighLightedFlows(BpmnModel bpmnModel, List<HistoricActivityInstance> historicActivityInstances) {
        // 高亮流程已发生流转的线id集合
        List<String> highLightedFlowIds = new ArrayList<>();
        // 全部活动节点
        List<FlowNode> historicActivityNodes = new ArrayList<>();
        // 已完成的历史活动节点
        List<HistoricActivityInstance> finishedActivityInstances = new ArrayList<>();

        for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
            FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(historicActivityInstance.getActivityId(), true);
            historicActivityNodes.add(flowNode);
            if (historicActivityInstance.getEndTime() != null) {
                finishedActivityInstances.add(historicActivityInstance);
            }
        }

        FlowNode currentFlowNode = null;
        FlowNode targetFlowNode = null;
        // 遍历已完成的活动实例，从每个实例的outgoingFlows中找到已执行的
        for (HistoricActivityInstance currentActivityInstance : finishedActivityInstances) {
            // 获得当前活动对应的节点信息及outgoingFlows信息
            currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currentActivityInstance.getActivityId(), true);
            List<SequenceFlow> sequenceFlows = currentFlowNode.getOutgoingFlows();

            /**
             * 遍历outgoingFlows并找到已已流转的 满足如下条件认为已已流转： 1.当前节点是并行网关或兼容网关，则通过outgoingFlows能够在历史活动中找到的全部节点均为已流转 2.当前节点是以上两种类型之外的，通过outgoingFlows查找到的时间最早的流转节点视为有效流转
             */
            if ("parallelGateway".equals(currentActivityInstance.getActivityType()) || "inclusiveGateway".equals(currentActivityInstance.getActivityType())) {
                // 遍历历史活动节点，找到匹配流程目标节点的
                for (SequenceFlow sequenceFlow : sequenceFlows) {
                    targetFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getTargetRef(), true);
                    if (historicActivityNodes.contains(targetFlowNode)) {
                        highLightedFlowIds.add(targetFlowNode.getId());
                    }
                }
            } else {
                List<Map<String, Object>> tempMapList = new ArrayList<>();
                for (SequenceFlow sequenceFlow : sequenceFlows) {
                    for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
                        if (historicActivityInstance.getActivityId().equals(sequenceFlow.getTargetRef())) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("highLightedFlowId", sequenceFlow.getId());
                            map.put("highLightedFlowStartTime", historicActivityInstance.getStartTime().getTime());
                            tempMapList.add(map);
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(tempMapList)) {
                    // 遍历匹配的集合，取得开始时间最早的一个
                    long earliestStamp = 0L;
                    String highLightedFlowId = null;
                    for (Map<String, Object> map : tempMapList) {
                        long highLightedFlowStartTime = Long.valueOf(map.get("highLightedFlowStartTime").toString());
                        if (earliestStamp == 0 || earliestStamp >= highLightedFlowStartTime) {
                            highLightedFlowId = map.get("highLightedFlowId").toString();
                            earliestStamp = highLightedFlowStartTime;
                        }
                    }

                    highLightedFlowIds.add(highLightedFlowId);
                }

            }

        }
        return highLightedFlowIds;
    }

    private List<String> getHighLine(BpmnModel bpmnModel, List<HistoricActivityInstance> historicActivityInstances, List<HistoricActivityInstance> finishedActivityInstances) {

        // 高亮流程已发生流转的线id集合
        List<String> highLightedFlowIds = new ArrayList<>();
        // 全部活动节点
        List<FlowNode> historicActivityNodes = new ArrayList<>();

        //1、拿到所有的活动节点定义
        for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
            FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(historicActivityInstance.getActivityId(), true);
            historicActivityNodes.add(flowNode);
        }

        FlowNode currentFlowNode;
        FlowNode targetFlowNode;
        // 2、遍历已完成的活动实例，从每个实例的outgoingFlows中找到已执行的
        for (HistoricActivityInstance currentActivityInstance : finishedActivityInstances) {
            // 获得当前活动对应的节点信息及outgoingFlows信息
            currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currentActivityInstance.getActivityId(), true);
            List<SequenceFlow> outgoingFlows = currentFlowNode.getOutgoingFlows();

            /*
             * 遍历outgoingFlows并找到已流转的 满足如下条件认为已已流转：
             * 1.当前节点是并行网关或包含网关，则通过outgoingFlows能够在历史活动中找到的全部节点均为已流转
             * 2.当前节点是以上两种类型之外的，通过outgoingFlows查找到的开始时间最早的流转节点视为有效流转
             */
            String activityType = currentActivityInstance.getActivityType();

            if ("parallelGateway".equals(currentActivityInstance.getActivityType()) || "inclusiveGateway".equals(currentActivityInstance.getActivityType())) {
                // 遍历历史活动节点，找到匹配流程目标节点的
                for (SequenceFlow sequenceFlow : outgoingFlows) {
                    targetFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getTargetRef(), true);
                    if (historicActivityNodes.contains(targetFlowNode)) {
                        highLightedFlowIds.add(targetFlowNode.getId());
                    }
                }
                continue;
            }

            //1、拿到所有的TargetRef
            List<String> targetRefList = outgoingFlows.stream()
                    .map(SequenceFlow::getTargetRef)
                    .collect(Collectors.toList());

            //2、拿到ActivityId == TargetRef的所有 HistoricActivityInstance
            List<HistoricActivityInstance> historicActivityInstanceList = historicActivityInstances.stream()
                    .filter((HistoricActivityInstance instance) -> targetRefList.contains(instance.getActivityId()))
                    .collect(Collectors.toList());

            //3、开始时间>=当前节点结束时间的第一个 HistoricActivityInstance
            List<HistoricActivityInstance> historicActivityInstanceResultList = historicActivityInstanceList.stream()
                    .filter(historicActivityInstance -> historicActivityInstance.getStartTime()
                            .compareTo(currentActivityInstance.getEndTime()) >= 0)
                    .sorted(Comparator.comparing(HistoricActivityInstance::getStartTime))
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(historicActivityInstanceResultList)) {
                continue;
            }

            HistoricActivityInstance historicActivityInstanceResult = historicActivityInstanceResultList.get(0);

            //4、HistoricActivityInstance拿到flowid
            List<SequenceFlow> sequenceFlowList = outgoingFlows.stream()
                    .filter(sequenceFlow -> sequenceFlow.getTargetRef().equals(historicActivityInstanceResult.getActivityId()))
                    .collect(Collectors.toList());
            highLightedFlowIds.addAll(sequenceFlowList.stream().map(e -> e.getId()).collect(Collectors.toList()));
        }
        return highLightedFlowIds;
    }
}
