package com.yida.data.form.apply.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yida.data.common.core.entity.applyForm.*;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.enums.EnableStatusEnum;
import com.yida.data.common.core.enums.RoleName;
import com.yida.data.common.core.enums.leave.ApprovalResultEnum;
import com.yida.data.common.core.enums.leave.AuditModeEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.service.CommonService;
import com.yida.data.customForm.dto.apply.*;
import com.yida.data.customForm.vo.apply.*;
import com.yida.data.form.apply.mapper.ApplyFormDataMapper;
import com.yida.data.form.apply.mapper.CoreApplyFormFillUserMapper;
import com.yida.data.form.apply.service.*;
import com.yida.data.user.dto.ListStaffDTO;
import com.yida.data.user.feign.RemoteStaffService;
import com.yida.data.user.feign.RemoteStudentService;
import com.yida.data.user.feign.RemoteUserDeptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * H5--申请类表单管理 Service
 *
 * @author ZYJ
 * @date 2023/11/15 20:38
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class AppApplyFormServiceImpl implements AppApplyFormService {

    private final SendNoticeService sendNoticeService;
    private final ApplyFormDataService applyFormDataService;
    private final CoreApplyFormService coreApplyFormService;
    private final CoreApplyFormItemService coreApplyFormItemService;
    private final CoreApprovalProcessService coreApprovalProcessService;
    private final CoreApplyFormFillUserService coreApplyFormFillUserService;
    private final CoreApplyFormItemChildrenService coreApplyFormItemChildrenService;
    private final CoreApplyFormFillUserApprovalProcessService coreApplyFormFillUserApprovalProcessService;
    private final CoreApplyFormFillUserApprovalProcessRecordService coreApplyFormFillUserApprovalProcessRecordService;

    private final ApplyFormDataMapper applyFormDataMapper;
    private final CoreApplyFormFillUserMapper coreApplyFormFillUserMapper;

    private final RemoteStaffService remoteStaffService;
    private final RemoteStudentService remoteStudentService;
    private final RemoteUserDeptService remoteUserDeptService;

    private final RedisService redisService;
    private final CommonService commonService;

    @Override
    public IPage<ApplyFormSelectPageVO> listApplyFormPage(H5ApplyFormSelectPageDTO dto) {
        ApplyFormSelectPageDTO selectPageDTO = new ApplyFormSelectPageDTO();
        selectPageDTO.setDeptId(dto.getDeptId());
        selectPageDTO.setStatus(EnableStatusEnum.ENABLE_STATUS.getStatus());
        selectPageDTO.setPageNum(dto.getPageNum());
        selectPageDTO.setPageSize(dto.getPageSize());
        // 查询表单信息
        return coreApplyFormService.listApplyFormPage(selectPageDTO);
    }

    @Override
    public IPage<MyApplyFormPageVO> listMyApplyFormPage(H5ApplyFormSelectPageDTO dto) {
        // 查询学生列表
        List<EduStudent> studentList = remoteStudentService.listStudentByParent(dto.getParentId()).getData();
        if (CollUtil.isEmpty(studentList)) {
            return new Page<>();
        }
        Map<Long, List<EduStudent>> studentListMap = studentList.stream().collect(Collectors.groupingBy(EduStudent::getId));
        // 查询用户已经填报的数据
        List<Long> studentIds = studentList.stream().map(EduStudent::getId).collect(Collectors.toList());
        IPage<MyApplyFormPageVO> page = coreApplyFormFillUserService.selectUserFillForm(dto, studentIds);
        page.getRecords().forEach(myApplyFormPageVO -> {
            // 处理学生信息
            EduStudent eduStudent = studentListMap.get(myApplyFormPageVO.getUserId()).get(0);
            myApplyFormPageVO.setUserName(eduStudent.getStuName());
            myApplyFormPageVO.setUserPicUrl(eduStudent.getAvatar());
        });
        return page;
    }

    @Override
    public ApplyFormInfoVO getApplyFormInfo(Long id) {
        return coreApplyFormService.getApplyFormInfo(id);
    }

    @Override
    public void saveApplyFormData(ApplyFormDataInputDTO dto) {
        CoreApplyForm applyForm = coreApplyFormService.getById(dto.getFormId());
        if (Objects.isNull(applyForm)) {
            throw new FebsException("申请表信息异常");
        }
        applyFormDataService.saveFormData(dto, applyForm);
    }

    @Override
    public IPage<ApprovalApplyFormPageVO> findApprovalApplyFormDataList(SelectApprovalApplyFormDataListDTO dto) {
        LocalDateTime preDateTime = LocalDate.now().minusMonths(1).atTime(23, 59, 59);
        // 职工参与审核的填报用户信息
        List<CoreApplyFormFillUser> approvalUserFormList = coreApplyFormFillUserMapper.findApprovalFormDataFillUserList(dto, preDateTime);
        if (CollUtil.isEmpty(approvalUserFormList)) {
            return new Page<>();
        }
        // 如果表单已通过或者未通过，表示已处理了
        List<CoreApplyFormFillUser> dealEdList = approvalUserFormList.stream()
                .filter(e -> ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), e.getExamineStatus())
                        || ObjectUtil.equals(ApprovalResultEnum.AUDIT_NO.getResult(), e.getExamineStatus()))
                .collect(Collectors.toList());
        List<Long> dealEdIdList = dealEdList.stream().map(CoreApplyFormFillUser::getId).collect(Collectors.toList());
        // 待处理/正在处理的请假
        List<CoreApplyFormFillUser> dealIngList = approvalUserFormList.stream()
                .filter(e -> ObjectUtil.equals(ApprovalResultEnum.AUDIT.getResult(), e.getExamineStatus())
                        || ObjectUtil.equals(ApprovalResultEnum.AUDIT_ING.getResult(), e.getExamineStatus()))
                .collect(Collectors.toList());
        List<Long> dealIngIdList = new ArrayList<>();

        for (CoreApplyFormFillUser fillUser : dealIngList) {
            // 待审核
            List<CoreApplyFormFillUserApprovalProcess> userApprovalProcessList = coreApplyFormFillUserApprovalProcessService
                    .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcess())
                            .eq(CoreApplyFormFillUserApprovalProcess::getFillUserId, fillUser.getId())
                            .eq(CoreApplyFormFillUserApprovalProcess::getExamineStatus, ApprovalResultEnum.AUDIT.getResult())
                            .orderByAsc(CoreApplyFormFillUserApprovalProcess::getSort));
            if (CollUtil.isEmpty(userApprovalProcessList)) {
                continue;
            }
            // 下一级审核
            CoreApplyFormFillUserApprovalProcess userApprovalProcess = userApprovalProcessList.get(0);
            List<CoreApplyFormFillUserApprovalProcessRecord> recordList = coreApplyFormFillUserApprovalProcessRecordService
                    .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getFillUserId, fillUser.getId())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getUserProcessId, userApprovalProcess.getId()));
            if (recordList.stream().map(CoreApplyFormFillUserApprovalProcessRecord::getApprovalId)
                    .collect(Collectors.toList()).contains(dto.getUserId())) {
                dealIngIdList.add(fillUser.getId());
            }
            // 已审核通过
            List<CoreApplyFormFillUserApprovalProcess> userApprovalProcessPassList = coreApplyFormFillUserApprovalProcessService
                    .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcess())
                            .eq(CoreApplyFormFillUserApprovalProcess::getFillUserId, fillUser.getId())
                            .eq(CoreApplyFormFillUserApprovalProcess::getExamineStatus, ApprovalResultEnum.AUDIT_PASS.getResult())
                            .orderByAsc(CoreApplyFormFillUserApprovalProcess::getSort));
            if (CollUtil.isEmpty(userApprovalProcessPassList)) {
                continue;
            }
            List<CoreApplyFormFillUserApprovalProcessRecord> passRecordList = coreApplyFormFillUserApprovalProcessRecordService
                    .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getFillUserId, fillUser.getId())
                            .in(CoreApplyFormFillUserApprovalProcessRecord::getUserProcessId,
                                    userApprovalProcessPassList.stream().map(CoreApplyFormFillUserApprovalProcess::getId).collect(
                                            Collectors.toList())));
            if (passRecordList.stream().map(CoreApplyFormFillUserApprovalProcessRecord::getApprovalId)
                    .collect(Collectors.toList()).contains(dto.getUserId())) {
                dealEdIdList.add(fillUser.getId());
            }
        }

        if (CollUtil.isEmpty(dealEdIdList)) {
            dealEdIdList.add(-1L);
        }

        if (CollUtil.isEmpty(dealIngIdList)) {
            dealIngIdList.add(-1L);
        }
        ApprovalFillUserFormPageDTO pageDTO = new ApprovalFillUserFormPageDTO();
        pageDTO.setPageNum(dto.getPageNum());
        pageDTO.setPageSize(dto.getPageSize());
        pageDTO.setSchoolId(dto.getSchoolId());
        pageDTO.setFillUserIds(
                ObjectUtil.equals(ApprovalResultEnum.AUDIT.getResult(), dto.getCurrentUserStatus()) ? dealIngIdList : dealEdIdList);
        // 查询教师审核的表单分页数据
        IPage<ApprovalApplyFormPageVO> page = coreApplyFormFillUserMapper.selectApprovalUserFillForm(pageDTO.toPage(), pageDTO);
        for (ApprovalApplyFormPageVO record : page.getRecords()) {
            // 学生
            EduStudent student = commonService.getStudentById(record.getUserId());
            if (ObjectUtil.isNull(student)) {
                log.error("学生【{}】不存在,无法处理申请表单数据", record.getUserId().toString());
                continue;
            }
            EduUserDept userGreadeDept = (EduUserDept) redisService
                    .hget(CachePrefixConstant.USER_DEPT_DATA, student.getGradeId().toString());

            EduUserDept userClassDept = (EduUserDept) redisService
                    .hget(CachePrefixConstant.USER_DEPT_DATA, student.getClassId().toString());

            if (ObjectUtil.isNull(userGreadeDept)) {
                userGreadeDept = remoteUserDeptService.getByDeptId(student.getGradeId()).getData();
                if (ObjectUtil.isNotNull(userGreadeDept)) {
                    redisService.hset(CachePrefixConstant.USER_DEPT_DATA, student.getGradeId().toString(), userGreadeDept);
                }
            }

            if (ObjectUtil.isNull(userClassDept)) {
                userClassDept = remoteUserDeptService.getByDeptId(student.getClassId()).getData();
                if (ObjectUtil.isNotNull(userClassDept)) {
                    redisService.hset(CachePrefixConstant.USER_DEPT_DATA, student.getClassId().toString(), userClassDept);
                }
            }
            if (ObjectUtil.isNull(userGreadeDept) && ObjectUtil.isNull(userGreadeDept)) {
                record.setUserDeptName("未知班级");
            } else {
                record.setUserDeptName(
                        (ObjectUtil.isNull(userGreadeDept) ? "" : userGreadeDept.getDeptName()) + (ObjectUtil
                                .isNull(userClassDept) ? "" : userClassDept.getDeptName()));
            }
            record.setUserPicUrl(student.getAvatar());
        }
        return page;
    }

    @Override
    public ApplyFormFillUserDataVO getApplyFormFillUserData(ApplyFormFillUserDataDTO dto) {
        // 返回信息
        ApplyFormFillUserDataVO vo = new ApplyFormFillUserDataVO();
        // 查询填报用户信息
        CoreApplyFormFillUser fillUser = coreApplyFormFillUserService.getById(dto.getFillUserId());
        vo.setFillUserId(fillUser.getId());
        // 表单信息
        CoreApplyForm applyForm = coreApplyFormService.getById(dto.getApplyFormId());
        BeanUtils.copyProperties(applyForm, vo);
        // 查询组件信息
        List<CoreApplyFormItem> itemList = coreApplyFormItemService.list(Wrappers.<CoreApplyFormItem>query().lambda()
                .eq(CoreApplyFormItem::getFormId, dto.getApplyFormId()));
        itemList.forEach(item -> {
            // 查询组件选项信息
            List<CoreApplyFormItemChildren> childrenList =
                    coreApplyFormItemChildrenService.list(Wrappers.<CoreApplyFormItemChildren>query().lambda()
                            .eq(CoreApplyFormItemChildren::getFormItemId, item.getId()));
            item.setChildrenList(childrenList);
        });
        vo.setItemList(itemList);
        // 查询对应的填报信息
        Map<String, Object> parameterMap = new HashMap<>();
        String sql = "select * from " + applyForm.getTableName() + " where id = #{parameterMap.id}";
        parameterMap.put("id", fillUser.getApplyFormDataId());
        Map fillUserData = applyFormDataMapper.findFillUserData(sql, parameterMap);
        vo.setFillUserData(fillUserData);
        // 查询填报用户对应的审核流程
        List<CoreApplyFormFillUserApprovalProcess> userApprovalProcessList = coreApplyFormFillUserApprovalProcessService
                .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcess())
                        .eq(CoreApplyFormFillUserApprovalProcess::getFillUserId, fillUser.getId())
                        .orderByAsc(CoreApplyFormFillUserApprovalProcess::getSort));
        userApprovalProcessList.forEach(userApprovalProcess -> {
            List<CoreApplyFormFillUserApprovalProcessRecord> recordList = coreApplyFormFillUserApprovalProcessRecordService
                    .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getFillUserId, fillUser.getId())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getUserProcessId, userApprovalProcess.getId()));
            // 查询审核人信息
            ListStaffDTO staffDTO = new ListStaffDTO();
            staffDTO.setIds(recordList.stream().map(CoreApplyFormFillUserApprovalProcessRecord::getApprovalId)
                    .collect(Collectors.toList()));
            for (CoreApplyFormFillUserApprovalProcessRecord record : recordList) {
                EduStaff staff = (EduStaff) redisService.hget(CachePrefixConstant.STAFF_DATA, record.getApprovalId().toString());
                if (Objects.isNull(staff)) {
                    staff = remoteStaffService.getStaff(record.getApprovalId()).getData();
                    if (Objects.nonNull(staff)) {
                        redisService
                                .hset(CachePrefixConstant.STAFF_DATA, record.getApprovalId().toString(), staff);
                    }
                }
                if (Objects.nonNull(staff)) {
                    record.setApprovalInfo(staff);
                }
            }
            userApprovalProcess.setRecordList(recordList);
        });
        vo.setUserApprovalProcessList(userApprovalProcessList);
        // 学生信息
        EduStudent student = (EduStudent) redisService
                .hget(CachePrefixConstant.STUDENT_DATA, fillUser.getUserId().toString());
        if (Objects.isNull(student)) {
            student = remoteStudentService.getStudentNoPermission(fillUser.getUserId()).getData();
            if (ObjectUtil.isNotNull(student)) {
                redisService.hset(CachePrefixConstant.STUDENT_DATA, fillUser.getUserId().toString(), student);
            }
        }
        vo.setStudent(student);
        return vo;
    }

    @Override
    public void auditForm(AuditFormDTO dto) {
        // 填报信息主体
        CoreApplyFormFillUser fillUser = coreApplyFormFillUserService.getById(dto.getFillUserId());
        // 查询学生
        EduStudent student = (EduStudent) redisService
                .hget(CachePrefixConstant.STUDENT_DATA, fillUser.getUserId().toString());
        if (Objects.isNull(student)) {
            student = remoteStudentService.getStudentNoPermission(fillUser.getUserId()).getData();
            if (student == null) {
                throw new FebsException("学生信息错误，请联系管理员");
            } else {
                redisService.hset(CachePrefixConstant.STUDENT_DATA, fillUser.getUserId().toString(), student);
            }
        }
        // 查询学校信息
        Dept school = commonService.getDept(student.getSchoolId());
        // 封装消息发送对象
        SendStaffNoticeDTO sendStaffNoticeDTO = new SendStaffNoticeDTO();
        sendStaffNoticeDTO.setSchoolId(student.getSchoolId());
        sendStaffNoticeDTO.setSchoolType(school.getSchoolType());
        sendStaffNoticeDTO.setCreateTime(LocalDateTime.now());
        sendStaffNoticeDTO.setUserName(student.getStuName());
        sendStaffNoticeDTO.setUserDeptName(
                String.join("/", student.getCampusName(), student.getGradeName(), student.getClassName()));
        sendStaffNoticeDTO.setFormId(fillUser.getApplyFormId());
        sendStaffNoticeDTO.setFillUserId(fillUser.getId());
        sendStaffNoticeDTO.setUserId(student.getId());
        // 判断审核权限
        List<CoreApplyFormFillUserApprovalProcessRecord> list = coreApplyFormFillUserApprovalProcessRecordService.list(
                Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                        .eq(CoreApplyFormFillUserApprovalProcessRecord::getFillUserId, fillUser.getId())
                        .eq(CoreApplyFormFillUserApprovalProcessRecord::getApprovalId, dto.getApprovalId())
                        .orderByAsc(CoreApplyFormFillUserApprovalProcessRecord::getSort));
        // 获取当前审核数据
        CoreApplyFormFillUserApprovalProcessRecord processRecord = new CoreApplyFormFillUserApprovalProcessRecord();
        for (CoreApplyFormFillUserApprovalProcessRecord record : list) {
            if (record.getApprovalResult() == 0) {
                processRecord = record;
                break;
            }
        }
        // 保存审核流程记录
        processRecord.setApprovalResult(dto.getApprovalResult() == 0 ? 2 : 1);
        processRecord.setApprovalReason(dto.getApprovalReason());
        processRecord.setSignPic(dto.getSignPic());
        processRecord.setAuditTime(LocalDateTime.now());
        processRecord.setUpdateDate(LocalDateTime.now());
        coreApplyFormFillUserApprovalProcessRecordService.updateById(processRecord);
        // 查询对应的用户审核流程
        CoreApplyFormFillUserApprovalProcess userApprovalProcess =
                coreApplyFormFillUserApprovalProcessService.getById(processRecord.getUserProcessId());
        // 查询审核流程具体信息
        CoreApprovalProcess approvalProcess = coreApprovalProcessService.getById(userApprovalProcess.getProcessId());

        sendStaffNoticeDTO.setPreStaffName(processRecord.getApprovalName());
        // 查询角色名称
        List<String> roleNames = new ArrayList<>();
        List<Integer> teacherRoleTypeList = remoteStaffService
                .listStaffRolesByStaffId(processRecord.getApprovalId()).getData();
        if (teacherRoleTypeList.contains(1)) {
            roleNames.add(RoleName.CAMPUS.getName());
        } else if (teacherRoleTypeList.contains(2)) {
            roleNames.add(RoleName.GRADE.getName());
        } else if (teacherRoleTypeList.contains(3)) {
            roleNames.add(RoleName.MASTER.getName());
        } else if (teacherRoleTypeList.contains(4)) {
            roleNames.add(RoleName.COURSE.getName());
        } else if (teacherRoleTypeList.contains(5)) {
            roleNames.add(RoleName.SECTION.getName());
        } else {
            roleNames.add(RoleName.TEACHER.getName());
        }
        sendStaffNoticeDTO.setPreStaffRoleName(StrUtil.join("/", roleNames));
        // 或审
        if (ObjectUtil.equals(AuditModeEnum.OR_AUDIT.getMode(), approvalProcess.getApprovalType())) {
            userApprovalProcess.setExamineStatus(dto.getApprovalResult() == 0 ? 2 : 1);
            userApprovalProcess.setAuditTime(LocalDateTime.now());
            // 查询用户下一个审核流程
            CoreApplyFormFillUserApprovalProcess nextUserApprovalProcess = coreApplyFormFillUserApprovalProcessService
                    .getOne(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcess())
                            .eq(CoreApplyFormFillUserApprovalProcess::getFillUserId, fillUser.getId())
                            .eq(CoreApplyFormFillUserApprovalProcess::getSort, userApprovalProcess.getSort() + 1));
            // 用户填报信息
            CoreApplyFormFillUser saveFillUser = new CoreApplyFormFillUser();
            saveFillUser.setId(fillUser.getId());
            // 无下一个用户审核流程则表示审核完毕
            if (Objects.isNull(nextUserApprovalProcess)) {
                // 审核通过
                if (ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), dto.getApprovalResult())) {
                    saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_PASS.getResult());
                } else {
                    // 审核不通过
                    saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_NO.getResult());
                    saveFillUser.setRefuseReason(dto.getRefuseReason());
                }
                saveFillUser.setAuditTime(LocalDateTime.now());
            } else {
                // 有下一个用户审核流程
                if (ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), dto.getApprovalResult())) {
                    // 当前节点审核通过, 用户修改为审核中
                    saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_ING.getResult());
                    // 查询下一个审核节点的审核人信息
                    List<CoreApplyFormFillUserApprovalProcessRecord> nextAppUser = coreApplyFormFillUserApprovalProcessRecordService.list(
                            Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                                    .eq(CoreApplyFormFillUserApprovalProcessRecord::getUserProcessId, nextUserApprovalProcess.getId()));
                    nextAppUser.forEach(record -> {
                        // 发送提示审核消息
                        EduStaff staff = remoteStaffService.getStaff(record.getApprovalId()).getData();
                        sendStaffNoticeDTO.setStaffWxId(staff.getWxId());
                        sendStaffNoticeDTO.setStaffName(staff.getName());
                        sendStaffNoticeDTO.setSchoolType(school.getSchoolType());
                        sendNoticeService.sendStaffNotice(sendStaffNoticeDTO, 0);
                    });
                } else {
                    // 审核不通过
                    saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_NO.getResult());
                    saveFillUser.setRefuseReason(dto.getRefuseReason());
                    saveFillUser.setAuditTime(LocalDateTime.now());
                }
            }
            coreApplyFormFillUserService.updateById(saveFillUser);
            // 给家长发送审核结果信息
            if (ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), saveFillUser.getExamineStatus())
                    || ObjectUtil.equals(ApprovalResultEnum.AUDIT_NO.getResult(), saveFillUser.getExamineStatus())) {
                CoreApplyFormFillUser user = coreApplyFormFillUserService.getById(saveFillUser.getId());
                sendNoticeService.sendParentNotice(
                        SendParentNoticeDTO.builder()
                                .school(school)
                                .student(student)
                                .examineStatus(saveFillUser.getExamineStatus())
                                .createTime(user.getCreateDate())
                                .formId(fillUser.getApplyFormId())
                                .fillUserId(user.getId())
                                .build()
                );
            }
        } else {
            // 会审
            // 本次审核流程对应的全部审核人员
            List<CoreApplyFormFillUserApprovalProcessRecord> recordList = coreApplyFormFillUserApprovalProcessRecordService
                    .list(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getUserProcessId, processRecord.getUserProcessId())
                            .eq(CoreApplyFormFillUserApprovalProcessRecord::getFillUserId, fillUser.getId()));
            // 已通过的人员
            List<CoreApplyFormFillUserApprovalProcessRecord> passRecordList = recordList.stream()
                    .filter(x -> ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), x.getApprovalResult()))
                    .collect(Collectors.toList());
            // 用户填报信息
            CoreApplyFormFillUser saveFillUser = new CoreApplyFormFillUser();
            saveFillUser.setId(fillUser.getId());
            // 审核通过
            if (ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), dto.getApprovalResult())) {
                // 本次流程全部审核通过
                if (recordList.size() == passRecordList.size()) {
                    // 查询用户下一个审核流程
                    CoreApplyFormFillUserApprovalProcess nextUserApprovalProcess = coreApplyFormFillUserApprovalProcessService
                            .getOne(Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcess())
                                    .eq(CoreApplyFormFillUserApprovalProcess::getFillUserId, fillUser.getId())
                                    .eq(CoreApplyFormFillUserApprovalProcess::getSort, userApprovalProcess.getSort() + 1));
                    // 无下一个用户审核流程则表示审核完毕
                    if (Objects.isNull(nextUserApprovalProcess)) {
                        saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_PASS.getResult());
                        saveFillUser.setAuditTime(LocalDateTime.now());
                        // 给家长发送审核结果信息
                        CoreApplyFormFillUser user = coreApplyFormFillUserService.getById(saveFillUser.getId());
                        sendNoticeService.sendParentNotice(
                                SendParentNoticeDTO.builder()
                                        .school(school)
                                        .student(student)
                                        .examineStatus(saveFillUser.getExamineStatus())
                                        .createTime(user.getCreateDate())
                                        .formId(fillUser.getApplyFormId())
                                        .fillUserId(user.getId())
                                        .build()
                        );
                    } else {
                        // 有下一个用户审核流程
                        // 当前节点审核通过, 用户修改为审核中
                        saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_ING.getResult());
                        // 查询下一个审核节点的审核人信息
                        List<CoreApplyFormFillUserApprovalProcessRecord> nextAppUser = coreApplyFormFillUserApprovalProcessRecordService.list(
                                Wrappers.lambdaQuery(new CoreApplyFormFillUserApprovalProcessRecord())
                                        .eq(CoreApplyFormFillUserApprovalProcessRecord::getUserProcessId, nextUserApprovalProcess.getId()));
                        nextAppUser.forEach(record -> {
                            // 发送提示审核消息
                            EduStaff staff = remoteStaffService.getStaff(record.getApprovalId()).getData();
                            sendStaffNoticeDTO.setStaffWxId(staff.getWxId());
                            sendStaffNoticeDTO.setStaffName(staff.getName());
                            sendStaffNoticeDTO.setSchoolType(school.getSchoolType());
                            sendNoticeService.sendStaffNotice(sendStaffNoticeDTO, 0);
                        });
                    }
                    // 当前用户审核流程修改为通过
                    userApprovalProcess.setExamineStatus(ApprovalResultEnum.AUDIT_PASS.getResult());
                    userApprovalProcess.setAuditTime(LocalDateTime.now());
                } else {
                    // 本次流程还有未审核通过的人员
                    userApprovalProcess.setExamineStatus(ApprovalResultEnum.AUDIT_ING.getResult()); //当前流程审核中
                    userApprovalProcess.setAuditTime(LocalDateTime.now());
                    // 当前人员修改为审核中
                    saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_ING.getResult());
                }
            } else {
                // 审核不通过
                saveFillUser.setExamineStatus(ApprovalResultEnum.AUDIT_NO.getResult());
                saveFillUser.setRefuseReason(dto.getRefuseReason());
                saveFillUser.setAuditTime(LocalDateTime.now());
                // 当前用户审核流程修改为不通过
                userApprovalProcess.setExamineStatus(ApprovalResultEnum.AUDIT_NO.getResult());
                userApprovalProcess.setAuditTime(LocalDateTime.now());
                // 给家长发送审核结果信息
                CoreApplyFormFillUser user = coreApplyFormFillUserService.getById(saveFillUser.getId());
                sendNoticeService.sendParentNotice(
                        SendParentNoticeDTO.builder()
                                .school(school)
                                .student(student)
                                .examineStatus(saveFillUser.getExamineStatus())
                                .createTime(user.getCreateDate())
                                .formId(fillUser.getApplyFormId())
                                .fillUserId(user.getId())
                                .build()
                );
            }
            coreApplyFormFillUserService.updateById(saveFillUser);
        }
        coreApplyFormFillUserApprovalProcessService.updateById(userApprovalProcess);
    }
}
