package com.ruoyi.project.pssr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.domain.vo.TPssrCleaningVo;
import com.ruoyi.project.pssr.mapper.TPssrCleaningMapper;
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.ss.util.CellRangeAddress;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * 设备清洁Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/cleaning")
public class TPssrCleaningController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;
    @Resource
    private TPssrCleaningMapper tPssrCleaningMapper;
    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrCleaningService tPssrCleaningService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

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

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning: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<TPssrCleaning> list = new ArrayList<TPssrCleaning>();
        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();
                TPssrCleaning entity = new TPssrCleaning();
                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.setUnit(cellValue);
                    } else if (j == 1) {
                        entity.setDevNo(cellValue);
                    } else if (j == 2) {
                        entity.setDevType(cellValue);
                    }else if (j == 3) {
                        entity.setConfirm1(cellValue);
                    }else if (j == 4) {
                        entity.setConfirm2(cellValue);
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TPssrCleaning 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:cleaning:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrCleaning tPssrCleaning) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrCleaning.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")){
                        tPssrCleaning.setConfirm1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrCleaning.setConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrCleaning> list = tPssrCleaningService.selectTPssrCleaningList(tPssrCleaning);
        list.forEach(item -> {
            
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
            item.setContentList(JSON.parseArray(item.getCheckContent(), TPssrCleaningVo.class));
            if (item.getApproveStatus() != 2)
                item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "sbqjd"));
        });
        return getDataTable(list);
    }

    /**
     * 导出设备清洁列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:export')")
    @Log(title = "设备清洁", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrCleaning tPssrCleaning) {
        List<TPssrCleaning> list = tPssrCleaningService.selectTPssrCleaningList(tPssrCleaning);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrCleaning> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/sbqjd.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 (TPssrCleaning t : list) {
                // 处理检查内容JSON
                String checkContent = t.getCheckContent();
                JSONArray objects = JSONObject.parseArray(checkContent);
                int i = 0;
                int startRow = 0;
                for (Object object : objects) {
                    JSONObject jsonObject = JSONObject.parseObject(object.toString());
                    String num1 = jsonObject.get("num").toString();
                    String content = jsonObject.get("content").toString();
                    String result = jsonObject.get("result").toString();
                    if (i == 0) {
                        startRow = rowIndex;
                        Row row = sheet.createRow(rowIndex);
                        row.setHeight((short) 800);
                        row.createCell(0).setCellValue(t.getUnit());
                        row.createCell(1).setCellValue(t.getDevType());
                        row.createCell(2).setCellValue(t.getDevNo());
                        row.createCell(3).setCellValue(num1);
                        row.createCell(4).setCellValue(content);
                        row.createCell(5).setCellValue(result);
                        row.createCell(6);
                        row.createCell(7);
                        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(), 6, 1, 1);
                            ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 7, 1, 1);
                        } catch (NumberFormatException e) {
                            throw new RuntimeException(e);
                        }
                        row.createCell(8).setCellValue(DateUtils.dateTime(t.getConfirmationDate()));
                        row.createCell(9).setCellValue(t.getRemarks());
                        //渲染样式
                        for (int j = 0; j < 10; j++) {
                            row.getCell(j).setCellStyle(originalStyle);
                        }
                        num++;
                        rowIndex++;
                    } else {
                        Row row = sheet.createRow(rowIndex);
                        row.setHeight((short) 800);
                        row.createCell(0).setCellValue("");
                        row.createCell(1).setCellValue("");
                        row.createCell(2).setCellValue("");
                        row.createCell(3).setCellValue(num1);
                        row.createCell(4).setCellValue(content);
                        row.createCell(5).setCellValue(result);
                        row.createCell(6).setCellValue("");
                        row.createCell(7).setCellValue("");
                        row.createCell(8).setCellValue("");
                        row.createCell(9).setCellValue("");
                        //渲染样式
                        for (int j = 0; j < 10; j++) {
                            row.getCell(j).setCellStyle(originalStyle);
                        }
                        num++;
                        rowIndex++;
                    }
                    i++;
                }
                // 合并单元格
                CellRangeAddress cellRangeAddress1 = new CellRangeAddress(startRow, rowIndex - 1, 0, 0);
                CellRangeAddress cellRangeAddress2 = new CellRangeAddress(startRow, rowIndex - 1, 1, 1);
                CellRangeAddress cellRangeAddress3 = new CellRangeAddress(startRow, rowIndex - 1, 2, 2);
                CellRangeAddress cellRangeAddress4 = new CellRangeAddress(startRow, rowIndex - 1, 6, 6);
                CellRangeAddress cellRangeAddress5 = new CellRangeAddress(startRow, rowIndex - 1, 7, 7);
                CellRangeAddress cellRangeAddress6 = new CellRangeAddress(startRow, rowIndex - 1, 8, 8);
                CellRangeAddress cellRangeAddress7 = new CellRangeAddress(startRow, rowIndex - 1, 9, 9);
                sheet.addMergedRegion(cellRangeAddress1);
                sheet.addMergedRegion(cellRangeAddress2);
                sheet.addMergedRegion(cellRangeAddress3);
                sheet.addMergedRegion(cellRangeAddress4);
                sheet.addMergedRegion(cellRangeAddress5);
                sheet.addMergedRegion(cellRangeAddress6);
                sheet.addMergedRegion(cellRangeAddress7);
            }
            filename = "PSSR_07_设备清洁" + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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

    /**
     * 获取设备清洁详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrCleaning item = tPssrCleaningService.selectTPssrCleaningById(id);
        item.setContentList(JSON.parseArray(item.getCheckContent(), TPssrCleaningVo.class));
        
            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(), "sbqjd"));
        return AjaxResult.success(item);
    }

    /**
     * 新增设备清洁
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:add')")
    @Log(title = "设备清洁", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrCleaning tPssrCleaning) {
        if (StringUtils.isNotEmpty(tPssrCleaning.getConfirm1()) && tPssrCleaning.getConfirm1().equals(tPssrCleaning.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrCleaning.setCheckContent(JSON.toJSONString(genList(tPssrCleaning.getDevType())));
        tPssrCleaning.setApproveStatus(0L);
        return toAjax(tPssrCleaningService.insertTPssrCleaning(tPssrCleaning));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrCleaning item) {
        TPssrCleaning entity = new TPssrCleaning();
        entity.setSubId(item.getSubId());
        entity.setDevNo(item.getDevNo());
        List<TPssrCleaning> list = tPssrCleaningService.selectTPssrCleaningList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrCleaningService.updateTPssrCleaning(item);
        } else {
            return tPssrCleaningService.insertTPssrCleaning(item);
        }
    }

    private List<TPssrCleaningVo> genList(String devType) {
        List<TPssrCleaningVo> list = new ArrayList<>();
        switch (devType) {
            case "开工锅炉":
                list.add(new TPssrCleaningVo(1, "炉膛内壁衬里完整，无脱落。", "✔"));
                list.add(new TPssrCleaningVo(2, "炉膛内烧嘴清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "炉膛内炉管外壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(4, "水包清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(5, "汽包清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(6, "省煤器清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(7, "通风道清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(8, "烟道清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(9, "炉膛内部无遗留其他不相关的物件。", "✔"));
                break;
            case "裂解炉":
                list.add(new TPssrCleaningVo(1, "炉膛内壁衬里完整，无脱落。", "✔"));
                list.add(new TPssrCleaningVo(2, "炉膛内炉管外壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "炉膛内烧嘴清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(4, "炉膛内部管口清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(5, "炉膛内部无遗留其他不相关的物件。", "✔"));
                break;
            case "塔":
                list.add(new TPssrCleaningVo(1, "塔内壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(2, "塔板清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "降液槽清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(4, "塔内部管口清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(5, "塔内部无遗留其他不相关的物件。", "✔"));
                break;
            case "罐":
                list.add(new TPssrCleaningVo(1, "罐内壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(2, "罐内部管口清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "罐内部无遗留其他不相关的物件。", "✔"));
                break;
            case "反应器":
            case "干燥器":
                list.add(new TPssrCleaningVo(1, "器内壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(2, "器内部管口清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "器内部无遗留其他不相关的物件。", "✔"));
                break;
            case "换热器":
                list.add(new TPssrCleaningVo(1, "管束内壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(2, "管箱内部清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "管束外壁清洁干净，无残留物", "✔"));
                list.add(new TPssrCleaningVo(4, "筒体内壁清洁干净，无残留物", "✔"));
                break;
            case "冷箱":
                list.add(new TPssrCleaningVo(1, "箱内壁清洁干净，无残留物。", "✔"));
                list.add(new TPssrCleaningVo(2, "箱内部管口清洁干净,无残留物。", "✔"));
                list.add(new TPssrCleaningVo(3, "箱内部无遗留其他不相关的物件。", "✔"));
                break;
        }
        return list;
    }

    /**
     * 修改设备清洁
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:edit')")
    @Log(title = "设备清洁", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrCleaning tPssrCleaning) {
        TPssrCleaning entity = tPssrCleaningService.selectTPssrCleaningById(tPssrCleaning.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrCleaning.getConfirm1().equals(tPssrCleaning.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        TPssrCleaning cleaning = tPssrCleaningService.selectTPssrCleaningById(tPssrCleaning.getId());
        if (StringUtils.isEmpty(cleaning.getCheckContent())||"[]".equals(cleaning.getCheckContent())) {
            tPssrCleaning.setCheckContent(JSON.toJSONString(genList(tPssrCleaning.getDevType())));
        } else {
            tPssrCleaning.setCheckContent(JSON.toJSONString(tPssrCleaning.getContentList()));
        }
        tPssrFileService.updateFileRelevance(tPssrCleaning.getFileIds(), "sbqjd", tPssrCleaning.getId(), tPssrCleaning.getSubId());
        return toAjax(tPssrCleaningService.updateTPssrCleaning(tPssrCleaning));
    }

    /**
     * 修改设备清洁
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:edit')")
    @Log(title = "设备清洁", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrCleaning tPssrCleaning) {
        if (tPssrCleaning.getConfirm1().equals(tPssrCleaning.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrCleaningMapper.updateTPssrCleaningByIds(tPssrCleaning));
    }

    /**
     * 删除设备清洁
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:remove')")
    @Log(title = "设备清洁", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrCleaningService.deleteTPssrCleaningByIds(ids));
    }

    /**
     * 确认设备清洁
     */
    @PreAuthorize("@ss.hasPermi('pssr:cleaning:edit')")
    @Log(title = "设备清洁", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmCleaning")
    public AjaxResult confirmCleaning(@RequestBody TPssrCleaning tPssrCleaning) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrCleaning lock = new TPssrCleaning();
        if (tPssrCleaning.getTaskType() == 4) {
            //拆锁确认
            queryStatus = 1;
            approveStatus = 3;
            date = new Date();
            lock.setConfirm1(getUserId().toString());
        } else if (tPssrCleaning.getTaskType() == 5) {
            //上锁确认
            queryStatus = 3;
            approveStatus = 2;
            date = new Date();
            lock.setConfirm2(getUserId().toString());
        }
        // 修改状态
        if (tPssrCleaning.getIds() != null && tPssrCleaning.getIds().length > 0) {
            for (Long id : tPssrCleaning.getIds()) {
                TPssrCleaning item = tPssrCleaningService.selectTPssrCleaningById(id);
                item.setApproveStatus(approveStatus);
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                tPssrCleaningService.updateTPssrCleaning(item);
            }
        } else {
            lock.setSubId(tPssrCleaning.getSubId());
            lock.setApproveStatus(queryStatus);
            for (TPssrCleaning item : tPssrCleaningService.selectTPssrCleaningList(lock)) {
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                item.setApproveStatus(approveStatus);
                tPssrCleaningService.updateTPssrCleaning(item);
            }
        }
        //查询当前待审批的确认人
        TPssrCleaning entity = new TPssrCleaning();
        entity.setSubId(tPssrCleaning.getSubId());
        entity.setApproveStatus(queryStatus);
        for (TPssrCleaning item : tPssrCleaningService.selectTPssrCleaningList(entity)) {
            if (tPssrCleaning.getTaskType() == 4) {
                if (item.getConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrCleaning.getTaskType() == 5) {
                if (item.getConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

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

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

    }

    /**
     * 驳回设备清洁
     */
    @PutMapping("/turnDownCleaning")
    public AjaxResult turnDownCleaning(@RequestBody List<TPssrCleaning> tPssrCleaning) {
        if (CollectionUtils.isNotEmpty(tPssrCleaning)) {
            String userId = getUserId().toString();
            Long subId = tPssrCleaning.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrCleaning item : tPssrCleaning) {
                TPssrCleaning blind = new TPssrCleaning();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrCleaningService.updateTPssrCleaning(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();

            // 驳回 查询所有待审批的人员
            TPssrCleaning blind = new TPssrCleaning();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> installer = new HashSet<>();
            Set<String> remover = new HashSet<>();
            for (TPssrCleaning item : tPssrCleaningService.selectTPssrCleaningList(blind)) {

                // 安装人员
                installer.add(item.getConfirm1());

                //拆除人员
                remover.add(item.getConfirm2());
            }


            //处理流程节点
            Map<String, Object> param = new HashMap<>();
            param.put("condition", 1);
            param.put("confirmUsers1", new ArrayList<>(installer));
            param.put("confirmUsers2", new ArrayList<>(remover));
            //认领任务
            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();
    }
}
