package com.yida.data.user.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.Dict;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.entity.consume.EduStudentConsumeCard;
import com.yida.data.common.core.entity.school.EduSchoolStudentInformation;
import com.yida.data.common.core.entity.user.EduParent;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.entity.user.enums.StudentTypeEnum;
import com.yida.data.common.core.entity.user.enums.UserDeptTypeEnum;
import com.yida.data.common.core.enums.DictType;
import com.yida.data.common.core.utils.EasyExcelUtil;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.device.feign.consume.RemoteConsumeCardService;
import com.yida.data.system.feign.RemoteCommonService;
import com.yida.data.user.dto.*;
import com.yida.data.user.mapper.EduSchoolStudentInformationMapper;
import com.yida.data.user.service.EduStudentService;
import com.yida.data.user.service.ImportWelcomeStudentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 导入数据service层
 *
 * @author ZYJ
 * @date 2021/8/23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ImportWelcomeStudentServiceImpl implements ImportWelcomeStudentService {

    private final EduStudentService eduStudentService;
    private final EduSchoolStudentInformationMapper eduSchoolStudentInformationMapper;

    private final CommonService commonService;
    private final RemoteCommonService remoteCommonService;

    @Resource
    private RemoteConsumeCardService remoteConsumeCardService;


    /**
     * 保存导入数据
     *
     * @param concurrentHashMap 需要保存的用户数据
     * @param errorMap          导入错误数据集合
     * @param schoolId          学校id
     * @param timestamp         时间戳
     * @author ZYJ
     * @date 2021/8/23 16:52
     */
    @Override
    public void saveExcelData(ConcurrentHashMap<Integer, WelcomeStudentImportDTO> concurrentHashMap,
                              ConcurrentHashMap<Integer, Object> errorMap,
                              Long schoolId,
                              long timestamp) {
        // 当前登录用户信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        // 当前时间
        LocalDateTime now = LocalDateTime.now();

        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            // 保存前判断是否已存在
            for (Map.Entry<Integer, WelcomeStudentImportDTO> entry : concurrentHashMap.entrySet()) {
                // 获取对应key-value值
                Integer i = entry.getKey();
                WelcomeStudentImportDTO welcomeStudentDTO = entry.getValue();
                // 验证导入信息是否为空
                if (!checkStudentImportInfo(errorMap, welcomeStudentDTO, i)) {
                    continue;
                }
                // 验证身份证号码在当前学校的迎新表中是否重复
                List<EduSchoolStudentInformation> studentList =
                        this.eduSchoolStudentInformationMapper.selectList(Wrappers.lambdaQuery(new EduSchoolStudentInformation())
                                .eq(EduSchoolStudentInformation::getStudentIdCard, welcomeStudentDTO.getStudentIdCard())
                                .eq(EduSchoolStudentInformation::getSchoolId, schoolId)
                        );
                if (!studentList.isEmpty()) {
                    log.error("身份证号码已存在: {}", welcomeStudentDTO.toString());
                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.ID_CARD_EXIST.getValue());
                    continue;
                }
                // 验证学区是否存在
                EduUserDept campus = commonService.getUserDeptBySchoolIdAndNameAndType(
                        welcomeStudentDTO.getCampusName(), UserDeptTypeEnum.CAMPUS_TYPE.getValue(),
                        schoolId, String.valueOf(timestamp), schoolId);
                if (!Optional.ofNullable(campus).isPresent()) {
                    log.error("学区名称错误: {}", welcomeStudentDTO.toString());
                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.CAMPUS_NAME_ERROR.getValue());
                    continue;
                }
                // 验证学段是否存在
                EduUserDept section = commonService.getUserDeptBySchoolIdAndNameAndType(
                        welcomeStudentDTO.getSectionName(), UserDeptTypeEnum.SECTION_TYPE.getValue(),
                        schoolId, String.valueOf(timestamp), campus.getDeptId());
                if (!Optional.ofNullable(section).isPresent()) {
                    log.error("学段名称错误: {}", welcomeStudentDTO.toString());
                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.SECTION_NAME_ERROR.getValue());
                    continue;
                }
                // 验证年级是否存在
                EduUserDept grade = commonService.getUserDeptBySchoolIdAndNameAndType(
                        welcomeStudentDTO.getGradeName(), UserDeptTypeEnum.GRADE_TYPE.getValue(),
                        schoolId, String.valueOf(timestamp), section.getDeptId());
                if (!Optional.ofNullable(grade).isPresent()) {
                    log.error("年级名称错误: {}", welcomeStudentDTO.toString());
                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.GRADE_NAME_ERROR.getValue());
                    continue;
                }
                // 验证班级是否存在
                EduUserDept classDept = commonService.getUserDeptBySchoolIdAndNameAndType(
                        welcomeStudentDTO.getClassName(), UserDeptTypeEnum.CLASS_TYPE.getValue(),
                        schoolId, String.valueOf(timestamp), grade.getDeptId());
                if (!Optional.ofNullable(classDept).isPresent()) {
                    log.error("班级名称错误: {}", welcomeStudentDTO.toString());
                    errorMap.put(i, "第" + i + "行：" + ResultMsgType.CLASS_NAME_ERROR.getValue());
                    continue;
                }
                // 保存数据
                EduSchoolStudentInformation saveInfo = new EduSchoolStudentInformation();
                BeanUtils.copyProperties(welcomeStudentDTO, saveInfo);
                // 设置无法拷贝属性
                saveInfo.setCreateDate(now);
                saveInfo.setCreateId(currentUser != null ? currentUser.getUserId() : 1L);
                saveInfo.setSchoolId(schoolId);
                saveInfo.setSchoolName(commonService.getDept(schoolId).getDeptName());
                saveInfo.setCampusId(campus.getDeptId());
                saveInfo.setSectionId(section.getDeptId());
                saveInfo.setGradeId(grade.getDeptId());
                saveInfo.setClassId(classDept.getDeptId());
                // 学号
                if (!StringUtils.isNotEmpty(saveInfo.getStudentNumber())) {
                    String stuNumber = StrUtil.uuid().replace("-", "");
                    saveInfo.setStudentNumber(stuNumber);
                }
                this.eduSchoolStudentInformationMapper.insert(saveInfo);
            }
        }
    }

    /**
     * 验证智慧迎新导入信息是否为空
     *
     * @param errorMap          返回的错误信息
     * @param welcomeStudentDTO 当前行导入数据
     * @param i                 Excel第几行
     * @return boolean
     * @author ZYJ
     * @date 2021/8/23 17:30
     */
    private boolean checkStudentImportInfo(ConcurrentHashMap<Integer, Object> errorMap,
                                           WelcomeStudentImportDTO welcomeStudentDTO, Integer i) {
        // 判断学生名称是否为空
        if (!StringUtils.isNotBlank(welcomeStudentDTO.getStudentName())) {
            errorMap.put(i, "第" + i + "行：学生姓名为空");
            return false;
        }
        // 判断身份证号码是否为空
        else if (!StringUtils.isNotBlank(welcomeStudentDTO.getStudentIdCard())) {
            errorMap.put(i, "第" + i + "行：身份证号码为空");
            return false;
        }
        // 判断校区名称是否为空
        else if (!StringUtils.isNotBlank(welcomeStudentDTO.getCampusName())) {
            errorMap.put(i, "第" + i + "行：校区名称为空");
            return false;
        }
        // 判断学段名称是否为空
        else if (!StringUtils.isNotBlank(welcomeStudentDTO.getSectionName())) {
            errorMap.put(i, "第" + i + "行：学段名称为空");
            return false;
        }
        // 判断年级名称是否为空
        else if (!StringUtils.isNotBlank(welcomeStudentDTO.getGradeName())) {
            errorMap.put(i, "第" + i + "行：年级名称为空");
            return false;
        }
        // 判断班级名称是否为空
        else if (!StringUtils.isNotBlank(welcomeStudentDTO.getClassName())) {
            errorMap.put(i, "第" + i + "行：班级名称为空");
            return false;
        }
        return true;
    }

    /**
     * 保存一键邀请导入数据
     *
     * @param concurrentHashMap 需要保存的用户数据
     * @param errorList         导入错误数据集合
     * @param schoolId          学校id
     * @param uuid              当前导入数据唯一标识
     * @param currentUser       当前登录用户信息
     * @author ZYJ
     * @date 2021/8/24 17:33
     */
    @Override
    public void saveInviteExcelData(ConcurrentHashMap<Integer, WelcomeInviteImportDTO> concurrentHashMap,
                                    List<StudentErrorExportDTO> errorList,
                                    Long schoolId, String uuid, CurrentUser currentUser) {
        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            // 保存前判断是否已存在
            for (Map.Entry<Integer, WelcomeInviteImportDTO> entry : concurrentHashMap.entrySet()) {

                StudentErrorExportDTO dto = new StudentErrorExportDTO();
                WelcomeInviteImportDTO welcomeInviteImportDTO = new WelcomeInviteImportDTO();
                try {
                    welcomeInviteImportDTO = entry.getValue();
                    BeanUtils.copyProperties(welcomeInviteImportDTO, dto);
                    // 验证导入信息是否为空
                    if (!checkInviteImportInfo(dto, welcomeInviteImportDTO)) {
                        errorList.add(dto);
                        continue;
                    }
                    // 验证学号在当前学校的学生表中是否重复
                    EduStudent studentNumberEntity = eduStudentService.getOne(
                            Wrappers.lambdaQuery(new EduStudent())
                                    .eq(EduStudent::getStuNumber, welcomeInviteImportDTO.getStudentNumber())
                                    .eq(EduStudent::getSchoolId, schoolId));

                    if (Objects.nonNull(studentNumberEntity)) {
                        log.error("学号已存在: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO));
                        dto.setErrorMessage(ResultMsgType.STUDENT_NUMBER_EXIST.getValue());
                        errorList.add(dto);
                        continue;
                    }
                    // 验证部门信息是否正确
                    EduStudent eduStudent = checkDeptInfo(dto, welcomeInviteImportDTO, schoolId, uuid);
                    if (Objects.isNull(eduStudent)) {
                        errorList.add(dto);
                        continue;
                    }
                    // TODO 2021/08/25 后续此处需要判断同一个学生的四个家长手机号不能相同
                    // 整理家长数据
                    List<EduParent> parentList = setParentInfo(welcomeInviteImportDTO, schoolId);
                    eduStudent.setParents(parentList);

                    // 保存学生信息
                    eduStudentService.saveStudent(eduStudent, currentUser, false);
                } catch (Exception e) {
                    log.error("导入学生信息失败: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO), e);
                    dto.setErrorMessage("数据异常！");
                    errorList.add(dto);
                }
            }
        }
    }

    /**
     * 验证一键邀请导入信息是否为空
     *
     * @param dto                    返回的错误信息实体类
     * @param welcomeInviteImportDTO 当前行导入数据
     * @return boolean
     * @author ZYJ
     * @date 2021/8/24 17:44
     */
    private boolean checkInviteImportInfo(StudentErrorExportDTO dto, WelcomeInviteImportDTO welcomeInviteImportDTO) {
        BeanUtils.copyProperties(welcomeInviteImportDTO, dto);
        // 判断学生名称是否为空
        if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getStudentName())) {
            dto.setErrorMessage("学生姓名为空");
            return false;
        }
        // 判断校区名称是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getCampusName())) {
            dto.setErrorMessage("校区名称为空");
            return false;
        }
        // 判断学段名称是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getSectionName())) {
            dto.setErrorMessage("学段名称为空");
            return false;
        }
        // 判断年级名称是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getGradeName())) {
            dto.setErrorMessage("年级名称为空");
            return false;
        }
        // 判断班级名称是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getClassName())) {
            dto.setErrorMessage("班级名称为空");
            return false;
        }
        // 判断学号是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getStudentNumber())) {
            dto.setErrorMessage("学生学号为空");
            return false;
        }
        // 判断家长一关系是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTypeName())) {
            dto.setErrorMessage("家长一关系为空");
            return false;
        }
        // 判断家长一电话是否为空
        else if (!StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTelephone())) {
            dto.setErrorMessage("家长一电话为空");
            return false;
        }
        return true;
    }

    /**
     * 验证部门信息是否正确
     *
     * @param dto                    返回的错误信息实体类
     * @param welcomeInviteImportDTO 当前行导入数据
     * @param schoolId               学校id
     * @param uuid                   当前导入数据唯一标识
     * @return com.yida.data.common.core.entity.user.EduStudent
     * @author ZYJ
     * @date 2021/8/25 15:39
     */
    private EduStudent checkDeptInfo(StudentErrorExportDTO dto, WelcomeInviteImportDTO welcomeInviteImportDTO,
                                     Long schoolId, String uuid) {
        // 验证学区是否存在
        EduUserDept campus = this.commonService.getUserDeptBySchoolIdAndNameAndType(
                welcomeInviteImportDTO.getCampusName(), UserDeptTypeEnum.CAMPUS_TYPE.getValue(), schoolId, uuid, schoolId);
        if (!Optional.ofNullable(campus).isPresent()) {
            log.error("学区名称错误: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO));
            dto.setErrorMessage(ResultMsgType.CAMPUS_NAME_ERROR.getValue());
            return null;
        }
        // 验证学段是否存在
        EduUserDept section = this.commonService.getUserDeptBySchoolIdAndNameAndType(
                welcomeInviteImportDTO.getSectionName(), UserDeptTypeEnum.SECTION_TYPE.getValue(), schoolId, uuid,
                campus.getDeptId());
        if (!Optional.ofNullable(section).isPresent()) {
            log.error("学段名称错误: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO));
            dto.setErrorMessage(ResultMsgType.SECTION_NAME_ERROR.getValue());
            return null;
        }
        // 验证年级是否存在
        EduUserDept grade = this.commonService.getUserDeptBySchoolIdAndNameAndType(
                welcomeInviteImportDTO.getGradeName(), UserDeptTypeEnum.GRADE_TYPE.getValue(), schoolId, uuid, section.getDeptId());
        if (!Optional.ofNullable(grade).isPresent()) {
            log.error("年级名称错误: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO));
            dto.setErrorMessage(ResultMsgType.GRADE_NAME_ERROR.getValue());
            return null;
        }
        // 验证班级是否存在
        EduUserDept classDept = this.commonService.getUserDeptBySchoolIdAndNameAndType(
                welcomeInviteImportDTO.getClassName(), UserDeptTypeEnum.CLASS_TYPE.getValue(), schoolId, uuid, grade.getDeptId());
        if (!Optional.ofNullable(classDept).isPresent()) {
            log.error("班级名称错误: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO));
            dto.setErrorMessage(ResultMsgType.CLASS_NAME_ERROR.getValue());
            return null;
        }
        LocalDate startDate = null;
        // 处理入学时间
        if (StrUtil.isNotBlank(welcomeInviteImportDTO.getStartDate())) {
            try {
                startDate = LocalDateTimeUtil.parseDate(welcomeInviteImportDTO.getStartDate(), DatePattern.NORM_DATE_PATTERN);
            } catch (Exception e) {
                log.error("时间格式错误: {}", JSONUtil.toJsonStr(welcomeInviteImportDTO));
                dto.setErrorMessage(ResultMsgType.START_DATE_ERROR.getValue());
                return null;
            }
        }

        String familyType;
        // 判断家庭类型
        if (StringUtils.isNotBlank(welcomeInviteImportDTO.getFamilyName())) {
            familyType = checkFamilyType(welcomeInviteImportDTO.getFamilyName());
        } else {
            familyType = "0";
        }
        // 判断政治面貌
        if (StrUtil.isNotBlank(welcomeInviteImportDTO.getPoliticsStatus())) {
            Dict dict = commonService.getDictByTypeAndValueOrLabel("politics_status", null, welcomeInviteImportDTO.getPoliticsStatus());
            if (Objects.nonNull(dict)) {
                welcomeInviteImportDTO.setPoliticsStatus(dict.getValue());
            } else {
                welcomeInviteImportDTO.setPoliticsStatus("");
            }
        }
        // 判断性别
        if (StrUtil.isNotBlank(welcomeInviteImportDTO.getStuSex())) {
            Dict dict = commonService.getDictByTypeAndValueOrLabel("gender", null, welcomeInviteImportDTO.getStuSex());
            if (Objects.nonNull(dict)) {
                welcomeInviteImportDTO.setStuSex(dict.getValue());
            } else {
                welcomeInviteImportDTO.setStuSex("");
            }
        }
        // 判断民族
        if (StrUtil.isNotBlank(welcomeInviteImportDTO.getNation())) {
            Dict dict = commonService.getDictByTypeAndValueOrLabel("nation", null, welcomeInviteImportDTO.getNation());
            if (Objects.nonNull(dict)) {
                welcomeInviteImportDTO.setNation(dict.getValue());
            } else {
                welcomeInviteImportDTO.setNation("");
            }
        }
        // 判断学籍
        if (StrUtil.isNotBlank(welcomeInviteImportDTO.getStudentStatus())) {
            Dict dict = commonService.getDictByTypeAndValueOrLabel("student_status", null, welcomeInviteImportDTO.getStudentStatus());
            if (Objects.nonNull(dict)) {
                welcomeInviteImportDTO.setStudentStatus(dict.getValue());
            } else {
                welcomeInviteImportDTO.setStudentStatus("zaidu");
            }
        }

        // 保存数据
        EduStudent eduStudent = new EduStudent();
        BeanUtils.copyProperties(welcomeInviteImportDTO, eduStudent);
        // 设置无法拷贝属性
        eduStudent.setFamilyType(familyType);
        if (Objects.nonNull(startDate)) {
            eduStudent.setStartDate(startDate);
        }
        eduStudent.setStuName(welcomeInviteImportDTO.getStudentName());
        eduStudent.setSchoolId(schoolId);
        eduStudent.setSchoolName(commonService.getDept(schoolId).getDeptName());
        eduStudent.setCampusId(campus.getDeptId());
        eduStudent.setSectionId(section.getDeptId());
        eduStudent.setGradeId(grade.getDeptId());
        eduStudent.setClassId(classDept.getDeptId());
        // 设置学号和企业微信id
        eduStudent.setStuNumber(welcomeInviteImportDTO.getStudentNumber());
        // 设置创建信息
//        eduStudent.setStartDate(LocalDate.now());

        // 设置住宿类型
        if (ObjectUtil.isNotNull(welcomeInviteImportDTO.getType()) && ObjectUtil.equal(StudentTypeEnum.DORM_TYPE.getName(), welcomeInviteImportDTO.getType())) {
            eduStudent.setType(StudentTypeEnum.DORM_TYPE.getValue());
        } else {
            eduStudent.setType(StudentTypeEnum.SCHOOL_TYPE.getValue());
        }

        return eduStudent;
    }

    private String checkFamilyType(String familyName) {
        // 查询家庭类型
        List<Dict> familyTypeList = remoteCommonService.getDict(DictType.FAMILY_TYPE.getValue()).getData();
        String[] familyArray = familyName.split(StringConstant.DASH);

        List<String> returnFamily = new ArrayList<>();
        // 匹配家庭类型
        for (Dict dict : familyTypeList) {
            for (String familyType : familyArray) {
                if (familyType.contains(dict.getLabel())) {
                    returnFamily.add(dict.getValue());
                }
            }

        }
        return returnFamily.stream().distinct().collect(Collectors.joining(StringConstant.COMMA));
    }

    /**
     * 封装家长数据
     *
     * @param welcomeInviteImportDTO Excel一键邀请信息导入类
     * @param schoolId               学校id
     * @return java.util.List<com.yida.data.common.core.entity.user.EduParent>
     * @author ZYJ
     * @date 2021/8/25 16:45
     */
    private List<EduParent> setParentInfo(WelcomeInviteImportDTO welcomeInviteImportDTO, Long schoolId) {
        // 返回的家长集合数据
        List<EduParent> list = new ArrayList<>();
        // 设置家长一数据
        list.add(EduParent.builder()
                .mobile(welcomeInviteImportDTO.getParentTelephone())
                .parentType(welcomeInviteImportDTO.getParentTypeName())
                .schoolId(schoolId)
                .build());
        // 判断家长二数据是否存在
        if (StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTypeNameSecond())
                && StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTelephoneSecond())) {
            list.add(EduParent.builder()
                    .mobile(welcomeInviteImportDTO.getParentTelephoneSecond())
                    .parentType(welcomeInviteImportDTO.getParentTypeNameSecond())
                    .schoolId(schoolId)
                    .build());
        }
        // 判断家长三数据是否存在
        if (StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTypeNameThird())
                && StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTelephoneThird())) {
            list.add(EduParent.builder()
                    .mobile(welcomeInviteImportDTO.getParentTelephoneThird())
                    .parentType(welcomeInviteImportDTO.getParentTypeNameThird())
                    .schoolId(schoolId)
                    .build());
        }
        // 判断家长四数据是否存在
        if (StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTypeNameFourth())
                && StringUtils.isNotBlank(welcomeInviteImportDTO.getParentTelephoneFourth())) {
            list.add(EduParent.builder()
                    .mobile(welcomeInviteImportDTO.getParentTelephoneFourth())
                    .parentType(welcomeInviteImportDTO.getParentTypeNameFourth())
                    .schoolId(schoolId)
                    .build());
        }
        return list;
    }

    /**
     * 保存校园卡号导入数据
     *
     * @param concurrentHashMap 需要保存的用户数据
     * @param errorList         导入错误数据集合
     * @param schoolId          学校id
     * @param currentUser       当前登录用户信息
     * @author ZYJ
     * @date 2023/2/19 14:45
     */
    @Override
    public void saveCardExcelData(ConcurrentHashMap<Integer, CardImportDTO> concurrentHashMap,
                                  List<CardErrorExportDTO> errorList, Long schoolId, CurrentUser currentUser) {
        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            // 保存前判断是否已存在
            for (Map.Entry<Integer, CardImportDTO> entry : concurrentHashMap.entrySet()) {
                CardErrorExportDTO dto = new CardErrorExportDTO();
                CardImportDTO cardImportDTO = new CardImportDTO();
                try {
                    cardImportDTO = entry.getValue();
                    BeanUtils.copyProperties(cardImportDTO, dto);
                    // 验证导入信息是否为空
                    if (!checkCardImportInfo(dto, cardImportDTO)) {
                        errorList.add(dto);
                        continue;
                    }
                    // 验证学号在当前学校的学生表中是否存在
                    EduStudent studentNumberEntity = eduStudentService.getOne(
                            Wrappers.lambdaQuery(new EduStudent())
                                    .eq(EduStudent::getStuNumber, cardImportDTO.getStuNumber().trim())
                                    .eq(EduStudent::getSchoolId, schoolId));

                    if (Objects.isNull(studentNumberEntity)) {
                        log.error("学号不存在: {}", cardImportDTO.toString());
                        dto.setErrorMessage(ResultMsgType.STUDENT_NUMBER_NOT_EXIST.getValue());
                        errorList.add(dto);
                        continue;
                    }
                    // 验证部门信息是否重复
                    EduStudent eduStudent = eduStudentService.getOne(
                            Wrappers.lambdaQuery(new EduStudent())
                                    .eq(EduStudent::getStuCardNumber, cardImportDTO.getStuCardNumber().trim())
                                    .eq(EduStudent::getSchoolId, schoolId));
                    if (Objects.nonNull(eduStudent)) {
                        log.error("校园卡号已存在: {}", cardImportDTO.toString());
                        dto.setErrorMessage(ResultMsgType.STUDENT_CARD_NUMBER_EXIST.getValue());
                        errorList.add(dto);
                        continue;
                    }
                    // 保存校园卡号
                    studentNumberEntity.setStuCardNumber(cardImportDTO.getStuCardNumber().trim());
                    eduStudentService.saveOrUpdate(studentNumberEntity);
                    // 保存学生消费机信息管理
                    remoteConsumeCardService.saveConsumeCard(
                            EduStudentConsumeCard.builder()
                                    .deptId(schoolId)
                                    .studentId(studentNumberEntity.getId())
                                    .build());

                } catch (Exception e) {
                    log.error("导入校园卡号信息失败: {}", cardImportDTO.toString(), e);
                    dto.setErrorMessage("数据异常！");
                    errorList.add(dto);
                }
            }
        }
    }

    /**
     * 验证校园卡好导入信息是否为空
     *
     * @param dto           返回的错误信息实体类
     * @param cardImportDTO 当前行导入数据
     * @return boolean
     * @author ZYJ
     * @date 2023/2/19 14:53
     */
    private boolean checkCardImportInfo(CardErrorExportDTO dto, CardImportDTO cardImportDTO) {
        BeanUtils.copyProperties(cardImportDTO, dto);
        // 判断学生学号是否为空
        if (!StringUtils.isNotBlank(cardImportDTO.getStuNumber())) {
            dto.setErrorMessage("学生学号为空");
            return false;
        }
        // 判断校园卡号是否为空
        if (!StringUtils.isNotBlank(cardImportDTO.getStuCardNumber())) {
            dto.setErrorMessage("校园卡号为空");
            return false;
        }
        return true;
    }
}
