package com.ruoyi.project.pssr.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
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.pssr.domain.*;
import com.ruoyi.project.pssr.mapper.TPssrNitrogenMapper;
import com.ruoyi.project.pssr.service.*;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统氮气置换Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/nitrogen")
public class TPssrNitrogenController extends BaseController {
    @Resource
    private TPssrNitrogenMapper tPssrNitrogenMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrNitrogenService tPssrNitrogenService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ISysUserService sysUserService;
    private String forShort = "dqzh";

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:add')")
    @PostMapping("/importData")
    public AjaxResult importInterlockData(MultipartFile file, Long subId) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TPssrNitrogen> list = new ArrayList<TPssrNitrogen>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 2; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TPssrNitrogen entity = new TPssrNitrogen();
                entity.setDeptId(userService.selectUserById(getUserId()).getDeptId());
                entity.setSubId(subId);
                entity.setApproveStatus(0L);
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        entity.setSystemName(cellValue);
                    } else if (j == 1) {
                        if (cellValue.length() > 3) {
                            entity.setSamplingDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 2) {
                        entity.setSampleName(cellValue);
                    } else if (j == 3) {
                        entity.setDewPointValue(cellValue);
                    }else if (j == 4) {
                        entity.setConfirm1(cellValue);
                    }else if (j == 5) {
                        entity.setConfirm2(cellValue);
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TPssrNitrogen t : list
        ) {
            failNum++;
            try {
                this.add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success("导入成功行数：" + String.valueOf(successNumber));
    }

    /**
     * 查询系统氮气置换列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrNitrogen tPssrNitrogen) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrNitrogen.getSubId());
            if (approve != null) {
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                TaskService taskService = processEngine.getTaskService();
                Task task = processEngine.getTaskService()//获取任务service
                        .createTaskQuery()//创建查询对象
                        .taskAssignee(getUserId().toString())
                        .processInstanceId(approve.getProcessId()).singleResult();
                if (task != null) {
                    if (task.getName().equals("确认人1")) {
                        tPssrNitrogen.setConfirm1(getUserId().toString());
                    } else if (task.getName().equals("确认人2")) {
                        tPssrNitrogen.setConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}", e.getMessage());
        }
        startPage();
        List<TPssrNitrogen> list = tPssrNitrogenService.selectTPssrNitrogenList(tPssrNitrogen);
        list.forEach(item -> {
            
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
            if (item.getApproveStatus() != 2)
                item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "dqzh"));
        });
        return getDataTable(list);
    }

    /**
     * 导出系统氮气置换列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:export')")
    @Log(title = "系统氮气置换", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrNitrogen tPssrNitrogen) {
        List<TPssrNitrogen> list = tPssrNitrogenService.selectTPssrNitrogenList(tPssrNitrogen);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrNitrogen> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/dqzh.xlsx"; // 模板文件
            InputStream is = null;
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XSSFWorkbook wb = null;
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);

            //填充数据
            int rowIndex = 3;
            int num = 1;

            Row originalRow = sheet.getRow(3);
            Cell originalcell = originalRow.getCell(0);
            // 获取单元格样式
            CellStyle originalStyle = originalcell.getCellStyle();

            for (TPssrNitrogen t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getSystemName());
                row.createCell(2).setCellValue(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM, t.getSamplingDate()));
                row.createCell(3).setCellValue(t.getSampleName());
                row.createCell(4).setCellValue(t.getOxygen());
                row.createCell(5).setCellValue(t.getDewPoint());
                row.createCell(6).setCellValue(t.getDewPointValue());
                row.createCell(7).setCellValue(t.getStandard());
                row.createCell(8);
                row.createCell(9);
                try {
                    SysUser sysUser = sysUserService.selectUserById(Long.valueOf(t.getConfirm1()));
                    SysUser sysUser2 = sysUserService.selectUserById(Long.valueOf(t.getConfirm2()));
                    String confirm1 = sysUser.getSignUrl();
                    String confirm2 = sysUser2.getSignUrl();
                    ExcelUtils.insertPicture(wb, sheet, confirm1, row.getRowNum(), 8, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 9, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(10).setCellValue(DateUtils.dateTime(t.getConfirmationDate()));
                row.createCell(11).setCellValue(t.getRemarks());


                //渲染样式
                for (int i = 0; i < 12; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_12_氮气置换" + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

    /**
     * 获取系统氮气置换详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrNitrogen item = tPssrNitrogenService.selectTPssrNitrogenById(id);
        
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
        if (item.getApproveStatus() != 2)
            item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "dqzh"));
        return AjaxResult.success(item);
    }

    /**
     * 新增系统氮气置换
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:add')")
    @Log(title = "系统氮气置换", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrNitrogen tPssrNitrogen) {
        if (StringUtils.isNotEmpty(tPssrNitrogen.getConfirm1()) && tPssrNitrogen.getConfirm1().equals(tPssrNitrogen.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrNitrogen.setApproveStatus(0L);
        // 氧气空 露点不空
        if ((StringUtils.isEmpty(tPssrNitrogen.getOxygen())&&StringUtils.isEmpty(tPssrNitrogen.getoxygenValue()))&&
                (StringUtils.isNotEmpty(tPssrNitrogen.getDewPoint())&&StringUtils.isNotEmpty(tPssrNitrogen.getDewPointValue()))){
            tPssrNitrogen.setOxygen("NA");
            tPssrNitrogen.setoxygenValue("NA");
        }else if ((StringUtils.isNotEmpty(tPssrNitrogen.getOxygen())&&StringUtils.isNotEmpty(tPssrNitrogen.getoxygenValue()))&&
                (StringUtils.isEmpty(tPssrNitrogen.getDewPoint())&&StringUtils.isEmpty(tPssrNitrogen.getDewPointValue()))){
            tPssrNitrogen.setDewPointValue("NA");
            tPssrNitrogen.setDewPoint("NA");
        }
        this.verifySatndard(tPssrNitrogen);
        return toAjax(tPssrNitrogenService.insertTPssrNitrogen(tPssrNitrogen));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrNitrogen item) {
        TPssrNitrogen entity = new TPssrNitrogen();
        entity.setSubId(item.getSubId());
        entity.setSystemName(item.getSystemName());
        List<TPssrNitrogen> list = tPssrNitrogenService.selectTPssrNitrogenList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrNitrogenService.updateTPssrNitrogen(item);
        } else {
            return tPssrNitrogenService.insertTPssrNitrogen(item);
        }
    }

    /**
     * 验证氧气/露点是否合格
     *
     * @param tPssrNitrogen
     */
    private void verifySatndard(TPssrNitrogen tPssrNitrogen) {
        // 当氧气不为NA或空时，取值
        String oxygen = (StringUtils.isEmpty(tPssrNitrogen.getOxygen())||tPssrNitrogen.getOxygen().equals("NA"))?null:tPssrNitrogen.getOxygen();
        // 当氧气标准值不为NA或空时，取值
        String oxygenValue = (StringUtils.isEmpty(tPssrNitrogen.getoxygenValue())||tPssrNitrogen.getoxygenValue().equals("NA"))?null:tPssrNitrogen.getoxygenValue();
        //当氧气标准值为空并且不为NA时
        if(StringUtils.isEmpty(oxygenValue)&&StringUtils.isNotEmpty(tPssrNitrogen.getoxygenValue())&&!tPssrNitrogen.getoxygenValue().equals("NA")){
            oxygenValue="0.2";
        }
        String dewPoint = (StringUtils.isEmpty(tPssrNitrogen.getDewPoint())||tPssrNitrogen.getDewPoint().equals("NA"))?null:tPssrNitrogen.getDewPoint();
        String dewPointValue = (StringUtils.isEmpty(tPssrNitrogen.getDewPointValue())||tPssrNitrogen.getDewPointValue().equals("NA"))?null:tPssrNitrogen.getDewPointValue();
        String standard = "";
        // 氧气不为空并且露点不为空并且露点标准不为空的时候
        if (StringUtils.isNotEmpty(oxygen) &&StringUtils.isNotEmpty(oxygenValue) && StringUtils.isNotEmpty(dewPoint) && StringUtils.isNotEmpty(dewPointValue)) {//判断氧气+露点
            if (new BigDecimal(oxygen).compareTo(new BigDecimal(oxygenValue)) == -1
                    && new BigDecimal(dewPoint).compareTo(new BigDecimal(dewPointValue)) == -1) {
                standard = "是";
            } else {
                standard = "否";
            }
        } else if (StringUtils.isNotEmpty(oxygen) &&StringUtils.isNotEmpty(oxygenValue) && StringUtils.isEmpty(dewPoint) && StringUtils.isEmpty(dewPointValue)) {//判断氧气
            //氧气不为空 露点值为空 标准也为空
            if (new BigDecimal(oxygen).compareTo(new BigDecimal(oxygenValue)) == -1) {
                standard = "是";
            } else {
                standard = "否";
            }
        } else if (StringUtils.isEmpty(oxygen) && StringUtils.isNotEmpty(dewPointValue)) {//判断氧气
            //氧气为空 标准不为空
            if (StringUtils.isEmpty(dewPoint)) {
                standard = "否";
            } else {
                if (new BigDecimal(dewPoint).compareTo(new BigDecimal(dewPointValue)) == -1) {
                    standard = "是";
                } else {
                    standard = "否";
                }
            }
        } else {
            standard = "否";
        }
        tPssrNitrogen.setStandard(standard);
    }

    /**
     * 修改系统氮气置换
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:edit')")
    @Log(title = "系统氮气置换", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrNitrogen tPssrNitrogen) {
        // 氧气空 露点不空
        if ((StringUtils.isEmpty(tPssrNitrogen.getOxygen())&&StringUtils.isEmpty(tPssrNitrogen.getoxygenValue()))&&
                (StringUtils.isNotEmpty(tPssrNitrogen.getDewPoint())&&StringUtils.isNotEmpty(tPssrNitrogen.getDewPointValue())
                        &&!tPssrNitrogen.getDewPoint().equals("NA")&&!tPssrNitrogen.getDewPointValue().equals("NA"))){
            tPssrNitrogen.setOxygen("NA");
            tPssrNitrogen.setoxygenValue("NA");
        }else if ((StringUtils.isNotEmpty(tPssrNitrogen.getOxygen())&&StringUtils.isNotEmpty(tPssrNitrogen.getoxygenValue()))&&
                (StringUtils.isEmpty(tPssrNitrogen.getDewPoint())&&StringUtils.isEmpty(tPssrNitrogen.getDewPointValue()))){
            tPssrNitrogen.setDewPointValue("NA");
            tPssrNitrogen.setDewPoint("NA");
        }else if ((StringUtils.isNotEmpty(tPssrNitrogen.getOxygen())&&StringUtils.isEmpty(tPssrNitrogen.getoxygenValue()))){
            tPssrNitrogen.setoxygenValue("0.2");
        }
        TPssrNitrogen entity = tPssrNitrogenService.selectTPssrNitrogenById(tPssrNitrogen.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrNitrogen.getConfirm1().equals(tPssrNitrogen.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrNitrogen.getFileIds(), "dqzh", tPssrNitrogen.getId(), tPssrNitrogen.getSubId());
        this.verifySatndard(tPssrNitrogen);
        return toAjax(tPssrNitrogenService.updateTPssrNitrogen(tPssrNitrogen));
    }


    /**
     * 修改系统氮气置换
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:edit')")
    @Log(title = "系统氮气置换", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrNitrogen tPssrNitrogen) {
        if (tPssrNitrogen.getConfirm1().equals(tPssrNitrogen.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrNitrogenMapper.updateTPssrNitrogenByIds(tPssrNitrogen));
    }

    /**
     * 删除系统氮气置换
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:remove')")
    @Log(title = "系统氮气置换", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrNitrogenService.deleteTPssrNitrogenByIds(ids));
    }


    /**
     * 确认氮气置换
     */
    @PreAuthorize("@ss.hasPermi('pssr:nitrogen:edit')")
    @Log(title = "氮气置换确认", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmNitrogen")
    public AjaxResult confirmNitrogen(@RequestBody TPssrNitrogen tPssrNitrogen) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrNitrogen lock = new TPssrNitrogen();
        if (tPssrNitrogen.getTaskType() == 4) {
            //确认人1确认
            queryStatus = 1;
            approveStatus = 3;
            date = new Date();
            lock.setConfirm1(getUserId().toString());
        } else if (tPssrNitrogen.getTaskType() == 5) {
            //确认人2确认
            queryStatus = 3;
            approveStatus = 2;
            date = new Date();
            lock.setConfirm2(getUserId().toString());
        }
        // 修改状态
        if (tPssrNitrogen.getIds() != null && tPssrNitrogen.getIds().length > 0) {
            for (Long id : tPssrNitrogen.getIds()) {
                TPssrNitrogen item = tPssrNitrogenService.selectTPssrNitrogenById(id);
                if (item.getStandard().equals("否")) {
                    return AjaxResult.error("氮气置换不合格，请重新确认！");
                }
                item.setApproveStatus(approveStatus);
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                tPssrNitrogenService.updateTPssrNitrogen(item);
            }
        } else {
            lock.setSubId(tPssrNitrogen.getSubId());
            lock.setApproveStatus(queryStatus);
            for (TPssrNitrogen item : tPssrNitrogenService.selectTPssrNitrogenList(lock)) {
                if (item.getStandard().equals("否")) {
                    return AjaxResult.error("氮气置换不合格，请重新确认！");
                }
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                item.setApproveStatus(approveStatus);
                tPssrNitrogenService.updateTPssrNitrogen(item);
            }
        }
        //查询当前待审批的确认人
        TPssrNitrogen entity = new TPssrNitrogen();
        entity.setSubId(tPssrNitrogen.getSubId());
        entity.setApproveStatus(queryStatus);
        for (TPssrNitrogen item : tPssrNitrogenService.selectTPssrNitrogenList(entity)) {
            if (tPssrNitrogen.getTaskType() == 4) {
                if (item.getConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrNitrogen.getTaskType() == 5) {
                if (item.getConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

        //无待审批任务结束当前用户流程

        // 因为流程关系所以approve一定会有且只有一条数据
        TPssrApprove tPssrApprove = tPssrApproveService.selectTPssrApproveBySubId(tPssrNitrogen.getSubId());
        TPssrApproveController.handleConfirmApprove(tPssrApprove, getUserId().toString());
        return AjaxResult.success();

    }

    /**
     * 驳回氮气置换
     */
    @PutMapping("/turnDownNitrogen")
    @Log(title = "氮气置换驳回", businessType = BusinessType.UPDATE)
    public AjaxResult turnDownNitrogen(@RequestBody List<TPssrNitrogen> tPssrNitrogen) {
        if (CollectionUtils.isNotEmpty(tPssrNitrogen)) {
            String userId = getUserId().toString();
            Long subId = tPssrNitrogen.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrNitrogen item : tPssrNitrogen) {
                TPssrNitrogen blind = new TPssrNitrogen();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrNitrogenService.updateTPssrNitrogen(blind);
                // 新增驳回原因数据
                TPssrTurndown turndown = new TPssrTurndown();
                turndown.setForShort(forShort);
                turndown.setSubId(item.getSubId());
                turndown.setItemId(item.getId());
                turndown.setReason(item.getReason());
                turndown.setCreatedate(new Date());
                turndown.setCreaterCode(getUserId().toString());
                tPssrTurndownService.insertTPssrTurndown(turndown);
            }
            // 查询当前流程
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(subId);

            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            TaskService taskService = processEngine.getTaskService();
            Task task = processEngine.getTaskService()//获取任务service
                    .createTaskQuery()//创建查询对象
                    .taskAssignee(userId)
                    .processInstanceId(approve.getProcessId()).singleResult();
            String taskId = task.getId();

            // 驳回 查询所有待审批的人员
            TPssrNitrogen blind = new TPssrNitrogen();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> confirm1 = new HashSet<>();
            Set<String> confirm2 = new HashSet<>();
            for (TPssrNitrogen item : tPssrNitrogenService.selectTPssrNitrogenList(blind)) {

                // 确认人1
                confirm1.add(item.getConfirm1());

                // 确认人2
                confirm2.add(item.getConfirm2());
            }


            //处理流程节点
            Map<String, Object> param = new HashMap<>();
            param.put("condition", 1);
            param.put("confirmUsers1", new ArrayList<>(confirm1));
            param.put("confirmUsers2", new ArrayList<>(confirm2));
            //认领任务
            processEngine.getTaskService().claim(taskId, userId);
            taskService.addComment(taskId, approve.getProcessId(), "驳回");
            taskService.complete(taskId, param);

            // 修改审批表和sub表
            approve.setApproveStatus(1L);
            approve.setUpdatedate(new Date());
            approve.setUpdaterCode(getUserId().toString());
            tPssrApproveService.updateTPssrApprove(approve);

            TPssrSubcontent subcontent = new TPssrSubcontent();
            subcontent.setId(approve.getSubId());
            subcontent.setApproveStatus(1L);
            subcontent.setUpdatedate(new Date());
            subcontent.setUpdaterCode(getUserId().toString());
            tPssrSubcontentService.updateTPssrSubcontent(subcontent);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}
