package com.sundot.airport.check.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sundot.airport.check.domain.CheckProjectItem;
import com.sundot.airport.check.domain.CheckUser;
import com.sundot.airport.common.core.domain.ApprovalWorkflowBatchDto;
import com.sundot.airport.check.service.ICheckProjectItemService;
import com.sundot.airport.check.service.ICheckUserService;
import com.sundot.airport.common.constant.Constants;
import com.sundot.airport.common.core.redis.RedisSerialGenerator;
import com.sundot.airport.common.domain.BaseAttachment;
import com.sundot.airport.common.enums.BaseAttachmentSourceTypeEnum;
import com.sundot.airport.common.enums.CheckCorrectionStatusEnum;
import com.sundot.airport.common.enums.CheckLevelEnum;
import com.sundot.airport.common.enums.CheckProjectItemTypeEnum;
import com.sundot.airport.common.enums.CheckUserTypeEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.service.IBaseAttachmentService;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.system.domain.approval.ApprovalInstance;
import com.sundot.airport.system.domain.approval.ApprovalTask;
import com.sundot.airport.system.mapper.approval.ApprovalInstanceMapper;
import com.sundot.airport.system.mapper.approval.ApprovalTaskMapper;
import com.sundot.airport.system.service.approval.IApprovalEngineService;
import com.sundot.airport.system.service.approval.ICheckApprovalService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.check.mapper.CheckCorrectionMapper;
import com.sundot.airport.check.domain.CheckCorrection;
import com.sundot.airport.check.service.ICheckCorrectionService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 问题整改Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-08
 */
@Slf4j
@Service
public class CheckCorrectionServiceImpl extends ServiceImpl<CheckCorrectionMapper, CheckCorrection> implements ICheckCorrectionService {
    @Autowired
    private CheckCorrectionMapper checkCorrectionMapper;
    @Autowired
    private ICheckProjectItemService checkProjectItemService;
    @Autowired
    private ICheckUserService checkUserService;
    @Autowired
    private RedisSerialGenerator redisSerialGenerator;
    @Autowired
    private IBaseAttachmentService baseAttachmentService;
    @Autowired
    private ICheckApprovalService checkApprovalService;
    @Autowired
    private IApprovalEngineService approvalEngineService;
    @Autowired
    private ApprovalTaskMapper taskMapper;
    @Autowired
    private ApprovalInstanceMapper instanceMapper;

    /**
     * 查询问题整改
     *
     * @param id 问题整改主键
     * @return 问题整改
     */
    @Override
    public CheckCorrection selectCheckCorrectionById(Long id) {
        CheckCorrection result = checkCorrectionMapper.selectCheckCorrectionById(id);
        if (ObjUtil.isNull(result)) {
            throw new ServiceException("根据id[" + id + "]未查询到问题整改单");
        }
        //检查项明细列表
        CheckProjectItem checkProjectItem = new CheckProjectItem();
        checkProjectItem.setType(CheckProjectItemTypeEnum.CHECK_CORRECTION.getCode());
        checkProjectItem.setSourceId(result.getId());
        List<CheckProjectItem> checkProjectItemList = checkProjectItemService.selectCheckProjectItemList(checkProjectItem);
        LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckUser::getType, CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getCode())
                .in(CheckUser::getSourceId, checkProjectItemList.stream().map(CheckProjectItem::getId).toArray());
        List<CheckUser> checkUserListTemp = checkUserService.getBaseMapper().selectList(wrapper);
        Map<Long, List<CheckUser>> checkUserListMap = checkUserListTemp.stream().collect(Collectors.groupingBy(CheckUser::getSourceId));
        checkProjectItemList.forEach(item -> {
            item.setCheckUserList(checkUserListMap.get(item.getId()));
        });
        result.setCheckProjectItemList(checkProjectItemList);
        //附件列表
        BaseAttachment baseAttachment = new BaseAttachment();
        baseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getCode());
        baseAttachment.setSourceId(result.getId());
        List<BaseAttachment> baseAttachmentList = baseAttachmentService.selectBaseAttachmentList(baseAttachment);
        result.setBaseAttachmentList(baseAttachmentList);
        //检查单附件列表
        BaseAttachment checkRecordBaseAttachment = new BaseAttachment();
        checkRecordBaseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION_RECORD.getCode());
        checkRecordBaseAttachment.setSourceId(result.getId());
        List<BaseAttachment> checkRecordBaseAttachmentList = baseAttachmentService.selectBaseAttachmentList(checkRecordBaseAttachment);
        result.setCheckRecordBaseAttachmentList(checkRecordBaseAttachmentList);
        return result;
    }

    /**
     * 查询问题整改列表
     *
     * @param checkCorrection 问题整改
     * @return 问题整改
     */
    @Override
    public List<CheckCorrection> selectCheckCorrectionList(CheckCorrection checkCorrection) {
        return checkCorrectionMapper.selectCheckCorrectionList(checkCorrection);
    }

    /**
     * 新增问题整改
     *
     * @param checkCorrection 问题整改
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertCheckCorrection(CheckCorrection checkCorrection) {
        //整改单
        checkCorrection.setCreateTime(DateUtils.getNowDate());
        checkCorrection.setCorrectionCode(redisSerialGenerator.generate(Constants.CHECK_CORRECTION_PREFIX));
        checkCorrection.setStatus(CheckCorrectionStatusEnum.UNDER_RECTIFICATION.getCode());
        checkCorrection.setStatusDesc(CheckCorrectionStatusEnum.UNDER_RECTIFICATION.getDesc());
        int result = checkCorrectionMapper.insertCheckCorrection(checkCorrection);
        //检查项明细列表
        if (CollUtil.isNotEmpty(checkCorrection.getCheckProjectItemList())) {
            checkCorrection.getCheckProjectItemList().forEach(checkProjectItem -> {
                checkProjectItem.setCreateBy(checkCorrection.getCreateBy());
                checkProjectItem.setCreateTime(DateUtils.getNowDate());
                checkProjectItem.setType(CheckProjectItemTypeEnum.CHECK_CORRECTION.getCode());
                checkProjectItem.setTypeDesc(CheckProjectItemTypeEnum.CHECK_CORRECTION.getInfo());
                checkProjectItem.setSourceId(checkCorrection.getId());
                checkProjectItemService.insertCheckProjectItem(checkProjectItem);
                if (CollUtil.isNotEmpty(checkProjectItem.getCheckUserList())) {
                    checkProjectItem.getCheckUserList().forEach(checkUser -> {
                        checkUser.setCreateBy(checkProjectItem.getCreateBy());
                        checkUser.setCreateTime(DateUtils.getNowDate());
                        checkUser.setType(CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getCode());
                        checkUser.setTypeDesc(CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getInfo());
                        checkUser.setSourceId(checkProjectItem.getId());
                    });
                    checkUserService.saveBatch(checkProjectItem.getCheckUserList());
                }
            });
        }
        //附件列表
        if (CollUtil.isNotEmpty(checkCorrection.getBaseAttachmentList())) {
            checkCorrection.getBaseAttachmentList().forEach(baseAttachment -> {
                baseAttachment.setCreateBy(checkCorrection.getCreateBy());
                baseAttachment.setCreateTime(DateUtils.getNowDate());
                baseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getCode());
                baseAttachment.setSourceTypeName(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getInfo());
                baseAttachment.setSourceId(checkCorrection.getId());
            });
            baseAttachmentService.saveBatch(checkCorrection.getBaseAttachmentList());
        }
        //检查单附件列表
        if (CollUtil.isNotEmpty(checkCorrection.getCheckRecordBaseAttachmentList())) {
            checkCorrection.getCheckRecordBaseAttachmentList().forEach(baseAttachment -> {
                baseAttachment.setCreateBy(checkCorrection.getCreateBy());
                baseAttachment.setCreateTime(DateUtils.getNowDate());
                baseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION_RECORD.getCode());
                baseAttachment.setSourceTypeName(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION_RECORD.getInfo());
                baseAttachment.setSourceId(checkCorrection.getId());
            });
            baseAttachmentService.saveBatch(checkCorrection.getCheckRecordBaseAttachmentList());
        }
        //开始审批流
        startApproval(checkCorrection);
        return result;
    }

    /**
     * 修改问题整改
     *
     * @param checkCorrection 问题整改
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateCheckCorrection(CheckCorrection checkCorrection) {
        checkCorrection.setUpdateTime(DateUtils.getNowDate());
        int result = checkCorrectionMapper.updateCheckCorrection(checkCorrection);
        //检查项明细列表先删除后新增
        CheckProjectItem checkProjectItemQuery = new CheckProjectItem();
        checkProjectItemQuery.setType(CheckProjectItemTypeEnum.CHECK_CORRECTION.getCode());
        checkProjectItemQuery.setSourceId(checkCorrection.getId());
        List<CheckProjectItem> checkProjectItemListOld = checkProjectItemService.selectCheckProjectItemList(checkProjectItemQuery);
        checkProjectItemService.removeBatchByIds(checkProjectItemListOld);
        LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckUser::getType, CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getCode())
                .in(CheckUser::getSourceId, checkProjectItemListOld.stream().map(CheckProjectItem::getId).toArray());
        List<CheckUser> checkUserListOld = checkUserService.getBaseMapper().selectList(wrapper);
        checkUserService.removeBatchByIds(checkUserListOld);
        if (CollUtil.isNotEmpty(checkCorrection.getCheckProjectItemList())) {
            checkCorrection.getCheckProjectItemList().forEach(checkProjectItem -> {
                checkProjectItem.setUpdateTime(DateUtils.getNowDate());
                checkProjectItem.setType(CheckProjectItemTypeEnum.CHECK_CORRECTION.getCode());
                checkProjectItem.setTypeDesc(CheckProjectItemTypeEnum.CHECK_CORRECTION.getInfo());
                checkProjectItem.setSourceId(checkCorrection.getId());
                checkProjectItemService.save(checkProjectItem);
                if (CollUtil.isNotEmpty(checkProjectItem.getCheckUserList())) {
                    checkProjectItem.getCheckUserList().forEach(checkUser -> {
                        checkUser.setId(null);
                        checkUser.setCreateBy(checkProjectItem.getCreateBy());
                        checkUser.setCreateTime(DateUtils.getNowDate());
                        checkUser.setType(CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getCode());
                        checkUser.setTypeDesc(CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getInfo());
                        checkUser.setSourceId(checkProjectItem.getId());
                    });
                    checkUserService.saveBatch(checkProjectItem.getCheckUserList());
                }
            });
        }
        //附件列表先删除后新增
        BaseAttachment baseAttachmentQuery = new BaseAttachment();
        baseAttachmentQuery.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getCode());
        baseAttachmentQuery.setSourceId(checkCorrection.getId());
        List<BaseAttachment> baseAttachmentListOld = baseAttachmentService.selectBaseAttachmentList(baseAttachmentQuery);
        baseAttachmentService.removeBatchByIds(baseAttachmentListOld);
        if (CollUtil.isNotEmpty(checkCorrection.getBaseAttachmentList())) {
            checkCorrection.getBaseAttachmentList().forEach(baseAttachment -> {
                baseAttachment.setCreateBy(checkCorrection.getCreateBy());
                baseAttachment.setCreateTime(DateUtils.getNowDate());
                baseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getCode());
                baseAttachment.setSourceTypeName(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getInfo());
                baseAttachment.setSourceId(checkCorrection.getId());
            });
            baseAttachmentService.saveBatch(checkCorrection.getBaseAttachmentList());
        }
        return result;
    }

    /**
     * 批量删除问题整改
     *
     * @param ids 需要删除的问题整改主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCheckCorrectionByIds(Long[] ids) {
        int result = checkCorrectionMapper.deleteCheckCorrectionByIds(ids);
        for (Long id : ids) {
            CheckProjectItem checkProjectItemQuery = new CheckProjectItem();
            checkProjectItemQuery.setType(CheckProjectItemTypeEnum.CHECK_CORRECTION.getCode());
            checkProjectItemQuery.setSourceId(id);
            List<CheckProjectItem> checkProjectItemListOld = checkProjectItemService.selectCheckProjectItemList(checkProjectItemQuery);
            checkProjectItemService.removeBatchByIds(checkProjectItemListOld);
            LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CheckUser::getType, CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getCode())
                    .in(CheckUser::getSourceId, checkProjectItemListOld.stream().map(CheckProjectItem::getId).toArray());
            List<CheckUser> checkUserListOld = checkUserService.getBaseMapper().selectList(wrapper);
            checkUserService.removeBatchByIds(checkUserListOld);
            BaseAttachment baseAttachmentQuery = new BaseAttachment();
            baseAttachmentQuery.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getCode());
            baseAttachmentQuery.setSourceId(id);
            List<BaseAttachment> baseAttachmentListOld = baseAttachmentService.selectBaseAttachmentList(baseAttachmentQuery);
            baseAttachmentService.removeBatchByIds(baseAttachmentListOld);
        }
        return result;
    }

    /**
     * 删除问题整改信息
     *
     * @param id 问题整改主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCheckCorrectionById(Long id) {
        int result = checkCorrectionMapper.deleteCheckCorrectionById(id);
        CheckProjectItem checkProjectItemQuery = new CheckProjectItem();
        checkProjectItemQuery.setType(CheckProjectItemTypeEnum.CHECK_CORRECTION.getCode());
        checkProjectItemQuery.setSourceId(id);
        List<CheckProjectItem> checkProjectItemListOld = checkProjectItemService.selectCheckProjectItemList(checkProjectItemQuery);
        checkProjectItemService.removeBatchByIds(checkProjectItemListOld);
        LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckUser::getType, CheckUserTypeEnum.PROBLEM_RECTIFICATION_INSPECTION_ITEM_DETAILS.getCode())
                .in(CheckUser::getSourceId, checkProjectItemListOld.stream().map(CheckProjectItem::getId).toArray());
        List<CheckUser> checkUserListOld = checkUserService.getBaseMapper().selectList(wrapper);
        checkUserService.removeBatchByIds(checkUserListOld);
        BaseAttachment baseAttachmentQuery = new BaseAttachment();
        baseAttachmentQuery.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_CORRECTION.getCode());
        baseAttachmentQuery.setSourceId(id);
        List<BaseAttachment> baseAttachmentListOld = baseAttachmentService.selectBaseAttachmentList(baseAttachmentQuery);
        baseAttachmentService.removeBatchByIds(baseAttachmentListOld);
        return result;
    }

    /**
     * 审批任务（同意）
     *
     * @param checkCorrection 问题整改
     * @return 结果
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int approveTask(CheckCorrection checkCorrection) {
        CheckCorrection checkCorrectionOld = selectCheckCorrectionById(checkCorrection.getId());
        boolean resubmit = StringUtils.equals(CheckLevelEnum.PERSONNEL_LEVEL.getCode(), checkCorrection.getCheckedLevel()) && !Objects.equals(checkCorrectionOld.getResponsibleUserId(), checkCorrection.getResponsibleUserId());
        int result = updateCheckCorrection(checkCorrection);
        if (resubmit) {
            approvalEngineService.cancelProcess(checkCorrection.getInstanceId(), SecurityUtils.getUserId(), SecurityUtils.getUsername(), checkCorrection.getComment());
            startApproval(checkCorrection);
        } else {
            Map<String, Object> formData = BeanUtil.beanToMap(checkCorrection);
            if (StringUtils.equals(CheckLevelEnum.DEPARTMENT_LEVEL.getCode(), checkCorrection.getCheckedLevel()) && ObjUtil.isNotNull(checkCorrection.getIsSelectTeam())) {
                if (checkCorrection.getIsSelectTeam() == 1) {
                    formData.put("routeToGroupLeader", true);
                    formData.put("groupLeaderId", checkCorrection.getSelectTeamLeaderId());
                } else {
                    formData.put("routeToGroupLeader", false);
                }
            }
            log.info("整改单审批任务（同意）:formData:【{}】", formData);
            checkApprovalService.approveTask(checkCorrection.getTaskId(), checkCorrection.getComment(), formData, SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername());
        }
        return result;
    }

    /**
     * 审批任务（驳回）
     *
     * @param checkCorrection 问题整改
     * @return 结果
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int rejectTask(CheckCorrection checkCorrection) {
        checkApprovalService.rejectTask(checkCorrection.getTaskId(), checkCorrection.getComment(), SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername());
        return 0;
    }

    /**
     * 开始审批
     *
     * @param checkCorrection
     */
    @SneakyThrows
    private void startApproval(CheckCorrection checkCorrection) {
        if (StringUtils.equals(CheckLevelEnum.PERSONNEL_LEVEL.getCode(), checkCorrection.getCheckedLevel())) {
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("businessId", checkCorrection.getId());//业务ID
            requestData.put("checkType", "SAFETY_CHECK");//检查类型
            requestData.put("severity", "");//严重程度
            requestData.put("location", checkCorrection.getChannelName());//位置
            requestData.put("sectionLeaderId", checkCorrection.getResponsibleUserId());//科长ID
            requestData.put("problemUserId", checkCorrection.getCheckedPersonnelId());//被检查人员ID
            requestData.put("formData", BeanUtil.beanToMap(checkCorrection));
            ApprovalInstance approvalInstance = checkApprovalService.submitPersonalCheck(requestData, SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername(), CheckLevelEnum.PERSONNEL_LEVEL.getDesc());
            checkCorrection.setInstanceId(approvalInstance.getId());
            checkCorrectionMapper.updateCheckCorrection(checkCorrection);
            log.info("人员级:{}", approvalInstance);
        } else if (StringUtils.equals(CheckLevelEnum.TEAM_LEVEL.getCode(), checkCorrection.getCheckedLevel())) {
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("businessId", checkCorrection.getId());//业务ID
            requestData.put("checkType", "OPERATION_ISSUE");//检查类型
            requestData.put("severity", "");//严重程度
            requestData.put("location", checkCorrection.getChannelName());//位置
            requestData.put("groupLeaderId", checkCorrection.getResponsibleUserId());//目标用户ID列表
            requestData.put("targetDeptId", checkCorrection.getCheckedDeptId());//目标部门ID
            requestData.put("formData", BeanUtil.beanToMap(checkCorrection));
            ApprovalInstance approvalInstance = checkApprovalService.submitGroupCheck(requestData, SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername(), CheckLevelEnum.TEAM_LEVEL.getDesc());
            checkCorrection.setInstanceId(approvalInstance.getId());
            checkCorrectionMapper.updateCheckCorrection(checkCorrection);
            log.info("班组级:{}", approvalInstance);
        } else if (StringUtils.equals(CheckLevelEnum.DEPARTMENT_LEVEL.getCode(), checkCorrection.getCheckedLevel())) {
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("businessId", checkCorrection.getId());//业务ID
            requestData.put("checkType", CheckLevelEnum.DEPARTMENT_LEVEL.getCode());//检查类型
            requestData.put("severity", "");//严重程度
            requestData.put("location", checkCorrection.getChannelName());//位置
            requestData.put("sectionLeaderId", checkCorrection.getResponsibleUserId());//责任人
            requestData.put("targetDeptId", checkCorrection.getCheckedDeptId());//目标部门ID
            requestData.put("formData", BeanUtil.beanToMap(checkCorrection));
            ApprovalInstance approvalInstance = checkApprovalService.submitSectionCheck(requestData, SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername(), CheckLevelEnum.DEPARTMENT_LEVEL.getDesc());
            checkCorrection.setInstanceId(approvalInstance.getId());
            checkCorrectionMapper.updateCheckCorrection(checkCorrection);
            log.info("科级:{}", approvalInstance);
        } else if (StringUtils.equals(CheckLevelEnum.BRIGADE_LEVEL.getCode(), checkCorrection.getCheckedLevel())) {
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("businessId", checkCorrection.getId());//业务ID
            requestData.put("checkType", CheckLevelEnum.BRIGADE_LEVEL.getCode());//检查类型
            requestData.put("severity", "");//严重程度
            requestData.put("location", checkCorrection.getChannelName());//位置
            requestData.put("sectionLeaderId", checkCorrection.getResponsibleUserId());//责任人
            requestData.put("targetDeptId", checkCorrection.getCheckedDeptId());//目标部门ID
            requestData.put("formData", BeanUtil.beanToMap(checkCorrection));
            ApprovalInstance approvalInstance = checkApprovalService.submitBrigadeCheck(requestData, SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername(), CheckLevelEnum.DEPARTMENT_LEVEL.getDesc());
            checkCorrection.setInstanceId(approvalInstance.getId());
            checkCorrectionMapper.updateCheckCorrection(checkCorrection);
            log.info("大队级:{}", approvalInstance);
        } else {
            throw new ServiceException("被检查级别数据异常");
        }
    }

    /**
     * 批量审批任务（同意）
     *
     * @param approvalWorkflowBatchDto 批量审批参数
     * @return 结果
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int approveTaskBatch(ApprovalWorkflowBatchDto approvalWorkflowBatchDto) {
        approvalWorkflowBatchDto.getTaskIdList().forEach(taskId -> {
            ApprovalTask task = taskMapper.selectApprovalTaskById(taskId);
            if (ObjUtil.isNull(task)) {
                throw new ServiceException("【" + taskId + "】任务不存在");
            }
            ApprovalInstance instance = instanceMapper.selectApprovalInstanceById(task.getInstanceId());
            if (ObjUtil.isNull(instance)) {
                throw new ServiceException("【" + taskId + "-" + task.getInstanceId() + "】流程实例不存在");
            }
            CheckCorrection checkCorrection = selectCheckCorrectionById(instance.getBusinessId());
            Map<String, Object> formData = BeanUtil.beanToMap(checkCorrection);
            try {
                checkApprovalService.approveTask(taskId, approvalWorkflowBatchDto.getComment(), formData, SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername());
            } catch (Exception e) {
                throw new ServiceException("审批失败");
            }
        });
        return 1;
    }

    /**
     * 批量审批任务（驳回）
     *
     * @param approvalWorkflowBatchDto 批量审批参数
     * @return 结果
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int rejectTaskBatch(ApprovalWorkflowBatchDto approvalWorkflowBatchDto) {
        approvalWorkflowBatchDto.getTaskIdList().forEach(taskId -> {
            try {
                checkApprovalService.rejectTask(taskId, approvalWorkflowBatchDto.getComment(), SecurityUtils.getLoginUser().getUserId(), SecurityUtils.getLoginUser().getUsername());
            } catch (Exception e) {
                throw new ServiceException("审批失败");
            }
        });
        return 1;
    }
}
