package yangtz.cs.liu.campus.service.impl.examination;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.constant.ArtExamConstant;
import yangtz.cs.liu.campus.domain.examination.*;
import yangtz.cs.liu.campus.mapper.examination.*;
import yangtz.cs.liu.campus.service.examination.ISchoolArtStudentService;
import com.ruoyi.common.core.domain.model.WebLoginBody;
import yangtz.cs.liu.campus.vo.examination.ArtAndEduStudentVo;
import yangtz.cs.liu.campus.vo.examination.SchoolArtStudentVo;
import yangtz.cs.liu.webpage.domain.WebRegisterBody;
import yangtz.cs.liu.webpage.vo.ArtAdmissionTicketVo;
import yangtz.cs.liu.campus.vo.examination.ArtEduStudentVo;
import yangtz.cs.liu.webpage.vo.QueryScoreVo;
import yangtz.cs.liu.webpage.vo.WebSchoolArtStudentVo;

import java.util.*;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;

@Service
public class SchoolArtStudentServiceImpl extends ServiceImpl<SchoolArtStudentMapper, SchoolArtStudent> implements ISchoolArtStudentService {
    @Autowired
    private SchoolArtStudentMapper artStudentMapper;

    @Autowired
    private SchoolArtExamMapper artExamMapper;

    @Autowired
    private SchoolArtRelationMapper artRelationMapper;

    @Autowired
    private SchoolTestProjectMapper projectMapper;

    @Autowired
    private JuniorHighSchoolMapper schoolMapper;

    @Autowired
    private EduArtStudentMapper eduArtStudentMapper;

    @Override
    public String register(WebRegisterBody registerBody) {
        String msg = "", studentName = registerBody.getStudentName(), idCard = registerBody.getIdCard(), phoneNumber = registerBody.getPhoneNumber(), password = registerBody.getPassword();
        SchoolArtStudent student = new SchoolArtStudent();
        student.setIdCard(idCard);
        student.setPhoneNumber(phoneNumber);

        if (StringUtils.isEmpty(studentName)) {
            msg = "姓名不能为空";
        } else if (StringUtils.isEmpty(idCard)) {
            msg = "身份证号不能为空";
        } else if (StringUtils.isEmpty(phoneNumber)) {
            msg = "手机号不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (studentName.length() < UserConstants.USERNAME_MIN_LENGTH
                || studentName.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "姓名长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (idCard.length() != 18) {
            msg = "身份证号长度必须为18位";
        } else if (phoneNumber.length() != 11) {
            msg = "手机号长度必须为11位";
        }
        /*else if (UserConstants.NOT_UNIQUE.equals(checkPhoneUnique(student)))
        {
            msg = "保存学生'" + studentName + "'失败，手机号已存在";
        }*/
        else if (UserConstants.NOT_UNIQUE.equals(checkIdCardUnique(student))) {
            msg = "保存学生'" + studentName + "'失败，身份证号已存在";
        } else {
            student.setStudentName(studentName);
            student.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = artStudentMapper.insert(student) > 0 ? true : false;
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(studentName, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    //身份证唯一，手机号不唯一
    @Override
    public WebLoginBody login(WebRegisterBody webRegisterBody) {
        WebLoginBody loginBody = new WebLoginBody();
        SchoolArtStudent student = artStudentMapper.getStudentByPhoneNumber(webRegisterBody.getPhoneNumber(), webRegisterBody.getIdCard());
        if (StringUtils.isNull(student)) {
            throw new ServiceException("登录用户：" + webRegisterBody.getIdCard() + "不存在");
        }
        if (!SecurityUtils.matchesPassword(webRegisterBody.getPassword(), student.getPassword())) {
            throw new ServiceException("密码错误");
        }
        loginBody.setId(student.getId());
        loginBody.setIdCard(student.getIdCard());
        loginBody.setPhoneNumber(student.getPhoneNumber());
        loginBody.setStudentName(student.getStudentName());
        loginBody.setPassword(student.getPassword());
        return loginBody;
    }

    /**
     * 判断能不能点进去进入按钮
     * 1能 0不能
     * 当前状态（0=报名，1=待审核，2=通过，3=驳回，4=信息修改，5=准考证打印，6=成绩查询，7=审核）
     */
    @Override
    public int enterBtn(Long studentId, Long testId) {
        //获取考试详情
        SchoolArtExam exam = artExamMapper.selectById(testId);
        //获取学生与考试关系，是否报名
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(testId, studentId);
        //未报名
        if (StringUtils.isNull(relation)) {
            //未报名，查询不到信息，且考试状态为报名阶段（信息审核）可以进去报名
            if (ArtExamConstant.INFOCHECK.equals(exam.getStatus())) {
                return 1;
            } else if (ArtExamConstant.ADDRESS.equals(exam.getStatus())) {
                //未报名，查询不到信息，且考试状态为考场分配，不能进入，因为考试报名审核已截止
                return 0;
            } else if (ArtExamConstant.SCORE.equals(exam.getStatus())) {
                //未报名，查询不到信息，且考试状态为成绩发布
                return 0;
            } else {
                //未报名，查询不到信息，且考试状态为结束
                return 0;
            }
        } else {
            //可以查到考生和考试的关系
            //提交状态为未提交，也就是未报名
            if (ArtExamConstant.NOSUBMIT.equals(relation.getSubmit())) {
                if (ArtExamConstant.INFOCHECK.equals(exam.getStatus())) {
                    //未提交信息，考试状态为审核，可以进入
                    return 1;
                } else if (ArtExamConstant.ADDRESS.equals(exam.getStatus())) {
                    //未报名，查询不到信息，且考试状态为考场分配，不可进入
                    return 0;
                } else if (ArtExamConstant.SCORE.equals(exam.getStatus())) {
                    //未报名，查询不到信息，且考试状态为成绩发布
                    return 0;
                } else {
                    //未报名，查询不到信息，且考试状态为结束
                    return 0;
                }
            } else {
                //提交状态为已提交，
                if (ArtExamConstant.INFOCHECK.equals(exam.getStatus())) {
                    //考试状态为信息审核阶段
                    return 1;
                } else if (ArtExamConstant.ADDRESS.equals(exam.getStatus())) {
                    //考试状态为考场分配
                    return 1;
                } else if (ArtExamConstant.SCORE.equals(exam.getStatus())) {
                    //考试状态为成绩发布
                    return 1;
                } else {
                    //考试状态为结束
                    return 1;
                }
            }
        }
    }

    @Override
    public WebSchoolArtStudentVo getInfo(Long id) {
        return artStudentMapper.getInfo(id);
    }

    @Override
    public WebSchoolArtStudentVo getStuInfo(Long id, Long examId) {
        return artStudentMapper.getStuInfo(id, examId);
    }

    //根据考试id和考生id获取准考证信息(前提是当前学生已通过审核，且考试状态位于成绩发布)
    @Override
    public ArtAdmissionTicketVo getTicket(Long studentId, Long examId) {
        ArtAdmissionTicketVo vo = new ArtAdmissionTicketVo();
        //获取考试详情
        SchoolArtExam exam = artExamMapper.selectById(examId);
        //获取考生信息
        SchoolArtStudent student = artStudentMapper.selectById(studentId);
        //获取考试和考生关系（此表中包含考试时间地点等）
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(examId, studentId);
        //测试项目
        SchoolTestProject project = projectMapper.selectById(relation.getTestId());
        //毕业学校
        JuniorHighSchool school = schoolMapper.selectById(relation.getJuniorId());

        vo.setExamName(exam.getExamName());
        vo.setNotice(exam.getNotice());
        vo.setStudentName(student.getStudentName());
        vo.setExamNumber(relation.getExamNumber());

        if (StringUtils.isNotNull(project)) {
            vo.setProject(project.getProject());
        }
        vo.setInGroup(relation.getInGroup());
        vo.setPhoneNumber(student.getPhoneNumber());

        if (StringUtils.isNotNull(school)) {
            vo.setSchoolName(school.getSchoolName());
        }
        vo.setPhoto(student.getPhoto());
        //"yyyy-MM-dd"考试日期
        Date d = relation.getExamDate();
        Calendar ca = Calendar.getInstance();
        ca.setTime(d);
        vo.setExamYear(ca.get(Calendar.YEAR));
        int day = ca.get(Calendar.DAY_OF_MONTH);
        int month = ca.get(Calendar.MONTH) + 1;//第几个月 8
        //考试时间 HH:mm
        String t = relation.getExamTime();
        int hour = Integer.parseInt(StringUtils.substringBefore(t, ":"));
        //判断是上午还是下午，小于12为上午，其余为下午
        String examDate = "";
        if (hour < 12) {
            examDate = month + "月" + day + "日上午";
        } else {
            examDate = month + "月" + day + "日下午";
        }
        vo.setExamDate(examDate);
        vo.setExamTime(t + "开始");
        vo.setExamAddress(relation.getExamAddress());
        return vo;
    }

    @Override
    public QueryScoreVo getScore(Long studentId, Long examId) {
        QueryScoreVo vo = new QueryScoreVo();
        //获取考试详情
        SchoolArtExam exam = artExamMapper.selectById(examId);
        //获取考生信息
        SchoolArtStudent student = artStudentMapper.selectById(studentId);
        //获取考试和考生关系（此表中包含考试时间地点等）
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(examId, studentId);
        //测试项目
        SchoolTestProject project = projectMapper.selectById(relation.getTestId());
        vo.setExamName(exam.getExamName());
        vo.setExamYear(exam.getExamYear());
        vo.setStudentName(student.getStudentName());
        vo.setStudentNumber(student.getStudentNumber());
        vo.setExamNumber(relation.getExamNumber());
        vo.setIdCard(student.getIdCard());
        if (StringUtils.isNotNull(project)) {
            //设置类别
            String type = "";
            switch (project.getType()) {
                case "0":
                    type = "体育";
                    break;
                case "1":
                    type = "音乐";
                    break;
                case "2":
                    type = "美术";
                    break;
                case "3":
                    type = "书法";
            }
            vo.setExamSort(type);
            vo.setExamProject(project.getProject());
        }
        vo.setScore(relation.getScore());
        vo.setResult(relation.getResult());
        vo.setPassScore(relation.getPassScore());
        return vo;
    }

    /**
     * 考生报名-暂存
     * 修改考生表
     * 首先判断该考生和该考试是否有relation，没有的话则要新增一份该考试考生关系数据
     * 此时存考试id，考生id，身份证，提交状态（0未提交）
     * 如果存在该考试考生关系数据，则对比身份证是否改变，修改了则修改关系表对应字段即可
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int webSave(Long examId, WebSchoolArtStudentVo student) {
        //判断考试所在节点，如果不是审核阶段则不能暂存
        SchoolArtExam exam = artExamMapper.selectById(examId);
        if (!ArtExamConstant.INFOCHECK.equals(exam.getStatus())) {
            throw new ServiceException("报名、审核阶段已过，暂时无法暂存信息");
        }
        //修改学生信息
        SchoolArtStudent s = artStudentMapper.selectById(student.getId());
        //BeanUtils.copyProperties(student,s);
        s.setStudentNumber(student.getStudentNumber());
        s.setSex(student.getSex());
        s.setHeight(student.getHeight());
        s.setWeight(student.getWeight());
        s.setTelephone1(student.getTelephone1());
        s.setTelephone2(student.getTelephone2());
        s.setPhoto(student.getPhoto());
        s.setUpdateTime(DateUtils.getNowDate());
        artStudentMapper.updateById(s);
        //获取考试考生关系
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(examId, student.getId());
        //暂无关系，则一份关系
        if (StringUtils.isNull(relation)) {
            relation = new SchoolArtRelation();
            relation.setExamId(examId);
            relation.setStudentId(student.getId());
            relation.setInfoIdCard(student.getIdCard());
            relation.setJuniorId(student.getJuniorId());
            relation.setTestId(student.getTestId());
            relation.setSubmit(ArtExamConstant.NOSUBMIT);
            relation.setCreateTime(DateUtils.getNowDate());
            return artRelationMapper.insert(relation);
        }
        //身份证号、初中学校、测试项目改变
        relation.setInfoIdCard(student.getIdCard());
        relation.setJuniorId(student.getJuniorId());
        relation.setTestId(student.getTestId());
        relation.setUpdateTime(DateUtils.getNowDate());
        return artRelationMapper.updateById(relation);
    }

    /**
     * 考生报名-提交
     * 修改考生表
     * 首先判断该考生和该考试是否有relation，没有的话则要新增一份该考试考生关系数据
     * 此时存考试id，考生id，身份证，提交状态（1已提交），审核状态为3=待审核
     * 如果存在该考试考生关系数据， 修改身份证号，提交状态（1已提交）,审核状态为3=待审核，修改关系表即可
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int webSubmit(Long examId, WebSchoolArtStudentVo student) {
        //判断考试所在节点，如果不是审核阶段则不能提交
        SchoolArtExam exam = artExamMapper.selectById(examId);
        if (!ArtExamConstant.INFOCHECK.equals(exam.getStatus())) {
            throw new ServiceException("报名、审核阶段已过，暂时无法提交信息");
        }
        //修改学生信息
        SchoolArtStudent s = artStudentMapper.selectById(student.getId());
        //BeanUtils.copyProperties(student,s);
        s.setStudentNumber(student.getStudentNumber());
        s.setSex(student.getSex());
        s.setHeight(student.getHeight());
        s.setWeight(student.getWeight());
        s.setTelephone1(student.getTelephone1());
        s.setTelephone2(student.getTelephone2());
        s.setPhoto(student.getPhoto());
        s.setUpdateTime(DateUtils.getNowDate());
        artStudentMapper.updateById(s);
        //获取考试考生关系
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(examId, student.getId());
        //暂无关系，则新增一份关系
        if (StringUtils.isNull(relation)) {
            relation = new SchoolArtRelation();
            relation.setExamId(examId);
            relation.setStudentId(student.getId());
            relation.setInfoIdCard(student.getIdCard());
            relation.setJuniorId(student.getJuniorId());
            relation.setTestId(student.getTestId());
            relation.setSubmit(ArtExamConstant.SUBMIT);
            relation.setAuditStatus(ArtExamConstant.CHECK);
            relation.setCreateTime(DateUtils.getNowDate());
            return artRelationMapper.insert(relation);
        }
        relation.setInfoIdCard(student.getIdCard());
        relation.setJuniorId(student.getJuniorId());
        relation.setTestId(student.getTestId());
        relation.setSubmit(ArtExamConstant.SUBMIT);
        relation.setAuditStatus(ArtExamConstant.CHECK);
        relation.setUpdateTime(DateUtils.getNowDate());
        return artRelationMapper.updateById(relation);
    }

    /**
     * 教务管理-考试管理-信息审核列表
     */
    @Override
    public List<ArtEduStudentVo> getInfoCheck(ArtEduStudentVo vo) {
        //结果集 ,获取到了所有考试考生关系及报名学生的信息
        List<ArtEduStudentVo> voList = artRelationMapper.getInfoCheck(vo);
        //获取教育局考生信息
        LambdaQueryWrapper<EduArtStudent> eduLqw = new LambdaQueryWrapper<>();
        eduLqw.eq(EduArtStudent::getExamId, vo.getExamId());
        List<EduArtStudent> eduArtStudentList = eduArtStudentMapper.selectList(eduLqw);
        if (StringUtils.isNotNull(eduArtStudentList) && eduArtStudentList.size() > 0) {
            //遍历教育局学生信息，将其值整到对应结果集对象信息，若根据身份证号匹配不到，就新建个对象放到结果集中
            for (EduArtStudent eduArtStudent : eduArtStudentList) {
                //判断能否根据身份证号匹配上
                boolean flag = true;
                for (ArtEduStudentVo studentVo : voList) {
                    //若可以匹配上
                    if (eduArtStudent.getEduIdCard().equals(studentVo.getInfoIdCard())) {
                        flag = false;
                        //设置结果集对应教育局信息
                        studentVo.setEduIdCard(eduArtStudent.getEduIdCard());
                        studentVo.setEduStudentName(eduArtStudent.getEduStudentName());
                        studentVo.setEduStudentNumber(eduArtStudent.getEduStudentNumber());
                        studentVo.setEduSchoolName(eduArtStudent.getEduSchoolName());
                        studentVo.setEduProject(eduArtStudent.getEduProject());
                        studentVo.setEduSex(eduArtStudent.getEduSex());
                        break;
                    }
                }
                if (flag) {
                    //说明没有报名信息可以和教育局信息匹配上，需要新增一条数据
                    ArtEduStudentVo studentVo = new ArtEduStudentVo();
                    studentVo.setExamId(vo.getExamId());
                    studentVo.setInfoIdCard(eduArtStudent.getEduIdCard());
                    studentVo.setEduIdCard(eduArtStudent.getEduIdCard());
                    studentVo.setEduStudentName(eduArtStudent.getEduStudentName());
                    studentVo.setEduStudentNumber(eduArtStudent.getEduStudentNumber());
                    studentVo.setEduSchoolName(eduArtStudent.getEduSchoolName());
                    studentVo.setEduProject(eduArtStudent.getEduProject());
                    studentVo.setEduSex(eduArtStudent.getEduSex());
                    voList.add(studentVo);
                }
            }
        }

        //设置匹配状态
        List<ArtEduStudentVo> list = setState(voList);
        //通过模糊查询过滤，匹配状态，审核状态，姓名（对应学生自己的报名信息），身份证号
        if (StringUtils.isNotNull(vo.getMatchStatus())) {
            list = list.stream().filter(a -> a.getMatchStatus().equals(vo.getMatchStatus())).collect(Collectors.toList());
        }
        if (StringUtils.isNotNull(vo.getAuditStatus())) {
            list = list.stream().filter(a -> a.getAuditStatus().equals(vo.getAuditStatus())).collect(Collectors.toList());
        }
        if (StringUtils.isNotNull(vo.getStudentName())) {
            list = list.stream().filter(a -> a.getStudentName().contains(vo.getStudentName())).collect(Collectors.toList());
        }
        if (StringUtils.isNotNull(vo.getInfoIdCard())) {
            list = list.stream().filter(a -> a.getInfoIdCard().contains(vo.getInfoIdCard())).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editArtAndEdu(Long examId, ArtAndEduStudentVo student) {
        //修改学生信息
        SchoolArtStudent s = new SchoolArtStudent();
        BeanUtils.copyProperties(student, s);
        s.setId(student.getId());
        s.setCreateBy(student.getCreateBy());
        s.setCreateTime(student.getCreateTime());
        s.update();
        artStudentMapper.updateById(s);

        //获取考试考生关系
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(examId, student.getId());
        //身份证号改变
        relation.setInfoIdCard(student.getIdCard());
        relation.setJuniorId(student.getJuniorId());
        relation.setTestId(student.getTestId());
        relation.update();
        artRelationMapper.updateById(relation);

        //教育局信息修改
        LambdaQueryWrapper<EduArtStudent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduArtStudent::getExamId,examId).eq(EduArtStudent::getEduIdCard,student.getIdCard());
        List<EduArtStudent> list = eduArtStudentMapper.selectList(lqw);
        //存在 1条教育局信息
        if(StringUtils.isNotNull(list) && list.size() > 0){
            //修改
            EduArtStudent edu = list.get(0);
            edu.setEduStudentName(student.getEduStudentName());
            edu.setEduStudentNumber(student.getEduStudentNumber());
            edu.setEduJuniorId(student.getEduJuniorId());
            edu.setEduSchoolName(student.getEduSchoolName());
            edu.setEduTestId(student.getEduTestId());
            edu.setEduProject(student.getEduProject());
            edu.setEduSex(student.getEduSex());
            edu.update();
            return eduArtStudentMapper.updateById(edu);
        }else {
            //不存在，新增对应教育局信息
            EduArtStudent edu = new EduArtStudent();
            edu.setExamId(examId);
            //赋值学生的身份证号
            edu.setEduIdCard(student.getIdCard());
            edu.setEduStudentName(student.getEduStudentName());
            edu.setEduStudentNumber(student.getEduStudentNumber());
            edu.setEduJuniorId(student.getEduJuniorId());
            edu.setEduSchoolName(student.getEduSchoolName());
            edu.setEduTestId(student.getEduTestId());
            edu.setEduProject(student.getEduProject());
            edu.setEduSex(student.getEduSex());
            edu.insert();
            return eduArtStudentMapper.insert(edu);
        }
    }

    /**
     * 教务管理-考试管理-信息审核-修改
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int edit(Long examId, WebSchoolArtStudentVo student) {
        //修改学生信息
        SchoolArtStudent s = new SchoolArtStudent();
        BeanUtils.copyProperties(student, s);
        s.setId(student.getId());
        s.setCreateBy(student.getCreateBy());
        s.setCreateTime(student.getCreateTime());
        s.update();
        artStudentMapper.updateById(s);

        //获取考试考生关系
        SchoolArtRelation relation = artRelationMapper.getRelationByIds(examId, student.getId());
        //身份证号改变
        relation.setInfoIdCard(student.getIdCard());
        relation.setJuniorId(student.getJuniorId());
        relation.setTestId(student.getTestId());
        return artRelationMapper.updateById(relation);
    }

    /**
     * 教务管理-考试管理-信息审核-导出报名信息
     */
    @Override
    public List<SchoolArtStudentVo> editExport(List<Long> idList, Long examId) {
        List<SchoolArtStudentVo> list = artStudentMapper.editExport(idList, examId);
        //序号
        int i = 1;
        for (SchoolArtStudentVo student : list) {
            student.setXh(i);
            i++;
        }
        return list;
    }

    /**
     * 教务管理-考试管理-通过
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String pass(Long examId, List<Long> studentIds) {
        // 准备记录日志数据
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        //查询出所有studentIds对应的学生信息
        List<SchoolArtStudentVo> list = artStudentMapper.editExport(studentIds, examId);
        //选中的有效学生信息总数
        int allNum = list.size();
        for (SchoolArtStudentVo student : list) {
            //根据考试id，和学生身份证号查出教育局学生信息进行比对
            EduArtStudent eduArtStudent = eduArtStudentMapper.getStudent(examId, student.getIdCard());
            boolean flag = true;
            if (StringUtils.isNotNull(eduArtStudent)) {
                //匹配学生和教育局信息
                if (!student.getStudentName().equals(eduArtStudent.getEduStudentName())) {
                    flag = false;
                }
                if (!student.getStudentNumber().equals(eduArtStudent.getEduStudentNumber())) {
                    flag = false;
                }
                if (!student.getSchoolName().equals(eduArtStudent.getEduSchoolName())) {
                    flag = false;
                }
                if (!student.getProject().equals(eduArtStudent.getEduProject())) {
                    flag = false;
                }
                if (!student.getSex().equals(eduArtStudent.getEduSex())) {
                    flag = false;
                }
                if (flag) {
                    //全部都匹配
                    //判断状态是否已是通过
                    LambdaQueryWrapper<SchoolArtRelation> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(SchoolArtRelation::getExamId, examId).eq(SchoolArtRelation::getStudentId, student.getId());
                    SchoolArtRelation relation = artRelationMapper.selectList(lqw).get(0);
                    if (ArtExamConstant.REJECT.equals(relation.getAuditStatus())) {
                        failureNum++;
                        successMsg.append("<br/>" + "身份证号为" + student.getIdCard() + "的学生信息已驳回，无法通过；");
                    } else if (ArtExamConstant.PASS.equals(relation.getAuditStatus())) {
                        failureNum++;
                        successMsg.append("<br/>" + "身份证号为" + student.getIdCard() + "的学生信息已通过，无法再次通过；");
                    } else if (ArtExamConstant.EDIT.equals(relation.getAuditStatus())) {
                        failureNum++;
                        successMsg.append("<br/>" + "身份证号为" + student.getIdCard() + "的学生信息已退回修改，没有再次提交申请，无法通过；");
                    } else {
                        relation.setAuditStatus(ArtExamConstant.PASS);
                        artRelationMapper.updateById(relation);
                        successNum++;
                    }
                } else {
                    //存在教育局信息，但是没有匹配上
                    failureNum++;
                    successMsg.append("<br/>" + "身份证号为" + student.getIdCard() + "的学生,信息不匹配，无法通过；");
                }
            } else {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + student.getIdCard() + "的学生,无教育局信息，无法通过；");
            }
        }
        if(allNum != successNum){
            //存在无法通过的数据
            successMsg.insert(0, "选中的有效数据共 <span style='color: red;font-size: 20px; font-weight:bold'>" + allNum + "</span> 条(排除所有未报名的数据)，已将选中数据中所有匹配的、待审核的 <span style='color: red;font-size: 20px; font-weight:bold'>"+ successNum +"</span> 条数据的状态改为通过！有 <span style='color: red;font-size: 20px; font-weight:bold'>" + failureNum + "</span> 条不符合条件的数据，不通过的理由如下：");
            return successMsg.toString();
        }else {
            return "恭喜您，已将选中的所有有效数据(排除所有未报名的数据)的状态改为通过！共 <span style='color: red;font-size: 20px; font-weight:bold'>" + allNum + " </span> 条";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int passOne(Long examId, Long studentId) {
        //查询出所有studentIds对应的学生信息
        WebSchoolArtStudentVo vo = artStudentMapper.getStuInfo(studentId, examId);

        //根据考试id，和学生身份证号查出教育局学生信息进行比对
        EduArtStudent eduArtStudent = eduArtStudentMapper.getStudent(examId, vo.getIdCard());
        boolean flag = true;
        if (StringUtils.isNotNull(eduArtStudent)) {
            //匹配学生和教育局信息
            if (!vo.getStudentName().equals(eduArtStudent.getEduStudentName())) {
                flag = false;
            }
            if (!vo.getStudentNumber().equals(eduArtStudent.getEduStudentNumber())) {
                flag = false;
            }
            if (!vo.getSchoolName().equals(eduArtStudent.getEduSchoolName())) {
                flag = false;
            }
            if (!vo.getProject().equals(eduArtStudent.getEduProject())) {
                flag = false;
            }
            if (!vo.getSex().equals(eduArtStudent.getEduSex())) {
                flag = false;
            }
            if (flag) {
                //全部都匹配
                //判断状态是否已是通过
                LambdaQueryWrapper<SchoolArtRelation> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SchoolArtRelation::getExamId, examId).eq(SchoolArtRelation::getStudentId, vo.getId());
                SchoolArtRelation relation = artRelationMapper.selectList(lqw).get(0);
                if (ArtExamConstant.REJECT.equals(relation.getAuditStatus())) {
                    throw new ServiceException("身份证号为" + vo.getIdCard() + "的学生信息已驳回，无法通过");
                } else if (ArtExamConstant.PASS.equals(relation.getAuditStatus())) {
                    throw new ServiceException("身份证号为" + vo.getIdCard() + "的学生信息已通过，无法再次通过");
                } else if (ArtExamConstant.EDIT.equals(relation.getAuditStatus())) {
                    throw new ServiceException("身份证号为" + vo.getIdCard() + "的学生信息已退回修改，没有再次提交申请，无法通过");
                } else {
                    relation.setAuditStatus(ArtExamConstant.PASS);
                    return artRelationMapper.updateById(relation);
                }
            } else {
                //存在教育局信息，但是没有匹配上
                throw new ServiceException("身份证号为" + vo.getIdCard() + "的学生,信息不匹配，无法通过");
            }
        } else {
            throw new ServiceException("身份证号为" + vo.getIdCard() + "的学生,无教育局信息，无法通过");
        }
    }

    /**
     * 教务管理-考试管理-退回修改
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public  String back(Long examId, List<Long> studentIds) {
        // 准备记录日志数据
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        //查询出所有studentIds对应的学生信息
        LambdaQueryWrapper<SchoolArtRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolArtRelation::getExamId, examId).in(SchoolArtRelation::getStudentId, studentIds);
        List<SchoolArtRelation> list = artRelationMapper.selectList(lqw);
        //选中的有效学生信息总数
        int allNum = list.size();
        for (SchoolArtRelation relation : list) {
            if (ArtExamConstant.REJECT.equals(relation.getAuditStatus())) {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + relation.getInfoIdCard() + "的学生信息已驳回，无法退回修改；");
            } else if (ArtExamConstant.PASS.equals(relation.getAuditStatus())) {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + relation.getInfoIdCard() + "的学生信息已通过，无法退回修改；");
            } else if (ArtExamConstant.EDIT.equals(relation.getAuditStatus())) {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + relation.getInfoIdCard() + "的学生信息已退回修改，没有再次提交申请，无法再次退回修改；");
            } else {
                relation.setAuditStatus(ArtExamConstant.EDIT);
                artRelationMapper.updateById(relation);
                successNum++;
            }
        }
        if(allNum != successNum){
            //存在无法退回修改的数据
            successMsg.insert(0, "选中的有效数据共 <span style='color: red;font-size: 20px; font-weight:bold'>" + allNum + "</span> 条(排除所有未报名的数据)，已将选中数据中所有匹配的、待审核的 <span style='color: red;font-size: 20px; font-weight:bold'>"+ successNum +"</span> 条数据的状态改为退回修改！有 <span style='color: red;font-size: 20px; font-weight:bold'>" + failureNum + "</span> 条不符合条件的数据，无法退回修改的理由如下：");
            return successMsg.toString();
        }else {
            return "恭喜您，已将选中的所有有效数据(排除所有未报名的数据)的状态改为退回修改，共 <span style='color: red;font-size: 20px; font-weight:bold'>" + allNum + "</span> 条！";
        }
    }

    @Override
    public int backOne(Long examId, Long studentId) {
        //查询出studentId对应的学生考试信息
        LambdaQueryWrapper<SchoolArtRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolArtRelation::getExamId, examId).eq(SchoolArtRelation::getStudentId, studentId);
        SchoolArtRelation relation = artRelationMapper.selectList(lqw).get(0);

        if (ArtExamConstant.REJECT.equals(relation.getAuditStatus())) {
            throw new ServiceException("身份证号为" + relation.getInfoIdCard() + "的学生信息已驳回，无法退回修改");
        } else if (ArtExamConstant.PASS.equals(relation.getAuditStatus())) {
            throw new ServiceException("身份证号为" + relation.getInfoIdCard() + "的学生信息已通过，无法退回修改");
        } else if (ArtExamConstant.EDIT.equals(relation.getAuditStatus())) {
            throw new ServiceException("身份证号为" + relation.getInfoIdCard() + "的学生信息已退回修改，没有再次提交申请，无法再次退回修改");
        } else {
            relation.setAuditStatus(ArtExamConstant.EDIT);
            return artRelationMapper.updateById(relation);
        }
    }

    /**
     * 教务管理-考试管理-驳回
     */
    @Override
    public String reject(Long examId, List<Long> studentIds) {
        // 准备记录日志数据
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        //查询出所有studentIds对应的学生信息
        LambdaQueryWrapper<SchoolArtRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolArtRelation::getExamId, examId).in(SchoolArtRelation::getStudentId, studentIds);
        List<SchoolArtRelation> list = artRelationMapper.selectList(lqw);
        //选中的有效学生信息总数
        int allNum = list.size();
        for (SchoolArtRelation relation : list) {
            if (ArtExamConstant.REJECT.equals(relation.getAuditStatus())) {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + relation.getInfoIdCard() + "的学生信息已驳回，无法再次驳回；");
            } else if (ArtExamConstant.PASS.equals(relation.getAuditStatus())) {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + relation.getInfoIdCard() + "的学生信息已通过，无法驳回；");
            } else if (ArtExamConstant.EDIT.equals(relation.getAuditStatus())) {
                failureNum++;
                successMsg.append("<br/>" + "身份证号为" + relation.getInfoIdCard() + "的学生信息已退回修改，没有再次提交申请，无法驳回；");
            } else {
                relation.setAuditStatus(ArtExamConstant.REJECT);
                artRelationMapper.updateById(relation);
                successNum++;
            }
        }
        if(allNum != successNum){
            //存在无法通过的数据
            successMsg.insert(0, "选中的有效数据共 <span style='color: red;font-size: 20px; font-weight:bold'>" + allNum + "</span> 条(排除所有未报名的数据)，已将选中数据中所有待审核的 <span style='color: red;font-size: 20px; font-weight:bold'>"+ successNum +"</span> 条数据的状态改为驳回！有 <span style='color: red;font-size: 20px; font-weight:bold'>" + failureNum + "</span> 条不符合条件的数据，无法驳回的理由如下：");
            return successMsg.toString();
        }else {
            return "恭喜您，已将选中的所有有效数据的数据(排除所有未报名的数据)的状态改为驳回，共 <span style='color: red;font-size: 20px; font-weight:bold'>" + allNum + "</span> 条！";
        }
    }

    @Override
    public int rejectOne(Long examId, Long studentId) {
        //查询出studentId对应的学生信息
        LambdaQueryWrapper<SchoolArtRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolArtRelation::getExamId, examId).eq(SchoolArtRelation::getStudentId, studentId);
        SchoolArtRelation relation = artRelationMapper.selectList(lqw).get(0);
        if (ArtExamConstant.REJECT.equals(relation.getAuditStatus())) {
            throw new ServiceException("身份证号为" + relation.getInfoIdCard() + "的学生信息已驳回，无法再次驳回");
        } else if (ArtExamConstant.PASS.equals(relation.getAuditStatus())) {
            throw new ServiceException("身份证号为" + relation.getInfoIdCard() + "的学生信息已通过，无法驳回");
        } else if (ArtExamConstant.EDIT.equals(relation.getAuditStatus())) {
            throw new ServiceException("身份证号为" + relation.getInfoIdCard() + "的学生信息已退回修改，没有再次提交申请，无法驳回");
        } else {
            relation.setAuditStatus(ArtExamConstant.REJECT);
            return artRelationMapper.updateById(relation);
        }
    }

    /**
     * 考务管理-考生账号管理-列表
     */
    @Override
    public List<SchoolArtStudent> queryList(SchoolArtStudent student) {
        LambdaQueryWrapper<SchoolArtStudent> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotNull(student.getStudentName()), SchoolArtStudent::getStudentName, student.getStudentName())
                .like(isNotNull(student.getPhoneNumber()), SchoolArtStudent::getPhoneNumber, student.getPhoneNumber())
                .like(isNotNull(student.getIdCard()), SchoolArtStudent::getIdCard, student.getIdCard())
                .orderByDesc(SchoolArtStudent::getCreateTime)
        ;
        return artStudentMapper.selectList(lqw);
    }

    //设置匹配状态
    public List<ArtEduStudentVo> setState(List<ArtEduStudentVo> list) {
        for (ArtEduStudentVo vo : list) {
            //匹配时所有信息都匹配才算匹配（身份证号，姓名，学籍号，初中学校，报考的测试项目，性别)

            //因为学生数据必填，
            // 所以只需判断身份证号不为空，则可证明学生的其他字段都不为空，
            // 教育局信息也是如此
            if (StringUtils.isNotNull(vo.getIdCard())) {
                //学生数据存在
                //教育局信息存在
                if (StringUtils.isNotNull(vo.getEduIdCard())) {
                    //匹配学生和教育局信息
                    boolean flag = true;
                    if (!vo.getStudentName().equals(vo.getEduStudentName())) {
                        flag = false;
                    }
                    if (!vo.getStudentNumber().equals(vo.getEduStudentNumber())) {
                        flag = false;
                    }
                    if (!vo.getSchoolName().equals(vo.getEduSchoolName())) {
                        flag = false;
                    }
                    if (!vo.getProject().equals(vo.getEduProject())) {
                        flag = false;
                    }
                    if (!vo.getSex().equals(vo.getEduSex())) {
                        flag = false;
                    }
                    if (flag) {
                        //全部都匹配
                        vo.setMatchStatus(ArtExamConstant.PASS);
                    } else {
                        //不匹配
                        vo.setMatchStatus(ArtExamConstant.REJECT);
                    }
                } else {
                    //不存在教育局信息
                    vo.setMatchStatus(ArtExamConstant.EDIT);
                }
            } else {
                //学生信息不存在，也就是未报名
                vo.setMatchStatus(ArtExamConstant.CHECK);
            }
        }
        return list;
    }

    /**
     * 校验手机号是否唯一
     */
    public String checkPhoneUnique(SchoolArtStudent student) {
        Long id = StringUtils.isNull(student.getId()) ? -1L : student.getId();
        SchoolArtStudent info = artStudentMapper.checkPhoneUnique(student.getPhoneNumber());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验身份证号是否唯一
     */
    public String checkIdCardUnique(SchoolArtStudent student) {
        Long id = StringUtils.isNull(student.getId()) ? -1L : student.getId();
        SchoolArtStudent info = artStudentMapper.checkIdCardUnique(student.getIdCard());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
