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

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.core.utils.JDBCUtils;
import com.core.utils.LogfieldUtil;
import com.core.utils.StringUtil;
import com.mchange.v1.identicator.IdList;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.mapper.SysUserMapper;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGradeMentor;
import yangtz.cs.liu.campus.domain.student.*;
import yangtz.cs.liu.campus.domain.teacher.SchoolTeacherWages;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMentorMapper;
import yangtz.cs.liu.campus.mapper.student.*;
import yangtz.cs.liu.campus.service.student.ISchoolStudentClassRelationService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.vo.student.SchoolStudentNameVO;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;
import yangtz.cs.liu.wechat.vo.userInfo.UserInfoVo;

import javax.validation.Validator;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.*;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.StringUtils.isNotNull;
import static yangtz.cs.liu.campus.constant.GradeConstant.NEWTERM;
import static yangtz.cs.liu.campus.constant.SexConstant.MAN;
import static yangtz.cs.liu.campus.constant.UserType.PARENT;
import static com.core.constant.CompressType.ZIP_FILE;
import static com.core.constant.CompressType.RAR_FILE;

@Service
public class SchoolStudentServiceImpl extends ServiceImpl<SchoolStudentMapper, SchoolStudent> implements ISchoolStudentService {

    @Autowired
    private SchoolStudentMapper schoolStudentMapper;

    @Autowired
    private SchoolStudentEvaluateMapper schoolStudentEvaluateMapper;

    @Autowired
    private SchoolStudentClassesMapper schoolStudentClassesMapper;

    @Autowired
    private SchoolStudentLeaveMapper schoolStudentLeaveMapper;

    @Autowired
    private SchoolStudentParentMapper schoolStudentParentMapper;

    @Autowired
    private SchoolEducationMapper schoolEducationMapper;

    @Autowired
    private SchoolEducationDetailsMapper schoolEducationDetailsMapper;

    @Autowired
    private SchoolClassMapper schoolClassMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SchoolStudentClassRelationMapper relationMapper;

    @Autowired
    private ServerConfig serverConfig;


    @Override
    public List<SchoolStudentVO> queryList(SchoolStudentVO schoolStudent) {
        return schoolStudentMapper.queryList(schoolStudent);
    }

    @Override
    public List<SchoolStudentVO> exportQueryList(SchoolStudentVO schoolStudent) {
        List<SchoolStudentVO> list = schoolStudentMapper.queryList(schoolStudent);
        if (isNull(list) || list.size() == 0) {
            return new ArrayList<>();
        }
        //获取所有学生家长
        LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(SchoolStudentParent::getCreateTime);
        List<SchoolStudentParent> studentParentList = schoolStudentParentMapper.selectList(lqw);
        for (SchoolStudentVO vo : list) {
//            LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
//            lqw.eq(SchoolStudentParent::getStudentId, vo.getId())
//                    .orderByDesc(SchoolStudentParent::getCreateTime);
//            List<SchoolStudentParent> parentList = schoolStudentParentMapper.selectList(lqw);
            List<SchoolStudentParent> parentList = new ArrayList<>();
            for (SchoolStudentParent studentParent : studentParentList) {
                if (vo.getId().equals(studentParent.getStudentId())){
                    parentList.add(studentParent);
                }
            }
            if (isNull(parentList) || parentList.size() == 0) {
                continue;
            }
            //获取学生家长，至多2人
            int i = 1;
            for (SchoolStudentParent parent : parentList) {
                if (i == 1) {
                    vo.setParentName1(parent.getParentName());
                    vo.setRelationship1(parent.getRelationship());
                    vo.setWorkAddress1(parent.getWorkAddress());
                    vo.setContactAddress1(parent.getContactAddress());
                    vo.setTelephone1(parent.getTelephone());
                    vo.setPostalCode1(parent.getPostalCode());
                } else if (i == 2) {
                    vo.setParentName2(parent.getParentName());
                    vo.setRelationship2(parent.getRelationship());
                    vo.setWorkAddress2(parent.getWorkAddress());
                    vo.setContactAddress2(parent.getContactAddress());
                    vo.setTelephone2(parent.getTelephone());
                    vo.setPostalCode2(parent.getPostalCode());
                } /*else if (i == 3) {
                    vo.setParentName3(parent.getParentName());
                    vo.setRelationship3(parent.getRelationship());
                    vo.setWorkAddress3(parent.getWorkAddress());
                    vo.setContactAddress3(parent.getContactAddress());
                    vo.setTelephone3(parent.getTelephone());
                    vo.setPostalCode3(parent.getPostalCode());
                } else if (i == 4) {
                    vo.setParentName4(parent.getParentName());
                    vo.setRelationship4(parent.getRelationship());
                    vo.setWorkAddress4(parent.getWorkAddress());
                    vo.setContactAddress4(parent.getContactAddress());
                    vo.setTelephone4(parent.getTelephone());
                    vo.setPostalCode4(parent.getPostalCode());
                }*/
                i++;
                if (i > 2) {
                    break;
                }
            }

        }
        return list;
    }

    @Override
    public List<SchoolStudentVO> exportSelect(List<Long> ids) {
        List<SchoolStudentVO> list = new ArrayList<>();
        List<SchoolStudent> studentList = schoolStudentMapper.selectBatchIds(ids);

        //获取所有班级
        List<SchoolClass> schoolClasses = schoolClassMapper.selectList(new LambdaQueryWrapper<>());

        //获取所有家长
        LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(SchoolStudentParent::getCreateTime);
        List<SchoolStudentParent> studentParentList = schoolStudentParentMapper.selectList(lqw);

        for (SchoolStudent student : studentList) {
            SchoolStudentVO vo = new SchoolStudentVO();
            BeanUtils.copyProperties(student, vo);

            for (SchoolClass schoolClass : schoolClasses) {
                if (schoolClass.getId().equals(student.getClassId())){
                    vo.setSchoolYear(schoolClass.getSchoolYear());
                    vo.setGradeValue(schoolClass.getGradeValue());
                    vo.setClassValue(schoolClass.getClassValue());
                }
            }

//            //学年年级班级
//            SchoolClass theClass = schoolClassMapper.selectById(student.getClassId());
//            if (isNotNull(theClass)) {
//                vo.setSchoolYear(theClass.getSchoolYear());
//                vo.setGradeValue(theClass.getGradeValue());
//                vo.setClassValue(theClass.getClassValue());
//            }
            //家长信息
//            LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
//            lqw.eq(SchoolStudentParent::getStudentId, student.getId())
//                    .orderByDesc(SchoolStudentParent::getCreateTime);
//            List<SchoolStudentParent> parentList = schoolStudentParentMapper.selectList(lqw);

            List<SchoolStudentParent> parentList = new ArrayList<>();
            for (SchoolStudentParent studentParent : studentParentList) {
                if (vo.getId().equals(studentParent.getStudentId())){
                    parentList.add(studentParent);
                }
            }

            if (isNull(parentList) || parentList.size() == 0) {
                list.add(vo);
                continue;
            }

            //获取学生家长，至多2人
            int i = 1;
            for (SchoolStudentParent parent : parentList) {
                if (i == 1) {
                    vo.setParentName1(parent.getParentName());
                    vo.setRelationship1(parent.getRelationship());
                    vo.setWorkAddress1(parent.getWorkAddress());
                    vo.setContactAddress1(parent.getContactAddress());
                    vo.setTelephone1(parent.getTelephone());
                    vo.setPostalCode1(parent.getPostalCode());
                } else if (i == 2) {
                    vo.setParentName2(parent.getParentName());
                    vo.setRelationship2(parent.getRelationship());
                    vo.setWorkAddress2(parent.getWorkAddress());
                    vo.setContactAddress2(parent.getContactAddress());
                    vo.setTelephone2(parent.getTelephone());
                    vo.setPostalCode2(parent.getPostalCode());
                } /*else if (i == 3) {
                    vo.setParentName3(parent.getParentName());
                    vo.setRelationship3(parent.getRelationship());
                    vo.setWorkAddress3(parent.getWorkAddress());
                    vo.setContactAddress3(parent.getContactAddress());
                    vo.setTelephone3(parent.getTelephone());
                    vo.setPostalCode3(parent.getPostalCode());
                } else if (i == 4) {
                    vo.setParentName4(parent.getParentName());
                    vo.setRelationship4(parent.getRelationship());
                    vo.setWorkAddress4(parent.getWorkAddress());
                    vo.setContactAddress4(parent.getContactAddress());
                    vo.setTelephone4(parent.getTelephone());
                    vo.setPostalCode4(parent.getPostalCode());
                }*/
                i++;
                if (i > 2) {
                    break;
                }
            }

            list.add(vo);
        }
        return list;
    }

    @Override
    public List<SchoolStudentNameVO> queryName(SchoolStudent schoolStudent) {
        return schoolStudentMapper.queryName(schoolStudent);
    }

    /*
     * 根据学生ids删除学生
     * */
    @Override
    public int deleteByIds(List<Long> ids) {
//        /** 学生综合素质评价 */
//        LambdaQueryWrapper<SchoolStudentEvaluate> evaluateLqw = new LambdaQueryWrapper<>();
//        evaluateLqw
//                .in(SchoolStudentEvaluate::getStudentId, ids)
//        ;

        /** 学生班级管理 */
        LambdaQueryWrapper<SchoolStudentClasses> classesLqw = new LambdaQueryWrapper<>();
        classesLqw
                .in(SchoolStudentClasses::getStudentId, ids)
        ;

        /** 学生 */
        LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
        lqw
                .in(SchoolStudent::getId, ids)
        ;

        /** 学生请假信息 */
        LambdaQueryWrapper<SchoolStudentLeave> studentLeaveLqw = new LambdaQueryWrapper<>();
        studentLeaveLqw
                .in(SchoolStudentLeave::getStudentId, ids)
        ;

        /** 学生家长 */
        LambdaQueryWrapper<SchoolStudentParent> parentLqw = new LambdaQueryWrapper<>();
        parentLqw
                .in(SchoolStudentParent::getStudentId, ids)
        ;

//        /** 学校德育检查 */
//        LambdaQueryWrapper<SchoolEducation> educationLqw = new LambdaQueryWrapper<>();
//        educationLqw
//                .in(SchoolEducation::getStudentId, ids)
//        ;

        //由于学校德育检查明细表中无studentID，只有educationid 所以先查找educationid，再删
//        List<Long> educationIdList = schoolEducationMapper.getIds(ids);
//        if (educationIdList.size() > 0) {
//            LambdaQueryWrapper<SchoolEducationDetails> educationDetailsLqw = new LambdaQueryWrapper<>();
//            educationDetailsLqw
//                    .in(SchoolEducationDetails::getEducationId, educationIdList)
//            ;
//            schoolEducationDetailsMapper.delete(educationDetailsLqw);
//        }
//        schoolEducationMapper.delete(educationLqw);
        schoolStudentParentMapper.delete(parentLqw);
        schoolStudentLeaveMapper.delete(studentLeaveLqw);
        schoolStudentClassesMapper.delete(classesLqw);
//        schoolStudentEvaluateMapper.delete(evaluateLqw);
        return schoolStudentMapper.delete(lqw);
    }

    /*
     * 导入学生
     * */
    @Override
    public String importStudent(List<SchoolStudentVO> dataManagementList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(dataManagementList) || dataManagementList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolStudentVO student : dataManagementList) {
            try {
                /*
                 * 验证是否存在这个学生
                 *学号不能重复，姓名不能重复，身份证号不能重复，校园卡不能重复
                 * */
                SchoolStudent schoolStudent = new SchoolStudent();
                BeanUtils.copyProperties(student, schoolStudent);
                int i = judgIsExit(schoolStudent);
                if (i == 0) {
                    this.save(schoolStudent);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getStudentName() + " 导入成功");
                } else if (i == 1) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生姓名 " + student.getStudentName() + " 已存在");
                } else if (i == 2) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生身份证 " + student.getIdCard() + " 已存在");
                } else if (i == 3) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生学号 " + student.getSchoolNo() + " 已存在");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、校园一卡通 " + student.getOneCard() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + student.getStudentName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    public String updateStudent(SchoolStudent schoolStudent) {
        int i = judgIsExit(schoolStudent);
        if (i == 0) {
            this.updateById(schoolStudent);
            return "修改成功";
        } else if (i == 1) {
            return "学生姓名" + schoolStudent.getStudentName() + "已存在，更新失败";
        } else if (i == 2) {
            return "身份证号" + schoolStudent.getIdCard() + "已存在,更新失败";
        } else if (i == 3) {
            return "学号" + schoolStudent.getSchoolNo() + "已存在，更新失败";
        } else {
            return "校园一卡通" + schoolStudent.getOneCard() + "已存在，更新失败";
        }
    }

    @Override
    public String addStudent(SchoolStudent schoolStudent) {
        int i = judgIsExit(schoolStudent);
        if (i == 0) {
            this.save(schoolStudent);
            return "新增成功";
        } else if (i == 1) {
            return "学生姓名" + schoolStudent.getStudentName() + "已存在，新增失败";
        } else if (i == 2) {
            return "身份证号" + schoolStudent.getIdCard() + "已存在,新增失败";
        } else if (i == 3) {
            return "学号" + schoolStudent.getSchoolNo() + "已存在，新增失败";
        } else {
            return "校园一卡通" + schoolStudent.getOneCard() + "已存在，新增失败";
        }
    }

    @Override
    public SchoolStudentVO getInfo(Long id) {
        return schoolStudentMapper.getInfo(id);
    }

    /**
     * 通过身份证号获取信息
     *
     * @param idCard
     * @return
     */
    @Override
    public SchoolStudentVO getInfoByidCard(String idCard) {
        SchoolStudentVO vo = schoolStudentMapper.getInfoByidCard(idCard);
        if (StringUtils.isNull(vo)) {
            throw new ServiceException("查不到身份证号对应的学生");
        }
        return vo;
    }

    /**
     * 公众号老师查看具体带的学生
     *
     * @param teacherId
     * @return
     */
    @Override
    public List<SchoolStudent> getMemberByTeacher(Long teacherId) {
        return schoolStudentMapper.getMemberByTeacher(teacherId);
    }

   public Long getDdUserId(String foUserId ){
       return schoolStudentMapper.getDdUserId(foUserId);
   }

    /**
     * 家长查看班级其他同学
     *
     * @param studentId
     * @return
     */
    @Override
    public List<SchoolStudent> getMemberByParent(Long studentId) {
        return schoolStudentMapper.getMemberByParent(studentId);
    }


    /**
     * 老师根据班级id查看学生
     *
     * @param classId
     * @return
     */
    @Override
    public List<SchoolStudent> getMemberByClassId(Long classId, String studentName) {
        LambdaQueryWrapper<SchoolStudent> lwq = new LambdaQueryWrapper<>();
        lwq
                .eq(isNotNull(classId), SchoolStudent::getClassId, classId)
                .like(isNotBlank(studentName), SchoolStudent::getStudentName, studentName)
        ;
        return schoolStudentMapper.selectList(lwq);
    }

    /**
     * 公众号：教职工通过学生id查询学生基本信息
     *
     * @param studentId
     * @return
     */
    @Override
    public List<UserInfoVo> getStudentInfo(Long studentId) {
        return schoolStudentMapper.getStudentInfo(studentId);
    }

//    @Override
//    public void checkImport(List<SchoolStudentVO> list) {
//        if (StringUtils.isNull(list) || list.size() == 0)
//        {
//            throw new ServiceException("导入用户数据不能为空！");
//        }
//        int failureNum = 0;
//        StringBuilder failureMsg = new StringBuilder();
//        for (SchoolStudentVO student : list) {
//            try {
//                if (StringUtils.isEmpty(student.getStudentName())) {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、学生姓名,请您重新输入! ");
//                }
//                /*
//                 * 验证是否存在这个学生
//                 *学号不能重复，姓名不能重复，身份证号不能重复，校园卡不能重复
//                 * */
//                SchoolStudent schoolStudent = new SchoolStudent();
//                BeanUtils.copyProperties(student, schoolStudent);
//                int i = judgIsExit(schoolStudent);
//                if (i == 0) {
//                    this.save(schoolStudent);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、学生 " + student.getStudentName() + " 导入成功");
//                } else if (i == 1) {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、学生姓名 " + student.getStudentName() + " 已存在");
//                } else if (i == 2) {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、学生身份证 " + student.getIdCard() + " 已存在");
//                } else if (i == 3) {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、学生学号 " + student.getShoolNo() + " 已存在");
//                } else {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、校园一卡通 " + student.getOneCard() + " 已存在");
//                }
//            } catch (Exception e) {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、账号 " + student.getStudentName() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
//            }
//        }
//        if (failureNum > 0) {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new ServiceException(failureMsg.toString());
//        } else {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
//        return successMsg.toString();
//    }

    public int judgIsExit(SchoolStudent schoolStudent) {
        SchoolStudent schoolStudent1 = new SchoolStudent();
        if (StringUtils.isNotNull(schoolStudent.getId())) {
            schoolStudent1.setId(schoolStudent.getId());
        }
        schoolStudent1.setStudentName(schoolStudent.getStudentName());
        if (schoolStudentMapper.query(schoolStudent1).size() > 0 && schoolStudent.getStudentName() != null) {
            return 1;
        }
        schoolStudent1.setStudentName("");
        schoolStudent1.setIdCard(schoolStudent.getIdCard());
        if (schoolStudentMapper.query(schoolStudent1).size() > 0 && schoolStudent.getIdCard() != null) {
            return 2;
        }
        schoolStudent1.setIdCard("");
        schoolStudent1.setSchoolNo(schoolStudent.getSchoolNo());
        if (schoolStudentMapper.query(schoolStudent1).size() > 0 && schoolStudent.getSchoolNo() != null) {
            return 3;
        }
        schoolStudent1.setSchoolNo("");
        schoolStudent1.setOneCard(schoolStudent.getOneCard());
        if (schoolStudentMapper.query(schoolStudent1).size() > 0 && schoolStudent.getOneCard() != null) {
            return 4;
        }
        return 0;
    }


    /**
     * 导入数据校验
     *
     * @param list
     */
    @Override
    public void checkImport(List<SchoolStudentVO> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolStudentVO schoolStudentVO : list) {
            if (StringUtils.isEmpty(schoolStudentVO.getStudentName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学生姓名为空,请您重新输入! ");
            } /*else if (StringUtils.isEmpty(schoolStudentVO.getSex())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学生性别为空,请您重新输入! ");
            }*/ else if (StringUtils.isNull(schoolStudentVO.getSchoolYear())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学年为空,请您重新输入! ");
            } else if (StringUtils.isNull(schoolStudentVO.getGradeValue())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、年级为空,请您重新输入! ");
            } else if (StringUtils.isNull(schoolStudentVO.getClassValue())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolStudentVO.getIdCard())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolStudentVO.getNation())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、民族为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolStudentVO.getSchoolNo())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、注册序号为空,请您重新输入! ");
            } /*else if (StringUtils.isEmpty(schoolStudentVO.getEnrollmentYear())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、级为空,请您重新输入! ");
            }*/ else if (StringUtils.isEmpty(schoolStudentVO.getNativePlace())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、籍贯为空,请您重新输入! ");
            } /*else if (StringUtils.isNull(schoolStudentVO.getBirthday())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、出生日期为空,请您重新输入! ");
            }*/ else if (StringUtils.isEmpty(schoolStudentVO.getStudentStatus())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学生状态为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolStudentVO.getStudentType())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学生类型为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolStudentVO.getProvincialNumber())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、省学籍辅号为空,请您重新输入! ");
            } else {
                if (StringUtils.isNotEmpty(schoolStudentVO.getNation())){
                    switch (schoolStudentVO.getNation()){
                        case "汉族":break;
                        case "壮族":break;
                        case "回族":break;
                        case "满族":break;
                        case "维吾尔族":break;
                        case "苗族":break;
                        case "彝族":break;
                        case "土家族":break;
                        case "藏族":break;
                        case "蒙古族":break;
                        case "侗族":break;
                        case "布依族":break;
                        case "瑶族":break;
                        case "白族":break;
                        case "朝鲜族":break;
                        case "哈尼族":break;
                        case "黎族":break;
                        case "哈萨克族":break;
                        case "傣族":break;
                        case "畲族":break;
                        case "傈僳族":break;
                        case "东乡族":break;
                        case "仡佬族":break;
                        case "拉祜族":break;
                        case "佤族":break;
                        case "水族":break;
                        case "纳西族":break;
                        case "羌族":break;
                        case "土族":break;
                        case "仫佬族":break;
                        case "锡伯族":break;
                        case "柯尔克孜族":break;
                        case "景颇族":break;
                        case "达斡尔族":break;
                        case "撒拉族":break;
                        case "布朗族":break;
                        case "毛南族":break;
                        case "塔吉克族":break;
                        case "普米族":break;
                        case "阿昌族":break;
                        case "怒族":break;
                        case "鄂温克族":break;
                        case "京族":break;
                        case "基诺族":break;
                        case "德昂族":break;
                        case "保安族":break;
                        case "俄罗斯族":break;
                        case "裕固族":break;
                        case "乌孜别克族":break;
                        case "门巴族":break;
                        case "鄂伦春族":break;
                        case "独龙族":break;
                        case "高山族":break;
                        case "珞巴族":break;
                        case "塔塔尔族":break;
                        default:
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、民族格式不正确,请您重新输入! ");
                            break;
                    }
                }
                if (StringUtils.isNotEmpty(schoolStudentVO.getIdCard())){
                    if (schoolStudentVO.getIdCard().length() != 18 && schoolStudentVO.getIdCard().length() != 15){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、身份证号格式不正确,请您重新输入! ");
                    }
                }
                schoolStudentVO.setStudentName(StringUtil.clearSpace(schoolStudentVO.getStudentName()));
                schoolStudentVO.setIdCard(StringUtil.clearSpace(schoolStudentVO.getIdCard()));
                schoolStudentVO.setProvincialNumber(StringUtil.clearSpace(schoolStudentVO.getProvincialNumber()));
                schoolStudentVO.setNationalNumber(StringUtil.clearSpace(schoolStudentVO.getNationalNumber()));
                schoolStudentVO.setSchoolNo(StringUtil.clearSpace(schoolStudentVO.getSchoolNo()));
                if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
                    schoolStudentVO.setOneCard(StringUtil.clearSpace(schoolStudentVO.getOneCard()));
                }

                LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
                lqw
                        .eq(SchoolStudent::getIdCard, schoolStudentVO.getIdCard())
                ;
                SchoolStudent schoolStudent = schoolStudentMapper.selectOne(lqw);
                //已存在学生就根据身份证更新数据,导入改学生信息时，姓名、身份证号、民族不能修改
                if (isNotNull(schoolStudent)) {
                    //检验省学籍辅号、国家学籍号、注册学号是否存在
                    LambdaQueryWrapper<SchoolStudent> l = new LambdaQueryWrapper<>();
                    l
                            .eq(SchoolStudent::getSchoolNo, schoolStudentVO.getSchoolNo())
                            .or()
                            .eq(isNotBlank(schoolStudentVO.getProvincialNumber()), SchoolStudent::getProvincialNumber, schoolStudentVO.getProvincialNumber())
                            .or()
                            .eq(isNotBlank(schoolStudentVO.getNationalNumber()), SchoolStudent::getNationalNumber, schoolStudentVO.getNationalNumber())
                            .or()
                            .eq(isNotBlank(schoolStudentVO.getOneCard()), SchoolStudent::getOneCard, schoolStudentVO.getOneCard())
                    ;
                    SchoolStudent s = schoolStudentMapper.selectOne(l);
                    if (StringUtils.isNotNull(s)) {
                        //两者查出来的用户不一致时
                        if (!schoolStudent.getId().equals(s.getId())) {
                            if (schoolStudent.getSchoolNo().equals(s.getSchoolNo())) {
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的注册学号重复,请您重新输入! ");
                            }

                            if (StringUtils.isNotBlank(schoolStudentVO.getProvincialNumber())) {
                                if (schoolStudent.getProvincialNumber().equals(s.getProvincialNumber())) {
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的省学籍辅号重复,请您重新输入! ");
                                }
                            }

                            if (StringUtils.isNotBlank(schoolStudentVO.getNationalNumber())) {
                                if (schoolStudent.getNationalNumber().equals(s.getNationalNumber())) {
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的全国学籍号重复,请您重新输入! ");
                                }
                            }

                            if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
                                if (schoolStudent.getOneCard().equals(s.getOneCard())) {
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的一卡通重复,请您重新输入! ");
                                }
                            }
                        }
                    }

                    //特殊字段classId,,,更新时学年年级班级更改后，班级id也要改变，班级id改变，学生班级关系表也要搞一份
                    if (isNotNull(schoolStudentVO.getSchoolYear()) && isNotNull(schoolStudentVO.getGradeValue())
                            && isNotNull(schoolStudentVO.getClassValue())) {
                        LambdaQueryWrapper<SchoolClass> classLqw = new LambdaQueryWrapper<>();
                        classLqw
                                .eq(SchoolClass::getSchoolYear, schoolStudentVO.getSchoolYear())
                                .eq(SchoolClass::getGradeValue, schoolStudentVO.getGradeValue())
                                .eq(SchoolClass::getClassValue, schoolStudentVO.getClassValue());
                        List<SchoolClass> schoolClass = schoolClassMapper.selectList(classLqw);
                        if (isNull(schoolClass) || schoolClass.size() == 0) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "所选班级不存在,请您重新输入! ");
                        } else {
                            Long classId = schoolClass.get(0).getId();
                            schoolStudentVO.setClassId(classId);
                        }
                    }
                    schoolStudentVO.setStudentName(schoolStudent.getStudentName());
                    schoolStudentVO.setNation(schoolStudent.getNation());
                } else {

                    //检验省学籍辅号、国家学籍号、注册学号是否存在
                    LambdaQueryWrapper<SchoolStudent> l = new LambdaQueryWrapper<>();
                    l
                            .eq(SchoolStudent::getSchoolNo, schoolStudentVO.getSchoolNo())
                            .or()
                            .eq(isNotBlank(schoolStudentVO.getProvincialNumber()), SchoolStudent::getProvincialNumber, schoolStudentVO.getProvincialNumber())
                            .or()
                            .eq(isNotBlank(schoolStudentVO.getNationalNumber()), SchoolStudent::getNationalNumber, schoolStudentVO.getNationalNumber())
                            .or()
                            .eq(isNotBlank(schoolStudentVO.getOneCard()), SchoolStudent::getOneCard, schoolStudentVO.getOneCard())
                    ;
                    SchoolStudent s = schoolStudentMapper.selectOne(l);
                    if (StringUtils.isNotNull(s)) {
                        //两者查出来的用户不一致时
                        if (schoolStudentVO.getSchoolNo().equals(s.getSchoolNo())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的注册学号重复,请您重新输入! ");
                        }

                        if (StringUtils.isNotBlank(schoolStudentVO.getProvincialNumber())) {
                            if (schoolStudentVO.getProvincialNumber().equals(s.getProvincialNumber())) {
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的省学籍辅号重复,请您重新输入! ");
                            }
                        }

                        if (StringUtils.isNotBlank(schoolStudentVO.getNationalNumber())) {
                            if (schoolStudentVO.getNationalNumber().equals(s.getNationalNumber())) {
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的全国学籍号重复,请您重新输入! ");
                            }
                        }

                        if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
                            if (schoolStudentVO.getOneCard().equals(s.getOneCard())) {
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "的一卡通重复,请您重新输入! ");
                            }
                        }
                    }

                    //学生不存在，新增
                    if (isNotNull(schoolStudentVO.getSchoolYear()) && isNotNull(schoolStudentVO.getGradeValue())
                            && isNotNull(schoolStudentVO.getClassValue())) {
                        LambdaQueryWrapper<SchoolClass> classLqw = new LambdaQueryWrapper<>();
                        classLqw
                                .eq(SchoolClass::getSchoolYear, schoolStudentVO.getSchoolYear())
                                .eq(SchoolClass::getGradeValue, schoolStudentVO.getGradeValue())
                                .eq(SchoolClass::getClassValue, schoolStudentVO.getClassValue());
                        List<SchoolClass> schoolClass = schoolClassMapper.selectList(classLqw);
                        if (isNull(schoolClass) || schoolClass.size() == 0) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、" + schoolStudentVO.getStudentName() + "所选班级不存在,请您重新输入! ");
                        } else {
                            Long classId = schoolClass.get(0).getId();
                            schoolStudentVO.setClassId(classId);
                        }
                    }
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }

    }


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String importData(List<SchoolStudentDrVo> list) {
//        // 准备记录日志数据
//        int successNum = 0;
//        StringBuilder successMsg = new StringBuilder();
//        // 遍历并逐个导入
//        for (SchoolStudentDrVo schoolStudentVO : list) {
//            /*try {*/
//            //按身份证查询，看是否已存在，该查询主要用于判断班级classId是否改变
//            LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
//            lqw
//                    .eq(SchoolStudent::getIdCard, schoolStudentVO.getIdCard())
//            ;
//            SchoolStudent schoolStudent = schoolStudentMapper.selectOne(lqw);
//
//            //学生已存在
//            if (isNotNull(schoolStudent)) {
//                //再次检验导入的数据中是否有重复省学籍辅号、国家学籍号、注册学号、一卡通
//                LambdaQueryWrapper<SchoolStudent> lq = new LambdaQueryWrapper<>();
//                lq
//                        .eq(SchoolStudent::getSchoolNo, schoolStudentVO.getSchoolNo())
//                        .or()
//                        .eq(isNotBlank(schoolStudentVO.getProvincialNumber()), SchoolStudent::getProvincialNumber, schoolStudentVO.getProvincialNumber())
//                        .or()
//                        .eq(isNotBlank(schoolStudentVO.getNationalNumber()), SchoolStudent::getNationalNumber, schoolStudentVO.getNationalNumber())
//                        .or()
//                        .eq(isNotBlank(schoolStudentVO.getOneCard()), SchoolStudent::getOneCard, schoolStudentVO.getOneCard())
//                ;
//                List<SchoolStudent> ss = schoolStudentMapper.selectList(lq);
//                if (StringUtils.isNotNull(ss) && ss.size() > 1) {
//                    for (SchoolStudent student1 : ss) {
//                        if (!student1.getId().equals(schoolStudent.getId())) {
//                            //throw new ServiceException(schoolStudent.getStudentName() + "与" + student1.getStudentName() + "存在重复数据,请您检查后重新输入!");
//                            if (schoolStudentVO.getSchoolNo().equals(student1.getSchoolNo())) {
//                                throw new ServiceException(schoolStudentVO.getStudentName() + "的注册学号与导入文件中" + student1.getStudentName() + "的注册学号重复,请您重新输入!");
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getProvincialNumber())) {
//                                if (schoolStudentVO.getProvincialNumber().equals(student1.getProvincialNumber())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的省学籍辅号与导入文件中" + student1.getStudentName() + "的省学籍辅号重复,请您重新输入!");
//                                }
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getNationalNumber())) {
//                                if (schoolStudentVO.getNationalNumber().equals(student1.getNationalNumber())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的全国学籍号与导入文件中" + student1.getStudentName() + "的全国学籍号重复,请您重新输入!");
//                                }
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
//                                if (schoolStudentVO.getOneCard().equals(student1.getOneCard())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的一卡通号与导入文件中" + student1.getStudentName() + "的一卡通号重复,请您重新输入!");
//                                }
//                            }
//                        }
//                    }
//                } else {
//                    if (StringUtils.isNotNull(ss) && ss.size() > 0) {
//                         SchoolStudent s = ss.get(0);
//                        //两者查出来的用户不一致时
//                        if (!schoolStudent.getId().equals(s.getId())) {
//                            if (schoolStudentVO.getSchoolNo().equals(s.getSchoolNo())) {
//                                throw new ServiceException(schoolStudentVO.getStudentName() + "的注册学号与导入文件中" + s.getStudentName() + "的注册学号重复,请您重新输入!");
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getProvincialNumber())) {
//                                if (schoolStudentVO.getProvincialNumber().equals(s.getProvincialNumber())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的省学籍辅号与导入文件中" + s.getStudentName() + "的省学籍辅号重复,请您重新输入!");
//                                }
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getNationalNumber())) {
//                                if (schoolStudentVO.getNationalNumber().equals(s.getNationalNumber())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的全国学籍号与导入文件中" + s.getStudentName() + "的全国学籍号重复,请您重新输入!");
//                                }
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
//                                if (schoolStudentVO.getOneCard().equals(s.getOneCard())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的一卡通号与导入文件中" + s.getStudentName() + "的一卡通号重复,请您重新输入!");
//                                }
//                            }
//                        }
//
//                    }
//                }
//
//
//                //班级都存在
//                if (isNotNull(schoolStudentVO.getClassId()) && isNotNull(schoolStudent.getClassId())) {
//                    //班级id都存在，看是否发生改变
//                    if (!schoolStudentVO.getClassId().equals(schoolStudent.getClassId())) {
//                        LambdaQueryWrapper<SchoolStudentClassRelation> l = new LambdaQueryWrapper<>();
//                        l.eq(SchoolStudentClassRelation::getClassId, schoolStudent.getClassId())
//                                .eq(SchoolStudentClassRelation::getStudentId, schoolStudent.getId());
//                        relationMapper.delete(l);
//                        addRelation(schoolStudentVO.getClassId(), schoolStudent.getId());
//                    }
//                }
//                //之前没有班级，现在已有
//                if (isNotNull(schoolStudentVO.getClassId()) && isNull(schoolStudent.getClassId())) {
//                    addRelation(schoolStudentVO.getClassId(), schoolStudent.getId());
//                }
//                //此方法会整掉原有学生id
//                //BeanUtils.copyProperties(schoolStudentVO, schoolStudent);
//
//                if (schoolStudentMapper.updateById(copyStudent(schoolStudentVO, schoolStudent)) > 0) {
//                    //检查学生父母信息
//                    addParent(schoolStudentVO, schoolStudent.getId());
//
//                }
//            } else {
//                   /* if (MAN.equals(schoolStudentVO.getSex())) {
//                        schoolStudentVO.setAvatar("https://eos-wuxi-1.cmecloud.cn/dy-pro/image/2022/08/09/b076ed42bfca4a8cae062dfffd5f3618.jpg");
//                    } else {
//                        schoolStudentVO.setAvatar("https://eos-wuxi-1.cmecloud.cn/dy-pro/image/2022/08/09/8a6c1334494d418d8a53cc7bf5abd668.jpg");
//                    }*/
//                //检验省学籍辅号、国家学籍号、注册学号是否存在
//                LambdaQueryWrapper<SchoolStudent> l = new LambdaQueryWrapper<>();
//                l
//                        .eq(SchoolStudent::getSchoolNo, schoolStudentVO.getSchoolNo())
//                        .or()
//                        .eq(isNotBlank(schoolStudentVO.getProvincialNumber()), SchoolStudent::getProvincialNumber, schoolStudentVO.getProvincialNumber())
//                        .or()
//                        .eq(isNotBlank(schoolStudentVO.getNationalNumber()), SchoolStudent::getNationalNumber, schoolStudentVO.getNationalNumber())
//                        .or()
//                        .eq(isNotBlank(schoolStudentVO.getOneCard()), SchoolStudent::getOneCard, schoolStudentVO.getOneCard())
//                ;
//                List<SchoolStudent> ss = schoolStudentMapper.selectList(l);
//                if (StringUtils.isNotNull(ss) && ss.size() > 1) {
//                    for (SchoolStudent student1 : ss) {
//                        if (!student1.getId().equals(schoolStudent.getId())) {
//                            if (schoolStudentVO.getSchoolNo().equals(student1.getSchoolNo())) {
//                                throw new ServiceException(schoolStudentVO.getStudentName() + "的注册学号与导入文件中" + student1.getStudentName() + "的注册学号重复,请您重新输入!");
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getProvincialNumber())) {
//                                if (schoolStudentVO.getProvincialNumber().equals(student1.getProvincialNumber())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的省学籍辅号与导入文件中" + student1.getStudentName() + "的省学籍辅号重复,请您重新输入!");
//                                }
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getNationalNumber())) {
//                                if (schoolStudentVO.getNationalNumber().equals(student1.getNationalNumber())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的全国学籍号与导入文件中" + student1.getStudentName() + "的全国学籍号重复,请您重新输入!");
//                                }
//                            }
//
//                            if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
//                                if (schoolStudentVO.getOneCard().equals(student1.getOneCard())) {
//                                    throw new ServiceException(schoolStudentVO.getStudentName() + "的一卡通号与导入文件中" + student1.getStudentName() + "的一卡通号重复,请您重新输入!");
//                                }
//                            }
//                        }
//                    }
//                }else{
//                    if (StringUtils.isNotNull(ss) && ss.size() > 0) {
//                        SchoolStudent s = ss.get(0);
//                        //两者查出来的用户不一致时
//                        if (schoolStudentVO.getSchoolNo().equals(s.getSchoolNo())) {
//                            throw new ServiceException(schoolStudentVO.getStudentName() + "的注册学号与导入文件中" + s.getStudentName() + "的注册学号重复,请您重新输入!");
//                        }
//
//                        if (StringUtils.isNotBlank(schoolStudentVO.getProvincialNumber())) {
//                            if (schoolStudentVO.getProvincialNumber().equals(s.getProvincialNumber())) {
//                                throw new ServiceException(schoolStudentVO.getStudentName() + "的省学籍辅号与导入文件中" + s.getStudentName() + "的省学籍辅号重复,请您重新输入!");
//                            }
//                        }
//
//                        if (StringUtils.isNotBlank(schoolStudentVO.getNationalNumber())) {
//                            if (schoolStudentVO.getNationalNumber().equals(s.getNationalNumber())) {
//                                throw new ServiceException(schoolStudentVO.getStudentName() + "的全国学籍号与导入文件中" + s.getStudentName() + "的全国学籍号重复,请您重新输入!");
//                            }
//                        }
//
//                        if (StringUtils.isNotBlank(schoolStudentVO.getOneCard())) {
//                            if (schoolStudentVO.getOneCard().equals(s.getOneCard())) {
//                                throw new ServiceException(schoolStudentVO.getStudentName() + "的一卡通号与导入文件中" + s.getStudentName() + "的一卡通号重复,请您重新输入!");
//                            }
//                        }
//                    }
//                }
//
//                // TODO 新增
//                //设置该同学性别
//                schoolStudentVO.setSex(String.valueOf(getSexFromIdCard(schoolStudentVO.getIdCard())));
//                //设置该同学出生日期
//                schoolStudentVO.setBirthday(getBirthDayFromIdCard(schoolStudentVO.getIdCard()));
//
//                SchoolStudent student = new SchoolStudent();
//                BeanUtils.copyProperties(schoolStudentVO, student);
//                if (schoolStudentMapper.insert(student) > 0) {
//                    if (isNotNull(schoolStudentVO.getClassId())) {
//                        addRelation(schoolStudentVO.getClassId(), student.getId());
//                    }
//                    addParent(schoolStudentVO, student.getId());
//
//                }
//            }
//            successNum++;
//            successMsg.append("<br/>" + successNum + "数据" + " 导入成功");
//            /*} catch (Exception e) {
//                throw new ServiceException("导入失败");
//            }*/
//        }
//        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条，数据如下：");
//        return successMsg.toString();
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<SchoolStudentVO> list){
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();

        //查询全部学生
        LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
        List<SchoolStudent> schoolStudents = schoolStudentMapper.selectList(lqw);

        //查询所有班级学生对应关系
        LambdaQueryWrapper<SchoolStudentClassRelation> relationWrapper = new LambdaQueryWrapper<>();
        List<SchoolStudentClassRelation> classRelations = relationMapper.selectList(relationWrapper);

        //查询所有学生父母
        LambdaQueryWrapper<SchoolStudentParent> parentWrapper = new LambdaQueryWrapper<>();
        List<SchoolStudentParent> studentParents = schoolStudentParentMapper.selectList(parentWrapper);

        //学生集合
        List<SchoolStudent> addList = new ArrayList<>();
        List<SchoolStudent> updateList = new ArrayList<>();
        //学生与班级对应关系集合
        List<SchoolStudentClassRelation> updateRelationList = new ArrayList<>();
        List<SchoolStudentClassRelation> addRelationList = new ArrayList<>();
        List<SchoolStudentClassRelation> addRelationListX = new ArrayList<>();
        //学生家长集合
        List<SchoolStudentParent> updateParentList = new ArrayList<>();
        List<SchoolStudentParent> addParentList = new ArrayList<>();
        List<SchoolStudentParent> addParentListX = new ArrayList<>();
        //用户集合
        List<SysUser> addUserList = new ArrayList<>();
        List<SysUser> addUserListX = new ArrayList<>();
        List<SysUser> updateUserList = new ArrayList<>();

        //校验学生数据
        for (SchoolStudentVO schoolStudentDrVo : list) {
            //按身份证查询，看是否已存在，该查询主要用于判断班级classId是否改变
            SchoolStudent student = new SchoolStudent();
            for (SchoolStudent schoolStudent : schoolStudents) {
                if (schoolStudentDrVo.getIdCard().equals(schoolStudent.getIdCard())){
                    BeanUtils.copyProperties(schoolStudent,student);
                }
            }
            //学生已存在
            if (isNotNull(student.getId())){
                //班级都存在
                if (StringUtils.isNotNull(schoolStudentDrVo.getClassId()) && StringUtils.isNotNull(student.getClassId())){
                    //班级id都存在，看是否发生改变
                    if (!schoolStudentDrVo.getClassId().equals(student.getClassId())){
                        for (SchoolStudentClassRelation relation : classRelations) {
                            if (student.getId().equals(relation.getStudentId()) && student.getClassId().equals(relation.getClassId())){
                                relation.setClassId(schoolStudentDrVo.getClassId());
                                updateRelationList.add(relation);
                            }
                        }
                    }
                }
                //之前没有班级，现在已有
                if (isNotNull(schoolStudentDrVo.getClassId()) && isNull(student.getClassId())) {
                    SchoolStudentClassRelation relation = new SchoolStudentClassRelation();
                    relation.setStudentId(student.getId());
                    relation.setClassId(schoolStudentDrVo.getClassId());
                    addRelationList.add(relation);
                }
                //检查学生父母信息
                SchoolStudentParent studentParent1 = new SchoolStudentParent();
                SchoolStudentParent studentParent2 = new SchoolStudentParent();
                for (SchoolStudentParent studentParent : studentParents) {
                    if(!(schoolStudentDrVo.getParentName1().equals("")) && !(schoolStudentDrVo.getTelephone1().equals(""))){
                        if (student.getId().equals(studentParent.getStudentId()) && schoolStudentDrVo.getTelephone1().equals(studentParent.getTelephone())){
                            BeanUtils.copyProperties(studentParent,studentParent1);
                        }
                    }
                    if(!(schoolStudentDrVo.getParentName2().equals("")) && !(schoolStudentDrVo.getTelephone2().equals(""))){
                        if (student.getId().equals(studentParent.getStudentId()) && schoolStudentDrVo.getTelephone2().equals(studentParent.getTelephone())){
                            BeanUtils.copyProperties(studentParent,studentParent2);
                        }
                    }
                }
                if(!(schoolStudentDrVo.getParentName1().equals("")) && !(schoolStudentDrVo.getTelephone1().equals(""))){
                    if (StringUtils.isNotEmpty(studentParent1.getParentName())){
                        //存在更新家长信息
                        studentParent1.setParentName(StringUtil.clearSpace(schoolStudentDrVo.getParentName1()));
                        studentParent1.setRelationship(schoolStudentDrVo.getRelationship1());
                        studentParent1.setWorkAddress(schoolStudentDrVo.getWorkAddress1());
                        studentParent1.setContactAddress(schoolStudentDrVo.getContactAddress1());
                        studentParent1.setPostalCode(schoolStudentDrVo.getPostalCode1());
                        updateParentList.add(studentParent1);
                        SysUser user = new SysUser();
                        user.setUserId(studentParent1.getUserId());
                        user.setUserName(StringUtil.clearSpace(schoolStudentDrVo.getParentName1()));
                        updateUserList.add(user);
                    }else {
                        //不存在，新增用户表
                        //新增进用户表
                        SysUser user = new SysUser();
                        user.setUserLoginType(PARENT);
                        user.setUserName(StringUtil.clearSpace(schoolStudentDrVo.getParentName1()));
                        user.setPhonenumber(StringUtil.clearSpace(schoolStudentDrVo.getTelephone1()));
                        user.setStudentId(student.getId());
                        addUserList.add(user);

                        //新增进家长表
                        SchoolStudentParent parent = new SchoolStudentParent();
                        parent.setParentName(StringUtil.clearSpace(schoolStudentDrVo.getParentName1()));
                        parent.setRelationship(schoolStudentDrVo.getRelationship1());
                        parent.setWorkAddress(schoolStudentDrVo.getWorkAddress1());
                        parent.setContactAddress(schoolStudentDrVo.getContactAddress1());
                        parent.setTelephone(StringUtil.clearSpace(schoolStudentDrVo.getTelephone1()));
                        parent.setPostalCode(schoolStudentDrVo.getPostalCode1());
//                            parent.setUserId(user.getUserId());
                        parent.setStudentId(student.getId());
                        addParentList.add(parent);
                    }
                }

                if(!(schoolStudentDrVo.getParentName2().equals("")) && !(schoolStudentDrVo.getTelephone2().equals(""))){
                    //存在更新家长信息
                    if (StringUtils.isNotEmpty(studentParent2.getParentName())){
                        studentParent2.setParentName(StringUtil.clearSpace(schoolStudentDrVo.getParentName2()));
                        studentParent2.setRelationship(schoolStudentDrVo.getRelationship2());
                        studentParent2.setWorkAddress(schoolStudentDrVo.getWorkAddress2());
                        studentParent2.setContactAddress(schoolStudentDrVo.getContactAddress2());
                        studentParent2.setPostalCode(schoolStudentDrVo.getPostalCode2());
                        updateParentList.add(studentParent2);
                        SysUser user = new SysUser();
                        user.setUserId(studentParent2.getUserId());
                        user.setUserName(StringUtil.clearSpace(schoolStudentDrVo.getParentName2()));
                        updateUserList.add(user);
                    }else {
                        //不存在，新增用户表
                        //新增进用户表
                        SysUser user = new SysUser();
                        user.setUserLoginType(PARENT);
                        user.setUserName(StringUtil.clearSpace(schoolStudentDrVo.getParentName2()));
                        user.setPhonenumber(StringUtil.clearSpace(schoolStudentDrVo.getTelephone2()));
                        user.setStudentId(student.getId());
                        addUserList.add(user);

                        //新增进家长表
                        SchoolStudentParent parent = new SchoolStudentParent();
                        parent.setParentName(StringUtil.clearSpace(schoolStudentDrVo.getParentName2()));
                        parent.setRelationship(schoolStudentDrVo.getRelationship2());
                        parent.setWorkAddress(schoolStudentDrVo.getWorkAddress2());
                        parent.setContactAddress(schoolStudentDrVo.getContactAddress2());
                        parent.setTelephone(StringUtil.clearSpace(schoolStudentDrVo.getTelephone2()));
                        parent.setPostalCode(schoolStudentDrVo.getPostalCode2());
//                            parent.setUserId(user.getUserId());
                        parent.setStudentId(student.getId());
                        addParentList.add(parent);
                    }
                }

                updateList.add(copyStudent(schoolStudentDrVo,student));
            }else {
                //设置该同学性别
                schoolStudentDrVo.setSex(String.valueOf(getSexFromIdCard(schoolStudentDrVo.getIdCard())));
                //设置该同学出生日期
                schoolStudentDrVo.setBirthday(getBirthDayFromIdCard(schoolStudentDrVo.getIdCard()));

                //新增学生
                SchoolStudent schoolStudent = new SchoolStudent();
                BeanUtils.copyProperties(schoolStudentDrVo, schoolStudent);
                addList.add(schoolStudent);
            }
        }
        if (addList.size()>0){
            //新增学生
            schoolStudentMapper.inserStudentList(addList);
            //为新增学生添加班级关系
            for (SchoolStudent schoolStudent : addList) {
                SchoolStudentClassRelation relation = new SchoolStudentClassRelation();
                relation.setStudentId(schoolStudent.getId());
                relation.setClassId(schoolStudent.getClassId());
                addRelationListX.add(relation);
            }
            relationMapper.addRelationList(addRelationListX);
        }
        if (updateList.size()>0){
            //更新学生信息
            schoolStudentMapper.updateStudentList(updateList);
        }
        if (updateRelationList.size()>0){
            //更新学生与班级关系
            relationMapper.updateRelationList(updateRelationList);
        }
        if (addRelationList.size()>0){
            //新增学生与班级关系
            relationMapper.addRelationList(addRelationList);
        }
        if (updateParentList.size()>0){
            //更新学生家长信息
            schoolStudentParentMapper.updateParentList(updateParentList);
        }
        if (updateUserList.size()>0){
            //更新用户表
            userMapper.updateUserList(updateUserList);
        }
        if (addUserList.size()>0){
            //学生存在
            //新增用户表
            userMapper.addUserList(addUserList);
            for (SysUser sysUser : addUserList) {
                for (SchoolStudentParent parent : addParentList) {
                    if (parent.getParentName().equals(sysUser.getUserName()) && parent.getStudentId().equals(sysUser.getStudentId()) && parent.getTelephone().equals(sysUser.getPhonenumber())){
                        parent.setUserId(sysUser.getUserId());
                    }
                }
            }
            //新增学生家长信息
            schoolStudentParentMapper.addParentList(addParentList);
        }
        if (addList.size()>0){
            //学生不存在
            for (SchoolStudentVO schoolStudentDrVo : list) {
                for (SchoolStudent schoolStudent : addList) {
                    if (schoolStudent.getIdCard().equals(schoolStudentDrVo.getIdCard())){
                        if(!(schoolStudentDrVo.getParentName1().equals("")) && !(schoolStudentDrVo.getTelephone1().equals(""))){
                            SysUser user = new SysUser();
                            user.setUserLoginType(PARENT);
                            user.setUserName(StringUtil.clearSpace(schoolStudentDrVo.getParentName1()));
                            user.setPhonenumber(StringUtil.clearSpace(schoolStudentDrVo.getTelephone1()));
                            user.setStudentId(schoolStudent.getId());
                            addUserListX.add(user);

                            //新增进家长表
                            SchoolStudentParent parent = new SchoolStudentParent();
                            parent.setParentName(StringUtil.clearSpace(schoolStudentDrVo.getParentName1()));
                            parent.setRelationship(schoolStudentDrVo.getRelationship1());
                            parent.setWorkAddress(schoolStudentDrVo.getWorkAddress1());
                            parent.setContactAddress(schoolStudentDrVo.getContactAddress1());
                            parent.setTelephone(StringUtil.clearSpace(schoolStudentDrVo.getTelephone1()));
                            parent.setPostalCode(schoolStudentDrVo.getPostalCode1());
//                            parent.setUserId(user.getUserId());
//                            parent.setStudentId(student.getId());
                            addParentListX.add(parent);
                        }

                        if(!(schoolStudentDrVo.getParentName2().equals("")) && !(schoolStudentDrVo.getTelephone2().equals(""))){
                            SysUser user = new SysUser();
                            user.setUserLoginType(PARENT);
                            user.setUserName(StringUtil.clearSpace(schoolStudentDrVo.getParentName2()));
                            user.setPhonenumber(StringUtil.clearSpace(schoolStudentDrVo.getTelephone2()));
                            user.setStudentId(schoolStudent.getId());
                            addUserListX.add(user);

                            //新增进家长表
                            SchoolStudentParent parent = new SchoolStudentParent();
                            parent.setParentName(StringUtil.clearSpace(schoolStudentDrVo.getParentName2()));
                            parent.setRelationship(schoolStudentDrVo.getRelationship2());
                            parent.setWorkAddress(schoolStudentDrVo.getWorkAddress2());
                            parent.setContactAddress(schoolStudentDrVo.getContactAddress2());
                            parent.setTelephone(StringUtil.clearSpace(schoolStudentDrVo.getTelephone2()));
                            parent.setPostalCode(schoolStudentDrVo.getPostalCode2());
//                            parent.setUserId(user.getUserId());
//                            parent.setStudentId(student.getId());
                            addParentListX.add(parent);
                        }
                    }
                }
            }
            if (addUserListX.size()>0){
                //新增用户表
                userMapper.addUserList(addUserListX);
                for (SysUser sysUser : addUserListX) {
                    for (SchoolStudentParent parent : addParentListX) {
                        if (parent.getParentName().equals(sysUser.getUserName()) && parent.getStudentId().equals(sysUser.getStudentId()) && parent.getTelephone().equals(sysUser.getPhonenumber())){
                            parent.setUserId(sysUser.getUserId());
                        }
                    }
                }
                //新增学生家长信息
                schoolStudentParentMapper.addParentList(addParentListX);
            }
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！");
        return successMsg.toString();
    }


    //添加学生与班级关系表
    private boolean addRelation(Long classId, Long studentId) {
        SchoolStudentClassRelation relation = new SchoolStudentClassRelation();
        relation.setClassId(classId);
        relation.setStudentId(studentId);
        return relationMapper.insert(relation) > 0;
    }


    /**
     * 导入时处理家长
     */
    public void addParent(SchoolStudentVO vo, Long studentId) {
        if (!(vo.getParentName1().equals("")) && !(vo.getTelephone1().equals(""))) {
            LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolStudentParent::getStudentId, studentId)
                    .eq(SchoolStudentParent::getTelephone, StringUtil.clearSpace(vo.getTelephone1()));
            List<SchoolStudentParent> parentList = schoolStudentParentMapper.selectList(lqw);
            //存在该家长，更新已改信息
            if (StringUtils.isNotNull(parentList) && parentList.size() > 0) {
                SchoolStudentParent parent = parentList.get(0);
                parent.setParentName(StringUtil.clearSpace(vo.getParentName1()));
                parent.setRelationship(vo.getRelationship1());
                parent.setWorkAddress(vo.getWorkAddress1());
                parent.setContactAddress(vo.getContactAddress1());
                parent.setPostalCode(vo.getPostalCode1());
                schoolStudentParentMapper.updateById(parent);
                Long userId = parent.getUserId();
                userMapper.updateUserNameByUserId(StringUtil.clearSpace(vo.getParentName1()), userId);
            } else {
                /** 新增进用户表 */
                SysUser user = new SysUser();
                user.setUserLoginType(PARENT);
                user.setUserName(StringUtil.clearSpace(vo.getParentName1()));
                user.setPhonenumber(StringUtil.clearSpace(vo.getTelephone1()));
                user.setStudentId(studentId);
                userMapper.insertUser(user);

                /** 新增进家长表 */
                SchoolStudentParent parent = new SchoolStudentParent();
                parent.setParentName(StringUtil.clearSpace(vo.getParentName1()));
                parent.setRelationship(vo.getRelationship1());
                parent.setWorkAddress(vo.getWorkAddress1());
                parent.setContactAddress(vo.getContactAddress1());
                parent.setTelephone(StringUtil.clearSpace(vo.getTelephone1()));
                parent.setPostalCode(vo.getPostalCode1());
                parent.setUserId(user.getUserId());
                parent.setStudentId(studentId);
                schoolStudentParentMapper.insert(parent);
            }
        }

        if (!(vo.getParentName2().equals("")) && !(vo.getTelephone2().equals(""))) {
            LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolStudentParent::getStudentId, studentId)
                    .eq(SchoolStudentParent::getTelephone, StringUtil.clearSpace(vo.getTelephone2()));
            List<SchoolStudentParent> parentList = schoolStudentParentMapper.selectList(lqw);
            //存在该家长，更新已改信息
            if (StringUtils.isNotNull(parentList) && parentList.size() > 0) {
                SchoolStudentParent parent = parentList.get(0);
                parent.setParentName(StringUtil.clearSpace(vo.getParentName2()));
                parent.setRelationship(vo.getRelationship2());
                parent.setWorkAddress(vo.getWorkAddress2());
                parent.setContactAddress(vo.getContactAddress2());
                parent.setPostalCode(vo.getPostalCode2());
                schoolStudentParentMapper.updateById(parent);
                Long userId = parent.getUserId();
                userMapper.updateUserNameByUserId(StringUtil.clearSpace(vo.getParentName2()), userId);
            } else {
                /** 新增进用户表 */
                SysUser user = new SysUser();
                user.setUserLoginType(PARENT);
                user.setUserName(StringUtil.clearSpace(vo.getParentName2()));
                user.setPhonenumber(StringUtil.clearSpace(vo.getTelephone2()));
                user.setStudentId(studentId);
                userMapper.insertUser(user);

                /** 新增进家长表 */
                SchoolStudentParent parent = new SchoolStudentParent();
                parent.setParentName(StringUtil.clearSpace(vo.getParentName2()));
                parent.setRelationship(vo.getRelationship2());
                parent.setWorkAddress(vo.getWorkAddress2());
                parent.setContactAddress(vo.getContactAddress2());
                parent.setTelephone(StringUtil.clearSpace(vo.getTelephone2()));
                parent.setPostalCode(vo.getPostalCode2());
                parent.setUserId(user.getUserId());
                parent.setStudentId(studentId);
                schoolStudentParentMapper.insert(parent);
            }
        }

        /*if (!(vo.getParentName3().equals("")) && !(vo.getTelephone3().equals(""))) {
            LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolStudentParent::getStudentId, studentId)
                    .eq(SchoolStudentParent::getTelephone, vo.getTelephone3());
            List<SchoolStudentParent> parentList = schoolStudentParentMapper.selectList(lqw);
            //存在该家长，更新已改信息
            if (StringUtils.isNotNull(parentList) && parentList.size() > 0) {
                SchoolStudentParent parent = parentList.get(0);
                parent.setParentName(vo.getParentName3());
                parent.setRelationship(vo.getRelationship3());
                parent.setWorkAddress(vo.getWorkAddress3());
                parent.setContactAddress(vo.getContactAddress3());
                parent.setPostalCode(vo.getPostalCode3());
                schoolStudentParentMapper.updateById(parent);
                Long userId = parent.getUserId();
                userMapper.updateUserNameByUserId(vo.getParentName3(), userId);
            } else {
                *//** 新增进用户表 *//*
                SysUser user = new SysUser();
                user.setUserLoginType(PARENT);
                user.setUserName(vo.getParentName3());
                user.setPhonenumber(vo.getTelephone3());
                user.setStudentId(studentId);
                userMapper.insertUser(user);

                *//** 新增进家长表 *//*
                SchoolStudentParent parent = new SchoolStudentParent();
                parent.setParentName(vo.getParentName3());
                parent.setRelationship(vo.getRelationship3());
                parent.setWorkAddress(vo.getWorkAddress3());
                parent.setContactAddress(vo.getContactAddress3());
                parent.setTelephone(vo.getTelephone3());
                parent.setPostalCode(vo.getPostalCode3());
                parent.setUserId(user.getUserId());
                parent.setStudentId(studentId);
                schoolStudentParentMapper.insert(parent);
            }
        }

        if (!(vo.getParentName4().equals("")) && !(vo.getTelephone4().equals(""))) {
            LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolStudentParent::getStudentId, studentId)
                    .eq(SchoolStudentParent::getTelephone, vo.getTelephone4());
            List<SchoolStudentParent> parentList = schoolStudentParentMapper.selectList(lqw);
            //存在该家长，更新已改信息
            if (StringUtils.isNotNull(parentList) && parentList.size() > 0) {
                SchoolStudentParent parent = parentList.get(0);
                parent.setParentName(vo.getParentName4());
                parent.setRelationship(vo.getRelationship4());
                parent.setWorkAddress(vo.getWorkAddress4());
                parent.setContactAddress(vo.getContactAddress4());
                parent.setPostalCode(vo.getPostalCode4());
                schoolStudentParentMapper.updateById(parent);
                Long userId = parent.getUserId();
                userMapper.updateUserNameByUserId(vo.getParentName4(), userId);
            } else {
                *//** 新增进用户表 *//*
                SysUser user = new SysUser();
                user.setUserLoginType(PARENT);
                user.setUserName(vo.getParentName4());
                user.setPhonenumber(vo.getTelephone4());
                user.setStudentId(studentId);
                userMapper.insertUser(user);

                *//** 新增进家长表 *//*
                SchoolStudentParent parent = new SchoolStudentParent();
                parent.setParentName(vo.getParentName4());
                parent.setRelationship(vo.getRelationship4());
                parent.setWorkAddress(vo.getWorkAddress4());
                parent.setContactAddress(vo.getContactAddress4());
                parent.setTelephone(vo.getTelephone4());
                parent.setPostalCode(vo.getPostalCode4());
                parent.setUserId(user.getUserId());
                parent.setStudentId(studentId);
                schoolStudentParentMapper.insert(parent);
            }
        }*/
    }

    //学生赋值
    public SchoolStudent copyStudent(SchoolStudentVO vo, SchoolStudent student) {
        //student.setStudentName(StringUtil.clearSpace(vo.getStudentName()));
        student.setSex(String.valueOf(getSexFromIdCard(StringUtil.clearSpace(vo.getIdCard()))));
        student.setClassId(vo.getClassId());
        //student.setIdCard(StringUtil.clearSpace(vo.getIdCard()));
        student.setBirthday(getBirthDayFromIdCard(StringUtil.clearSpace(vo.getIdCard())));
        //student.setNation(vo.getNation());
        student.setStuTelephone(vo.getStuTelephone());
        student.setPostalCode(vo.getPostalCode());
        student.setNature(vo.getNature());
        student.setProvincialNumber(StringUtil.clearSpace(vo.getProvincialNumber()));
        student.setNationalNumber(StringUtil.clearSpace(vo.getNationalNumber()));
        student.setSchoolNo(StringUtil.clearSpace(vo.getSchoolNo()));
        student.setEnrollmentYear(vo.getEnrollmentYear());
        student.setEnrollmentTime(vo.getEnrollmentTime());
        student.setPlatform(vo.getPlatform());
        student.setNativePlace(vo.getNativePlace());
        student.setHomeAddress(vo.getHomeAddress());
        student.setBirthAddress(vo.getBirthAddress());
        student.setPostalAddress(vo.getPostalAddress());
        student.setStudentStatus(vo.getStudentStatus());
        student.setStudentType(vo.getStudentType());
        student.setRegisteredAddress(vo.getRegisteredAddress());
        student.setRegisteredType(vo.getRegisteredType());
        student.setJuniorSchool(vo.getJuniorSchool());
        student.setRegion(vo.getRegion());
        student.setForeignLanguages(vo.getForeignLanguages());
        student.setAppearance(vo.getAppearance());
        student.setBloodType(vo.getBloodType());
        student.setHealth(vo.getHealth());
        student.setOtherRegions(vo.getOtherRegions());
        student.setFloatingPopulation(vo.getFloatingPopulation());
        student.setSupport(vo.getSupport());
        student.setOnlyChild(vo.getOnlyChild());
        student.setOneCard(StringUtil.clearSpace(vo.getOneCard()));
        student.update();
        return student;
    }

    /**
     * 获取出生日期
     *
     * @return 返回日期格式
     */
    // TODO 新加
    public static Date getBirthDayFromIdCard(String idCard) {
        Date birth = null;
        if (idCard.length() == 18) {
            String year = idCard.substring(6).substring(0, 4);// 得到年份
            String month = idCard.substring(10).substring(0, 2);// 得到月份
            String day = idCard.substring(12).substring(0, 2);// 得到日
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            DateUtils.parseDate(year + "-" + month + "-" + day);
        } else if (idCard.length() == 15) {
            String year = "19" + idCard.substring(6, 8);// 年份
            String month = idCard.substring(8, 10);// 月份
            String day = idCard.substring(10, 12);// 得到日
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            DateUtils.parseDate(year + "-" + month + "-" + day);
        }
        return birth;
    }

    /**
     * 获取性别
     *         0=未知的性别,9=未说明的性别,2=女性,1=男性
     * @return int
     */
    // TODO 新加
    public static int getSexFromIdCard(String idCard) {
        int sex = 0;
        if (idCard.length() == 18) {
            if (Integer.parseInt(idCard.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                sex = 1; // 女
            } else {
                sex = 0; // 男
            }
        } else if (idCard.length() == 15) {
            String usex = idCard.substring(14, 15);// 用户的性别
            if (Integer.parseInt(usex) % 2 == 0) {
                sex = 1; // 女
            } else {
                sex = 0; // 男
            }
        }
        return sex;
    }

    @Override
    public List<SchoolStudentVO> getList(SchoolStudentVO schoolStudent) {
        return schoolStudentMapper.queryList(schoolStudent);
    }

    /**
     * 获取级部学生
     */
    @Override
    public List<SchoolStudentVO> getGradeStudent(List<Long> classIds, SchoolStudentVO studentVO) {
        return schoolStudentMapper.getGradeStudent(classIds, studentVO);
    }

    /**
     * 家长端修改头像（学生头像）
     */
    @Override
    public boolean updateStudentAvatar(Long id, String avatar) {
        return schoolStudentMapper.updateStudentAvatar(id, avatar) > 0;
    }

    /*
     * 批量导入学生照片
     * */
    @Override
    public String importStudentPicture(MultipartFile uploadFile) {
        StringBuilder failureMsg = new StringBuilder();
        /*解压到本地*/

        unpack(uploadFile);

        /*处理图片并匹配学生并添加到数据库中*/
        String os = System.getProperty("os.name");
        File file = null;
        //Windows操作系统
        if (os != null && os.toLowerCase().startsWith("windows")) {
            file = new File("C:\\uploadPicture");
        } else if (os != null && os.toLowerCase().startsWith("linux")) {//Linux操作系统
            file = new File("/uploadPicture");
        }
        File[] files = file.listFiles();
        judgeFiles(files);
        for (File f : files) {
            if (StringUtils.isNotNull(f)) {
                if (f.isDirectory()) {
                    File[] files1 = f.listFiles();
                    if (files1.length == 0 || StringUtils.isNull(files1)) {
                        throw new ServiceException("压缩包内文件夹里无头像信息，请检查");
                    }
                    for (File file1 : files1) {
                        saveUrlToObject(file1, failureMsg);
                        file1.delete();
                    }
                    f.delete();
                    continue;
                }
                //saveUrlToObject(f);
                /*将本地的文件删除*/
                f.delete();
            }
        }
        String s = "";
        if ("".equals(failureMsg.toString())) {
            s = "恭喜您，数据已全部导入成功！";
        } else {
            failureMsg.insert(0, "导入完成，其中不匹配的数据如下：");
            s = failureMsg.toString();
        }
        return s;
    }

    //判断解压出来的数据是否合适
    public File[] judgeFiles(File[] files) {
        if (files.length == 0 || StringUtils.isNull(files)) {
            throw new ServiceException("压缩包内容为空，请检查，支持的格式为：将学生头像照片放在某一文件夹内，将该文件夹压缩成zip格式的压缩包，然后再上传");
        }
        //定义需要删除的文件的索引
        List<File> files1 = new ArrayList<>();
        boolean hasPic = false;
        boolean hasFolder = false;
        //for (File f : files) {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                hasFolder = true;
                if (files[i].listFiles().length > 0 && StringUtils.isNotNull(files[i].listFiles())) {
                    files1 = Arrays.asList(files[i].listFiles());
                }
                for (File file1 : files[i].listFiles()) {
                    //遍历文件夹，看是否有图片格式的照片
                    String filename = file1.getName();
                    String[] split = filename.split("\\.");
                    if (split.length <= 1) {
                        throw new ServiceException("请检查压缩包,支持的格式为：将学生头像照片放在某一文件夹内，文件夹内不要嵌套文件夹，也不要有其他无关文件，将该文件夹压缩成zip格式的压缩包，然后再上传");
                    }
                    /*判断文件是否是jpg和png*/
                    if (split[1].equals("jpg") || split[1].equals("png") || split[1].equals("jpeg") || split[1].equals("bmp")) {
                        hasPic = true;
                    } else {
                        //文件夹内不是以上格式的删除掉
                        file1.delete();
                    }
                }

            } else {
                //不是文件夹的就删除
                files[i].delete();
                files[i] = null;
            }
        }

        //判断压缩格式是否合适，是否有文件夹
        if (!hasFolder) {
            throw new ServiceException("压缩包内无文件夹，请检查，支持的格式为：将学生头像照片放在某一文件夹内，将该文件夹压缩成zip格式的压缩包，然后再上传");
        }
        //files1为空，说明压缩包内文件夹里无任何文件
        if (StringUtils.isNull(files1) || files1.size() == 0) {
            throw new ServiceException("压缩包内的文件夹内无文件，请检查，支持的格式为：将学生头像照片放在某一文件夹内，将该文件夹压缩成zip格式的压缩包，然后再上传");
        }

        //判断文件夹内是否有需要的图片格式
        if (!hasPic) {
            throw new ServiceException("压缩包内文件夹里没有符合所要求的图片格式的学生头像照片，请检查，支持的图片格式：jpg、 png、 jpeg和bmp，暂不支持其它格式");
        }

        return files;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveUrlToObject(File f, StringBuilder failureMsg) {
        String filename = f.getName();
        String[] split = filename.split("\\.");
        //可能是身份证号，可能是省学籍号
        String idCard = split[0];
        /*获取到对应学生的数据  ,先根据身份证查*/
        LambdaQueryWrapper<SchoolStudent> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(SchoolStudent::getIdCard, idCard);
        List<SchoolStudent> studentList1 = schoolStudentMapper.selectList(lqw1);
        //用于标识改数据是根据身份证号还是省学籍号查询出的
        boolean isIdCard = true;
        //如果根据身份证号查不到则根据省学籍号查
        if (StringUtils.isNull(studentList1) || studentList1.size() == 0) {
            isIdCard = false;
            /*获取到对应学生的数据  ,根据省学籍号查*/
            LambdaQueryWrapper<SchoolStudent> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(SchoolStudent::getProvincialNumber, idCard);
            List<SchoolStudent> studentList2 = schoolStudentMapper.selectList(lqw2);
            studentList1.addAll(studentList2);
        }

        if (StringUtils.isNull(studentList1) || studentList1.size() == 0) {
            failureMsg.append("     身份证号或省学籍号为" + idCard + "的学生不存在，无法为该生导入图片");
        } else {
            boolean flag = false;
            if (split.length <= 1) {
                throw new ServiceException("请检查压缩包，压缩包内不要有文件夹；可将学生照片放到同一文件夹下，文件夹下不要有任何与学生照片无关的文件，将该文件夹压缩上传");
            }
            /*判断文件是否是jpg和png*/
            if (split[1].equals("jpg") || split[1].equals("png") || split[1].equals("jpeg") || split[1].equals("bmp")) {
                flag = true;
            } else {
                //throw new ServiceException("支持jpg、 png、 jpeg和bmp图片上传，暂不支持其它格式");
                failureMsg.append("     身份证号或省学籍号为" + idCard + "的图片格式有误，支持jpg、 png、 jpeg和bmp图片上传，暂不支持其它格式");
            }
            /*必须存在这个同学 并且 是图片类型才能进行下一步*/
            if (studentList1.size() != 0 && flag) {
                /*上传图片到服务器，获取地址*/
                /*将file文件转为MultipartFile*/
                MultipartFile cMultiFile = getMultipartFile(f);
                /*上传文件并获取url*/
                String url = uploadFile(cMultiFile);
                /*将路径添加到数据库中*/
                if (isIdCard) {
                    LambdaUpdateWrapper<SchoolStudent> luw = new LambdaUpdateWrapper<>();
                    luw
                            .eq(SchoolStudent::getIdCard, idCard)
                            .set(SchoolStudent::getAvatar, url)
                    ;
                    int i = schoolStudentMapper.update(null, luw);
                } else {
                    LambdaUpdateWrapper<SchoolStudent> luw = new LambdaUpdateWrapper<>();
                    luw
                            .eq(SchoolStudent::getProvincialNumber, idCard)
                            .set(SchoolStudent::getAvatar, url)
                    ;
                    int i = schoolStudentMapper.update(null, luw);
                }
            } else {
                //不能抛异常，，，否则指定目录下会存在脏数据
                //throw new ServiceException("身份证号或省学籍号为" + idCard + "的学生不存在，无法导入图片，请检查");
                failureMsg.append("     身份证号或省学籍号为" + idCard + "的学生不存在，无法为该生导入图片");
            }
        }

    }


    /*上传文件*/
    public String uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getAvatarPath();
            // 上传并返回新文件名称
            String url = FileUploadUtils.upload(filePath, file, MimeTypeUtils.IMAGE_EXTENSION);
            //String url = serverConfig.getUrl() + fileName;

            //int i = url.indexOf("/profile");
            //String substring = url.substring(i);
            //System.out.println(substring);
            return url;
        } catch (Exception e) {
            throw new ServiceException("上传异常");
        }
    }


    /*File转为MultipartFile*/
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }


    /*解压*/
    public void unpack(MultipartFile uploadFile) {
        boolean isZipPack = true;

        // 解压目录
        String packFileStr = "";

        String os = System.getProperty("os.name");
        File packFile = null;
        //Windows操作系统
        if (os != null && os.toLowerCase().startsWith("windows")) {
            packFileStr = "C:\\uploadPicture";
            packFile = new File(packFileStr);
        } else if (os != null && os.toLowerCase().startsWith("linux")) {//Linux操作系统
            packFileStr = "/uploadPicture";
            packFile = new File(packFileStr);
            packFile.setWritable(true, false);
        }

        //不存在则创建
        if (!packFile.exists()) {
            boolean mkdirs = packFile.mkdirs();
        } else {
            //存在则删除其中数据
            remove(packFile);
        }

        if (uploadFile == null) {
            throw new RuntimeException("请上传文件");
        }
        String contentType = uploadFile.getContentType();
        String filename = uploadFile.getOriginalFilename();
        String[] subFileName = filename.split("\\.");
        //将压缩包保存在指定路径
        String packFilePath = packFileStr + File.separator + filename;
        if (judgeIsZip(ZIP_FILE, contentType) || subFileName[1].equals("zip")) {
            //zip解压缩处理
        }
//        else if (RAR_FILE.equals(contentType)) {
//            //rar解压缩处理
//            isZipPack = false;
//        }
        else {
            throw new RuntimeException("上传的压缩包格式不正确,仅支持zip压缩文件!");
        }
        File file = new File(packFilePath);
        try {
            uploadFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("压缩文件到:" + packFileStr + " 失败!");
        }
        if (isZipPack) {
            //zip压缩包
            UnPackeUtil.unPackZip(file, null, packFileStr);
            //删除系统对应文件夹中的zip文件
            file.delete();
        } else {
            //rar压缩包
//            RandomAccessFile randomAccessFile = null;
//            IInArchive inArchive = null;
//
//            randomAccessFile = new RandomAccessFile(packFilePath, "r");
//            inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
//
//            int[] in = new int[inArchive.getNumberOfItems()];
//            for (int i = 0; i < in.length; i++) {
//                in[i] = i;
//            }
//            inArchive.extract(in, false, new ExtractCallback(inArchive, "366", packFileStr));

        }
        //获取压缩包名称
        filename = filename.substring(0, filename.lastIndexOf("."));

        System.out.println("解压成功，解压目录：" + filename);
        //可以根据解压路径、压缩包名称、文件名称，取出对应文件进行操作
    }

    public boolean judgeIsZip(String[] fileType, String contentType) {
        boolean flag = false;

        for (String i : fileType) {
            if (contentType.equals(i)) {
                flag = true;
            }
        }
        return flag;
    }

    //删除指定文件夹下的所有内容
    public void remove(File file) {
        File[] files = file.listFiles();//将file子目录及子文件放进文件数组
        if (files != null) {//如果包含文件进行删除操作
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {//删除子文件
                    files[i].delete();
                } else if (files[i].isDirectory()) {//通过递归方法删除子目录的文件
                    remove(files[i]);
                }
                files[i].delete();//删除子目录
            }
        }
    }

}
