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

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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sundot.airport.check.domain.CheckCorrection;
import com.sundot.airport.check.domain.CheckProjectItem;
import com.sundot.airport.check.domain.CheckUser;
import com.sundot.airport.check.service.ICheckCorrectionService;
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.domain.entity.SysUser;
import com.sundot.airport.common.core.redis.RedisSerialGenerator;
import com.sundot.airport.common.domain.BaseAttachment;
import com.sundot.airport.common.dto.DeptInfo;
import com.sundot.airport.common.enums.BaseAttachmentSourceTypeEnum;
import com.sundot.airport.common.enums.CheckLevelEnum;
import com.sundot.airport.common.enums.CheckProjectItemTypeEnum;
import com.sundot.airport.common.enums.CheckRecordStatusEnum;
import com.sundot.airport.common.enums.CheckResultEnum;
import com.sundot.airport.common.enums.CheckScoreLevelEnum;
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.common.utils.bean.BeanUtils;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.check.mapper.CheckRecordMapper;
import com.sundot.airport.check.domain.CheckRecord;
import com.sundot.airport.check.service.ICheckRecordService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 检查记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-11
 */
@Service
public class CheckRecordServiceImpl extends ServiceImpl<CheckRecordMapper, CheckRecord> implements ICheckRecordService {
    @Autowired
    private ICheckProjectItemService checkProjectItemService;
    @Autowired
    private ICheckUserService checkUserService;
    @Autowired
    private IBaseAttachmentService baseAttachmentService;
    @Autowired
    private CheckRecordMapper checkRecordMapper;
    @Autowired
    private ICheckCorrectionService checkCorrectionService;
    @Autowired
    private RedisSerialGenerator redisSerialGenerator;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询检查记录
     *
     * @param id 检查记录主键
     * @return 检查记录
     */
    @Override
    public CheckRecord selectCheckRecordById(Long id) {
        //检查记录
        CheckRecord result = checkRecordMapper.selectCheckRecordById(id);
        //检查项明细列表
        CheckProjectItem checkProjectItem = new CheckProjectItem();
        checkProjectItem.setType(CheckProjectItemTypeEnum.CHECK_RECORDS.getCode());
        checkProjectItem.setSourceId(result.getId());
        List<CheckProjectItem> checkProjectItemList = checkProjectItemService.selectCheckProjectItemList(checkProjectItem);
        LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckUser::getType, CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getCode())
                .in(CheckUser::getSourceId, checkProjectItemList.stream().map(CheckProjectItem::getId).collect(Collectors.toList()));
        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_RECORD.getCode());
        baseAttachment.setSourceId(result.getId());
        List<BaseAttachment> baseAttachmentList = baseAttachmentService.selectBaseAttachmentList(baseAttachment);
        result.setBaseAttachmentList(baseAttachmentList);
        return result;
    }

    /**
     * 查询检查记录列表
     *
     * @param checkRecord 检查记录
     * @return 检查记录
     */
    @Override
    public List<CheckRecord> selectCheckRecordList(CheckRecord checkRecord) {
        return checkRecordMapper.selectCheckRecordList(checkRecord);
    }

    /**
     * 新增检查记录
     *
     * @param checkRecord 检查记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertCheckRecord(CheckRecord checkRecord) {
        //检查记录
        checkRecord.setCreateTime(DateUtils.getNowDate());
        checkRecord.setDocumentCode(redisSerialGenerator.generate(Constants.CHECK_DOCUMENT_PREFIX));
        doCheckedDept(checkRecord);
        int result = checkRecordMapper.insertCheckRecord(checkRecord);
        //检查项明细列表
        checkRecord.getCheckProjectItemList().forEach(checkProjectItem -> {
            checkProjectItem.setCreateBy(checkRecord.getCreateBy());
            checkProjectItem.setCreateTime(DateUtils.getNowDate());
            checkProjectItem.setType(CheckProjectItemTypeEnum.CHECK_RECORDS.getCode());
            checkProjectItem.setTypeDesc(CheckProjectItemTypeEnum.CHECK_RECORDS.getInfo());
            checkProjectItem.setSourceId(checkRecord.getId());
            checkProjectItemService.insertCheckProjectItem(checkProjectItem);
            if (CollUtil.isNotEmpty(checkProjectItem.getCheckUserList())) {
                checkProjectItem.getCheckUserList().forEach(checkUser -> {
                    checkUser.setCreateBy(checkProjectItem.getCreateBy());
                    checkUser.setCreateTime(DateUtils.getNowDate());
                    checkUser.setType(CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getCode());
                    checkUser.setTypeDesc(CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getInfo());
                    checkUser.setSourceId(checkProjectItem.getId());
                });
                checkUserService.saveBatch(checkProjectItem.getCheckUserList());
            }
        });
        //附件列表
        if (CollUtil.isNotEmpty(checkRecord.getBaseAttachmentList())) {
            checkRecord.getBaseAttachmentList().forEach(baseAttachment -> {
                baseAttachment.setCreateBy(checkRecord.getCreateBy());
                baseAttachment.setCreateTime(DateUtils.getNowDate());
                baseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getCode());
                baseAttachment.setSourceTypeName(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getInfo());
                baseAttachment.setSourceId(checkRecord.getId());
            });
            baseAttachmentService.saveBatch(checkRecord.getBaseAttachmentList());
        }
        return result;
    }

    /**
     * 创建问题整改表单
     *
     * @param checkRecordId 检查记录表ID
     * @return
     */
    private void doCheckCorrection(Long checkRecordId) {
        CheckRecord checkRecord = selectCheckRecordById(checkRecordId);
        if (CollUtil.isEmpty(checkRecord.getCheckProjectItemList())) {
            return;
        }
        List<CheckProjectItem> checkProjectItemListTemp = checkRecord.getCheckProjectItemList().stream().filter(item -> !StringUtils.equals(CheckScoreLevelEnum.QUALIFIED.getCode(), item.getScoreLevel())).collect(Collectors.toList());
        if (CollUtil.isEmpty(checkProjectItemListTemp)) {
            return;
        }
        CheckCorrection checkCorrection = new CheckCorrection();
        BeanUtils.copyProperties(checkRecord, checkCorrection);
        checkCorrection.setCheckRecordId(checkRecord.getId());
        checkCorrection.setId(null);
        checkCorrection.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        List<CheckProjectItem> checkProjectItemList = new ArrayList<>();
        for (CheckProjectItem item : checkProjectItemListTemp) {
            CheckProjectItem checkProjectItem = new CheckProjectItem();
            BeanUtils.copyProperties(item, checkProjectItem);
            checkProjectItem.setId(null);
            checkProjectItem.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            List<CheckUser> checkUserListTemp = checkProjectItem.getCheckUserList();
            if (CollUtil.isNotEmpty(checkUserListTemp)) {
                List<CheckUser> checkUserList = new ArrayList<>();
                for (CheckUser checkUserItem : checkUserListTemp) {
                    CheckUser checkUser = new CheckUser();
                    BeanUtils.copyProperties(checkUserItem, checkUser);
                    checkUser.setId(null);
                    checkUser.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                    checkUserList.add(checkUser);
                }
                checkProjectItem.setCheckUserList(checkUserList);
            }
            checkProjectItemList.add(checkProjectItem);
        }
        checkCorrection.setCheckProjectItemList(checkProjectItemList);
        List<BaseAttachment> checkRecordBaseAttachmentList = new ArrayList<>();
        List<BaseAttachment> baseAttachmentListTemp = checkRecord.getBaseAttachmentList();
        if (CollUtil.isNotEmpty(baseAttachmentListTemp)) {
            for (BaseAttachment item : baseAttachmentListTemp) {
                BaseAttachment baseAttachment = new BaseAttachment();
                BeanUtils.copyProperties(item, baseAttachment);
                baseAttachment.setId(null);
                baseAttachment.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                checkRecordBaseAttachmentList.add(baseAttachment);
            }
        }
        checkCorrection.setCheckRecordBaseAttachmentList(checkRecordBaseAttachmentList);
        checkCorrection.setBaseAttachmentList(null);
        checkCorrectionService.insertCheckCorrection(checkCorrection);
    }

    /**
     * 修改检查记录
     *
     * @param checkRecord 检查记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateCheckRecord(CheckRecord checkRecord) {
        checkRecord.setUpdateTime(DateUtils.getNowDate());
        doCheckedDept(checkRecord);
        int result = checkRecordMapper.updateCheckRecord(checkRecord);
        //先删除
        CheckProjectItem checkProjectItemQuery = new CheckProjectItem();
        checkProjectItemQuery.setType(CheckProjectItemTypeEnum.CHECK_RECORDS.getCode());
        checkProjectItemQuery.setSourceId(checkRecord.getId());
        List<CheckProjectItem> checkProjectItemListTemp = checkProjectItemService.selectCheckProjectItemList(checkProjectItemQuery);
        checkProjectItemService.removeBatchByIds(checkProjectItemListTemp);
        LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckUser::getType, CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getCode())
                .in(CheckUser::getSourceId, checkProjectItemListTemp.stream().map(CheckProjectItem::getId).toArray());
        List<CheckUser> checkUserListTemp = checkUserService.getBaseMapper().selectList(wrapper);
        checkUserService.removeBatchByIds(checkUserListTemp);
        //附件列表
        BaseAttachment baseAttachmentQuery = new BaseAttachment();
        baseAttachmentQuery.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getCode());
        baseAttachmentQuery.setSourceId(checkRecord.getId());
        List<BaseAttachment> baseAttachmentListTemp = baseAttachmentService.selectBaseAttachmentList(baseAttachmentQuery);
        baseAttachmentService.removeBatchByIds(baseAttachmentListTemp);

        //后新增
        checkRecord.getCheckProjectItemList().forEach(checkProjectItem -> {
            checkProjectItem.setId(null);
            checkProjectItem.setCreateBy(checkRecord.getCreateBy());
            checkProjectItem.setCreateTime(DateUtils.getNowDate());
            checkProjectItem.setType(CheckProjectItemTypeEnum.CHECK_RECORDS.getCode());
            checkProjectItem.setTypeDesc(CheckProjectItemTypeEnum.CHECK_RECORDS.getInfo());
            checkProjectItem.setSourceId(checkRecord.getId());
            checkProjectItemService.insertCheckProjectItem(checkProjectItem);
            if (CollUtil.isNotEmpty(checkProjectItem.getCheckUserList())) {
                checkProjectItem.getCheckUserList().forEach(checkUser -> {
                    checkUser.setId(null);
                    checkUser.setCreateBy(checkProjectItem.getCreateBy());
                    checkUser.setCreateTime(DateUtils.getNowDate());
                    checkUser.setType(CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getCode());
                    checkUser.setTypeDesc(CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getInfo());
                    checkUser.setSourceId(checkProjectItem.getId());
                });
                checkUserService.saveBatch(checkProjectItem.getCheckUserList());
            }
        });
        //附件列表
        if (CollUtil.isNotEmpty(checkRecord.getBaseAttachmentList())) {
            checkRecord.getBaseAttachmentList().forEach(baseAttachment -> {
                baseAttachment.setId(null);
                baseAttachment.setCreateBy(checkRecord.getCreateBy());
                baseAttachment.setCreateTime(DateUtils.getNowDate());
                baseAttachment.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getCode());
                baseAttachment.setSourceTypeName(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getInfo());
                baseAttachment.setSourceId(checkRecord.getId());
            });
            baseAttachmentService.saveBatch(checkRecord.getBaseAttachmentList());
        }
        return result;
    }

    /**
     * 批量删除检查记录
     *
     * @param ids 需要删除的检查记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCheckRecordByIds(Long[] ids) {
        int result = checkRecordMapper.deleteCheckRecordByIds(ids);
        for (Long id : ids) {
            CheckProjectItem checkProjectItemQuery = new CheckProjectItem();
            checkProjectItemQuery.setType(CheckProjectItemTypeEnum.CHECK_RECORDS.getCode());
            checkProjectItemQuery.setSourceId(id);
            List<CheckProjectItem> checkProjectItemListTemp = checkProjectItemService.selectCheckProjectItemList(checkProjectItemQuery);
            checkProjectItemService.removeBatchByIds(checkProjectItemListTemp);
            LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CheckUser::getType, CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getCode())
                    .in(CheckUser::getSourceId, checkProjectItemListTemp.stream().map(CheckProjectItem::getId).toArray());
            List<CheckUser> checkUserListTemp = checkUserService.getBaseMapper().selectList(wrapper);
            checkUserService.removeBatchByIds(checkUserListTemp);
            //附件列表
            BaseAttachment baseAttachmentQuery = new BaseAttachment();
            baseAttachmentQuery.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getCode());
            baseAttachmentQuery.setSourceId(id);
            List<BaseAttachment> baseAttachmentListTemp = baseAttachmentService.selectBaseAttachmentList(baseAttachmentQuery);
            baseAttachmentService.removeBatchByIds(baseAttachmentListTemp);
        }
        return result;
    }

    /**
     * 删除检查记录信息
     *
     * @param id 检查记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCheckRecordById(Long id) {
        int result = checkRecordMapper.deleteCheckRecordById(id);
        CheckProjectItem checkProjectItemQuery = new CheckProjectItem();
        checkProjectItemQuery.setType(CheckProjectItemTypeEnum.CHECK_RECORDS.getCode());
        checkProjectItemQuery.setSourceId(id);
        List<CheckProjectItem> checkProjectItemListTemp = checkProjectItemService.selectCheckProjectItemList(checkProjectItemQuery);
        checkProjectItemService.removeBatchByIds(checkProjectItemListTemp);
        LambdaQueryWrapper<CheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckUser::getType, CheckUserTypeEnum.INSPECT_RECORDS_INSPECTION_ITEM_DETAILS.getCode())
                .in(CheckUser::getSourceId, checkProjectItemListTemp.stream().map(CheckProjectItem::getId).toArray());
        List<CheckUser> checkUserListTemp = checkUserService.getBaseMapper().selectList(wrapper);
        checkUserService.removeBatchByIds(checkUserListTemp);
        //附件列表
        BaseAttachment baseAttachmentQuery = new BaseAttachment();
        baseAttachmentQuery.setSourceType(BaseAttachmentSourceTypeEnum.CHECK_RECORD.getCode());
        baseAttachmentQuery.setSourceId(id);
        List<BaseAttachment> baseAttachmentListTemp = baseAttachmentService.selectBaseAttachmentList(baseAttachmentQuery);
        baseAttachmentService.removeBatchByIds(baseAttachmentListTemp);
        return result;
    }

    /**
     * 新增或更新检查记录
     *
     * @param checkRecord 检查记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertOrUpdateCheckRecord(CheckRecord checkRecord, boolean isLaunch) {
        if (isLaunch) {
            checkParam(checkRecord);
        }
        int result;
        if (ObjUtil.isEmpty(checkRecord.getId())) {
            if (CollUtil.isNotEmpty(checkRecord.getCheckProjectItemList())) {
                checkRecord.getCheckProjectItemList().forEach(checkProjectItem -> {
                    checkProjectItem.setId(null);
                    if (CollUtil.isNotEmpty(checkProjectItem.getCheckUserList())) {
                        checkProjectItem.getCheckUserList().forEach(checkUser -> {
                            checkUser.setId(null);
                        });
                    }
                });
            }
            if (CollUtil.isNotEmpty(checkRecord.getBaseAttachmentList())) {
                checkRecord.getBaseAttachmentList().forEach(baseAttachment -> {
                    baseAttachment.setId(null);
                });
            }
            List<CheckProjectItem> projectItemList = checkRecord.getCheckProjectItemList();
            if (CollUtil.isEmpty(projectItemList)) {
                checkRecord.setCheckResult(CheckResultEnum.PASS.getCode());
                checkRecord.setCheckResultDesc(CheckResultEnum.PASS.getDesc());
            } else {
                boolean hasUnqualifiedItem = projectItemList.stream().anyMatch(item -> item != null && !StringUtils.equals(CheckScoreLevelEnum.QUALIFIED.getCode(), item.getScoreLevel()));
                if (hasUnqualifiedItem) {
                    checkRecord.setCheckResult(CheckResultEnum.FAIL.getCode());
                    checkRecord.setCheckResultDesc(CheckResultEnum.FAIL.getDesc());
                } else {
                    checkRecord.setCheckResult(CheckResultEnum.PASS.getCode());
                    checkRecord.setCheckResultDesc(CheckResultEnum.PASS.getDesc());
                }
            }
            result = insertCheckRecord(checkRecord);
        } else {
            CheckRecord record = checkRecordMapper.selectById(checkRecord.getId());
            if (ObjUtil.isNull(record)) {
                throw new ServiceException("根据id[" + checkRecord.getId() + "]未查询到检查单");
            }
            List<CheckProjectItem> projectItemList = checkRecord.getCheckProjectItemList();
            if (CollUtil.isEmpty(projectItemList)) {
                checkRecord.setCheckResult(CheckResultEnum.PASS.getCode());
                checkRecord.setCheckResultDesc(CheckResultEnum.PASS.getDesc());
            } else {
                boolean hasUnqualifiedItem = projectItemList.stream().anyMatch(item -> item != null && !StringUtils.equals(CheckScoreLevelEnum.QUALIFIED.getCode(), item.getScoreLevel()));
                if (hasUnqualifiedItem) {
                    checkRecord.setCheckResult(CheckResultEnum.FAIL.getCode());
                    checkRecord.setCheckResultDesc(CheckResultEnum.FAIL.getDesc());
                } else {
                    checkRecord.setCheckResult(CheckResultEnum.PASS.getCode());
                    checkRecord.setCheckResultDesc(CheckResultEnum.PASS.getDesc());
                }
            }
            result = updateCheckRecord(checkRecord);
        }
        //创建问题整改表单
        if (isLaunch && StringUtils.equals(CheckRecordStatusEnum.FORMAL.getCode(), checkRecord.getCheckRecordStatus())) {
            doCheckCorrection(checkRecord.getId());
        }
        return result;
    }

    /**
     * 检查参数
     *
     * @param checkRecord 检查记录
     */
    private static void checkParam(CheckRecord checkRecord) {
        if (ObjUtil.isEmpty(checkRecord.getCheckerId()) || StrUtil.isEmpty(checkRecord.getCheckerName())) {
            throw new ServiceException("检查人不能为空");
        }
        if (StrUtil.isEmpty(checkRecord.getTerminlCode()) || StrUtil.isEmpty(checkRecord.getTerminlName())
                || StrUtil.isEmpty(checkRecord.getRegionalCode()) || StrUtil.isEmpty(checkRecord.getRegionalName())
                || StrUtil.isEmpty(checkRecord.getChannelCode()) || StrUtil.isEmpty(checkRecord.getChannelName())) {
            throw new ServiceException("检查地点不能为空");
        }
        if (ObjUtil.isEmpty(checkRecord.getCheckTime())) {
            throw new ServiceException("检查时间不能为空");
        }
        if (StrUtil.isEmpty(checkRecord.getCheckedLevel()) || StrUtil.isEmpty(checkRecord.getCheckedLevelDesc())) {
            throw new ServiceException("被检查级别不能为空");
        }
        if (StrUtil.equals(checkRecord.getCheckedLevel(), CheckLevelEnum.PERSONNEL_LEVEL.getCode()) &&
                (ObjUtil.isEmpty(checkRecord.getCheckedPersonnelId()) || StrUtil.isEmpty(checkRecord.getCheckedPersonnelName()))) {
            throw new ServiceException("被检查人不能为空");
        }
        if (StrUtil.equals(checkRecord.getCheckedLevel(), CheckLevelEnum.TEAM_LEVEL.getCode()) &&
                (ObjUtil.isEmpty(checkRecord.getCheckedTeamId()) || StrUtil.isEmpty(checkRecord.getCheckedTeamName()))) {
            throw new ServiceException("被检查班组不能为空");
        }
        if (StrUtil.equals(checkRecord.getCheckedLevel(), CheckLevelEnum.DEPARTMENT_LEVEL.getCode()) &&
                (ObjUtil.isEmpty(checkRecord.getCheckedDepartmentId()) || StrUtil.isEmpty(checkRecord.getCheckedDepartmentName()))) {
            throw new ServiceException("被检查科室不能为空");
        }
        if (StrUtil.equals(checkRecord.getCheckedLevel(), CheckLevelEnum.BRIGADE_LEVEL.getCode()) &&
                (ObjUtil.isEmpty(checkRecord.getCheckedBrigadeId()) || StrUtil.isEmpty(checkRecord.getCheckedBrigadeName()))) {
            throw new ServiceException("被检查大队不能为空");
        }
        if (CollUtil.isNotEmpty(checkRecord.getCheckProjectItemList())) {
            List<CheckProjectItem> unQualifiedList = checkRecord.getCheckProjectItemList().stream().filter(checkProjectItem -> StrUtil.equals(CheckScoreLevelEnum.UNQUALIFIED.getCode(), checkProjectItem.getScoreLevel())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(unQualifiedList)) {
                if (ObjUtil.isEmpty(checkRecord.getResponsibleUserId()) && StrUtil.isEmpty(checkRecord.getResponsibleUserName())) {
                    throw new ServiceException("负责人不能为空");
                }
                if (ObjUtil.isEmpty(checkRecord.getRectificationDeadline())) {
                    throw new ServiceException("整改期限不能为空");
                }
                if (StrUtil.isEmpty(checkRecord.getRectificationSuggestions())) {
                    throw new ServiceException("整改要求不能为空");
                }
                unQualifiedList.forEach(checkProjectItem -> {
                    if (CollUtil.isEmpty(checkProjectItem.getCheckUserList()) && StringUtils.isEmpty(checkProjectItem.getProblemDescription())) {
                        throw new ServiceException("不合格人员及问题描述不能同时为空");
                    }
                });
            }
        }
    }

    /**
     * 处理被检查部门信息
     *
     * @param checkRecord 检查单
     */
    private void doCheckedDept(CheckRecord checkRecord) {
        if (StringUtils.equals(CheckLevelEnum.PERSONNEL_LEVEL.getCode(), checkRecord.getCheckedLevel())) {
            Long userId = checkRecord.getCheckedPersonnelId();
            if (Objects.isNull(userId)) {
                throw new ServiceException("请选择被检查人员");
            }
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (Objects.isNull(sysUser.getDeptId())) {
                throw new ServiceException("被检查人员[" + userId + "]所属部门为空");
            }
            DeptInfo deptInfo = deptService.getDeptInfoByDeptId(sysUser.getDeptId());
            if (Objects.isNull(deptInfo.getTeamId())) {
                throw new ServiceException("被检查人员[" + userId + "]所属班组信息为空");
            }
            if (Objects.isNull(deptInfo.getDepartmentId())) {
                throw new ServiceException("被检查人员[" + userId + "]所属主管信息为空");
            }
            if (Objects.isNull(deptInfo.getBrigadeId())) {
                throw new ServiceException("被检查人员[" + userId + "]所属大队信息为空");
            }
            if (Objects.isNull(deptInfo.getStationId())) {
                throw new ServiceException("被检查人员[" + userId + "]所属机构站信息为空");
            }
            checkRecord.setCheckedBrigadeId(deptInfo.getBrigadeId());
            checkRecord.setCheckedBrigadeName(deptInfo.getBrigadeName());
            checkRecord.setCheckedDepartmentId(deptInfo.getDepartmentId());
            checkRecord.setCheckedDepartmentName(deptInfo.getDepartmentName());
            checkRecord.setCheckedTeamId(deptInfo.getTeamId());
            checkRecord.setCheckedTeamName(deptInfo.getTeamName());
        } else {
            Long deptId = checkRecord.getCheckedDeptId();
            if (Objects.isNull(deptId)) {
                throw new ServiceException("请选择被检查部门");
            }
            DeptInfo deptInfo = deptService.getDeptInfoByDeptId(deptId);
            checkRecord.setCheckedBrigadeId(deptInfo.getBrigadeId());
            checkRecord.setCheckedBrigadeName(deptInfo.getBrigadeName());
            checkRecord.setCheckedDepartmentId(deptInfo.getDepartmentId());
            checkRecord.setCheckedDepartmentName(deptInfo.getDepartmentName());
            checkRecord.setCheckedTeamId(deptInfo.getTeamId());
            checkRecord.setCheckedTeamName(deptInfo.getTeamName());
        }
    }

}
