package com.yida.data.school.smart.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.FebsConstant;
import com.yida.data.common.core.entity.school.EduDormitory;
import com.yida.data.common.core.entity.school.EduDormitoryRoom;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeDepartment;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideDormRecord;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideRoster;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideStep;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideStepDorm;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideStepDormFix;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.utils.QrCodeUtil;
import com.yida.data.school.dto.index.ListDormRoomDTO;
import com.yida.data.school.dto.smart.ClassFixImportDTO;
import com.yida.data.school.dto.smart.ClassImportDTO;
import com.yida.data.school.dto.smart.CustomDormImportDTO;
import com.yida.data.school.dto.smart.DormImportDTO;
import com.yida.data.school.dto.smart.DormImportFixDTO;
import com.yida.data.school.dto.smart.GuideRosterErrorExportDTO;
import com.yida.data.school.dto.smart.GuideRosterImportDTO;
import com.yida.data.school.facility.service.EduDormitoryRoomService;
import com.yida.data.school.facility.service.EduDormitoryService;
import com.yida.data.school.smart.excel.CustomDormExcelListener;
import com.yida.data.school.smart.excel.ExcelListener;
import com.yida.data.school.smart.excel.GuideRosterExcelListener;
import com.yida.data.school.smart.mapper.EduSmartWelcomeGuideRosterMapper;
import com.yida.data.school.smart.mapper.EduSmartWelcomeGuideStepDormMapper;
import com.yida.data.school.smart.service.EduSmartWelcomeDepartmentService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideDormRecordService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideStepDormFixService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideStepDormService;
import com.yida.data.school.vo.smart.ClassFixImportVO;
import com.yida.data.school.vo.smart.ClassImportVO;
import com.yida.data.school.vo.smart.DormImportFixVO;
import com.yida.data.school.vo.smart.DormImportVO;
import com.yida.data.school.vo.smart.ImportRosterDataVO;
import com.yida.data.school.vo.smart.WelcomeImportProgress;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;

/**
 * 智慧迎新宿舍预分表Service实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduSmartWelcomeGuideStepDormServiceImpl extends ServiceImpl
    <EduSmartWelcomeGuideStepDormMapper, EduSmartWelcomeGuideStepDorm> implements EduSmartWelcomeGuideStepDormService {

    private final RedisService redisService;
    private final EduSmartWelcomeGuideRosterMapper eduSmartWelcomeGuideRosterMapper;
    private final EduSmartWelcomeGuideDormRecordService eduSmartWelcomeGuideDormRecordService;
    private final EduDormitoryService eduDormitoryService;
    private final EduDormitoryRoomService eduDormitoryRoomService;
    private final EduSmartWelcomeDepartmentService eduSmartWelcomeDepartmentService;
    private final EduSmartWelcomeGuideStepDormFixService eduSmartWelcomeGuideStepDormFixService;
    @Value("${febs.uploadUrl}")
    private String uploadUrl;

    @Override
    public void downloadDormTemplate(HttpServletResponse response) {
        try {
            String fileName = "宿舍预选导入模板.xlsx";
            // 获取导入文件模板
            ClassPathResource classPathResource = new ClassPathResource("template/" + fileName);
            InputStream inputStream = classPathResource.getInputStream();
            com.yida.data.common.core.utils.FileUtil
                .download(com.yida.data.common.core.utils.FileUtil.inputStreamToFile(inputStream), fileName, false, response);
        } catch (Exception e) {
            throw new FebsException("下载宿舍预选导入模板失败");
        }
    }

    @Override
    public void downloadDormFixTemplate(HttpServletResponse response) {
        try {
            String fileName = "固定宿舍学生导入模板.xlsx";
            // 获取导入文件模板
            ClassPathResource classPathResource = new ClassPathResource("template/" + fileName);
            InputStream inputStream = classPathResource.getInputStream();
            com.yida.data.common.core.utils.FileUtil
                .download(com.yida.data.common.core.utils.FileUtil.inputStreamToFile(inputStream), fileName, false, response);
        } catch (Exception e) {
            throw new FebsException("下载固定宿舍学生导入模板失败");
        }
    }

    @Override
    public void importDormData(MultipartFile file, String importKey, CurrentUser currentUser) {
        // 错误信息文件excel
        File errorFile = null;
        try {
            // 验证文件类型
            if (!FileUtil.checkMultipartFile(file, FebsConstant.EXCEL_FILE_TYPE)) {
                return;
            }
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            // 调用导入方法
            ExcelListener<DormImportDTO> listener = new ExcelListener<DormImportDTO>();
            List<DormImportDTO> listMap = new ArrayList<>();
            try {
                ExcelReader excelReader = EasyExcelFactory.read(file.getInputStream(), DormImportDTO.class, listener)
                    .headRowNumber(1).build();
                excelReader.readAll();
                listMap = listener.getDatas();
                excelReader.finish();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            Integer current = 0;
            redisService.set(CachePrefixConstant.WELCOME_DORM_IMPOST_PROGRESS + importKey,
                WelcomeImportProgress.<DormImportDTO>builder().importKey(importKey).total(listMap.size()).current(0)
                    .importStatus(0).build());

            List<DormImportVO> dormImportVOList = new ArrayList<>();

            List<EduSmartWelcomeDepartment> departmentList = eduSmartWelcomeDepartmentService.list();
            List<EduDormitory> dormitoryList = eduDormitoryService.list(Wrappers.lambdaQuery(new EduDormitory())
                .eq(EduDormitory::getSchoolId, currentUser.getDeptId()));
            ListDormRoomDTO listDormRoomDTO = new ListDormRoomDTO();
            listDormRoomDTO.setSchoolId(currentUser.getDeptId());
            List<EduDormitoryRoom> eduDormitoryRooms = eduDormitoryRoomService.listDormRoom(listDormRoomDTO);

            List<DormImportDTO> errorList = new ArrayList<>();

            for (DormImportDTO dormImportDTO : listMap) {
                current++;
                redisService.set(CachePrefixConstant.WELCOME_DORM_IMPOST_PROGRESS + importKey,
                    WelcomeImportProgress.builder().importKey(importKey).total(listMap.size()).current(current).importStatus(0)
                        .build());

                DormImportVO vo = new DormImportVO();
                BeanUtils.copyProperties(dormImportDTO, vo);

                //宿舍楼
                List<EduDormitory> dormitories = dormitoryList.stream().filter(d -> d.getName().equals(vo.getDormName()))
                    .collect(Collectors.toList());

                if (CollUtil.isEmpty(dormitories)) {
                    errorList.add(dormImportDTO);
                    continue;
                }

                Long dormId = dormitories.get(0).getId();
                //寝室号
                List<EduDormitoryRoom> dormitoryRoomList = eduDormitoryRooms.stream()
                    .filter(d -> d.getDormName().equals(vo.getDormName()) && d.getName().equals(vo.getDormRoomName()))
                    .collect(Collectors.toList());
                if (CollUtil.isEmpty(dormitoryRoomList)) {
                    errorList.add(dormImportDTO);
                    continue;
                }
                Long dormRoomId = dormitoryRoomList.get(0).getId();

                //系部ID
                List<EduSmartWelcomeDepartment> departmentList1 = departmentList.stream()
                    .filter(d -> d.getName().equals(vo.getDepartmentName()))
                    .collect(Collectors.toList());
                if (CollUtil.isEmpty(departmentList1)) {
                    errorList.add(dormImportDTO);
                    continue;
                }
                Long departmentId = departmentList1.get(0).getId();
                //专业ID
                List<EduSmartWelcomeDepartment> majorList = departmentList.stream()
                    .filter(d -> d.getName().equals(vo.getMajorName()))
                    .collect(Collectors.toList());
                if (CollUtil.isEmpty(majorList)) {
                    errorList.add(dormImportDTO);
                    continue;
                }
                Long majorId = majorList.get(0).getId();

                vo.setDepartmentId(departmentId);
                vo.setMajorId(majorId);
                vo.setDormId(dormId);
                vo.setDormRoomId(dormRoomId);
                vo.setGender("男".equals(dormImportDTO.getGender()) ? 0 : 1);
                dormImportVOList.add(vo);
            }
            WelcomeImportProgress<DormImportVO> build = WelcomeImportProgress.<DormImportVO>builder().importKey(importKey)
                .total(listMap.size()).current(listMap.size())
                .importStatus(1)
                .dataList(dormImportVOList).build();

            if (CollUtil.isNotEmpty(errorList)) {
                // 错误信息文件名称
                String fileName = FileUtil.getLocalUploadAddress() + UUID.randomUUID() + ".xlsx";
                EasyExcel.write(fileName, DormImportDTO.class)
                    .sheet("错误信息")
                    .doWrite(errorList);
                // 上传到媒资
                errorFile = new File(fileName);
                String url = FileUtil.uploadFileToMediaServer(uploadUrl, errorFile);
                build.setErrorPath(url);
                build.setImportStatus(2);
            }
            redisService.set(CachePrefixConstant.WELCOME_DORM_IMPOST_PROGRESS + importKey, build);
            stopWatch.stop();
            log.info("导入宿舍预分数据总共耗时: {}", stopWatch.getTotalTimeSeconds() + "秒");
        } catch (Exception e) {
            log.error("导入宿舍班级数据失败: {}", e.getMessage(), e);
            redisService.set(CachePrefixConstant.WELCOME_DORM_IMPOST_PROGRESS + importKey,
                WelcomeImportProgress.<DormImportVO>builder().importKey(importKey)
                    .total(100).current(100)
                    .importStatus(2).build());
            throw new FebsException("导入失败！请重新操作");
        } finally {
            if (Objects.nonNull(errorFile)) {
                cn.hutool.core.io.FileUtil.del(errorFile);
            }
        }
    }

    @Override
    public void importDormDataByCustom(String fileUrl, CurrentUser currentUser) {
        // 上传的excel文件
        File file = null;
        // 错误信息文件excel
        File errorFile = null;
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            // 调用导入方法
            file = new File(fileUrl);
            EasyExcel.read(file, CustomDormImportDTO.class,
                new CustomDormExcelListener(this, currentUser))
                .sheet().headRowNumber(1).doRead();
            stopWatch.stop();
            log.info("导入宿舍预选数据总共耗时: {}", stopWatch.getTotalTimeSeconds() + "秒");
        } catch (Exception e) {
            log.error("导入宿舍预选数据总共耗时: {}", e.getMessage(), e);
            throw new FebsException("导入失败！请重新操作");
        } finally {
            if (Objects.nonNull(file)) {
                cn.hutool.core.io.FileUtil.del(file);
            }
            if (Objects.nonNull(errorFile)) {
                cn.hutool.core.io.FileUtil.del(errorFile);
            }
        }
    }

    @Override
    public DormImportFixVO importDormFixData(MultipartFile file, CurrentUser currentUser, Long guideId) {
        // 验证文件类型
        if (!FileUtil.checkMultipartFile(file, FebsConstant.EXCEL_FILE_TYPE)) {
            return null;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        DormImportFixVO dormImportFixVO = new DormImportFixVO();
        List<DormImportFixVO.FixImportVO> voList = new ArrayList<>();
        // 调用导入方法
        ExcelListener<DormImportFixDTO> listener = new ExcelListener<DormImportFixDTO>();
        try {
            ExcelReader excelReader = EasyExcelFactory.read(file.getInputStream(), DormImportFixDTO.class, listener)
                .headRowNumber(1).build();
            excelReader.readAll();
            List<DormImportFixDTO> listMap = listener.getDatas();
            List<String> errorIdNumberList = new ArrayList<>();
            excelReader.finish();

            List<EduSmartWelcomeGuideRoster> eduSmartWelcomeGuideRosters = eduSmartWelcomeGuideRosterMapper
                .selectList(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRoster())
                    .eq(EduSmartWelcomeGuideRoster::getGuideId, guideId));

            List<EduDormitory> dormitoryList = eduDormitoryService.list(Wrappers.lambdaQuery(new EduDormitory())
                .eq(EduDormitory::getSchoolId, currentUser.getDeptId()));
            ListDormRoomDTO listDormRoomDTO = new ListDormRoomDTO();
            listDormRoomDTO.setSchoolId(currentUser.getDeptId());
            List<EduDormitoryRoom> eduDormitoryRooms = eduDormitoryRoomService.listDormRoom(listDormRoomDTO);

            for (DormImportFixDTO dormImportFixDTO : listMap) {
                DormImportFixVO.FixImportVO vo = new DormImportFixVO().new FixImportVO();
                BeanUtils.copyProperties(dormImportFixDTO, vo);

                //宿舍楼
                List<EduDormitory> dormitories = dormitoryList.stream().filter(d -> d.getName().equals(vo.getDormName()))
                    .collect(Collectors.toList());

                if (CollUtil.isEmpty(dormitories)) {
                    errorIdNumberList.add(dormImportFixDTO.getIdNumber());
                    continue;
                }

                Long dormId = dormitories.get(0).getId();
                //寝室号
                List<EduDormitoryRoom> dormitoryRoomList = eduDormitoryRooms.stream()
                    .filter(d -> d.getDormName().equals(vo.getDormName()) && d.getName().equals(vo.getDormRoomName()))
                    .collect(Collectors.toList());
                if (CollUtil.isEmpty(dormitoryRoomList)) {
                    errorIdNumberList.add(dormImportFixDTO.getIdNumber());
                    continue;
                }
                Long dormRoomId = dormitoryRoomList.get(0).getId();

                List<EduSmartWelcomeGuideRoster> rosters = eduSmartWelcomeGuideRosters.stream()
                    .filter(g -> g.getFullName().equals(dormImportFixDTO.getRosterName())).collect(Collectors.toList());

                if (CollUtil.isEmpty(rosters)) {
                    errorIdNumberList.add(dormImportFixDTO.getIdNumber());
                    continue;
                }
                Long rosterId = rosters.get(0).getId();

                vo.setDormId(dormId);
                vo.setDormRoomId(dormRoomId);
                vo.setRosterId(rosterId);
                voList.add(vo);
            }

            if (CollUtil.isNotEmpty(errorIdNumberList)) {
                dormImportFixVO.setErrorIdNumberList(errorIdNumberList);
            }

            if (CollUtil.isNotEmpty(voList)) {
                dormImportFixVO.setFixImportVOList(voList);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        stopWatch.stop();
        log.info("导入固定班级学生数据总共耗时: {}", stopWatch.getTotalTimeSeconds() + "秒");
        return dormImportFixVO;
    }

    @Override
    public void dormBanding(Long guideId, Long stepId, Long rosterId) {
        EduSmartWelcomeGuideRoster roster = (EduSmartWelcomeGuideRoster) redisService
            .hget(CachePrefixConstant.WELCOME_ROSTER, rosterId.toString());
        if (ObjectUtil.isNull(roster)) {
            roster = eduSmartWelcomeGuideRosterMapper.selectById(rosterId);
        }
        if (ObjectUtil.isNull(roster)) {
            log.info("花名册无人员信息：【{}】", rosterId);
            return;
        }
        Long dormId = null;
        Long dormRoomId = null;
        Long schoolId = null;
        EduSmartWelcomeGuideStepDormFix dormFix = eduSmartWelcomeGuideStepDormFixService
            .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStepDormFix())
                .eq(EduSmartWelcomeGuideStepDormFix::getRosterId, rosterId));
        if (ObjectUtil.isNotNull(dormFix)) {
            dormId = dormFix.getDormId();
            dormRoomId = dormFix.getDormRoomId();
            schoolId = dormFix.getSchoolId();
            log.info("花名册人员【{}】已在固定宿舍【{}{}】", roster.getFullName(), dormId, dormRoomId);
        } else {
            //比对专业查找出对应的班级
            //查询预分宿舍信息
            List<EduSmartWelcomeGuideStepDorm> dormList = new ArrayList<>();
            String str = (String) redisService.get(CachePrefixConstant.WELCOME_DORM_DATA + guideId + stepId);

            if (ObjectUtil.isNotNull(str)) {
                dormList = JSON.parseArray(str, EduSmartWelcomeGuideStepDorm.class);
            } else {
                dormList = this.list(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStepDorm())
                    .eq(EduSmartWelcomeGuideStepDorm::getGuideId, guideId)
                    .eq(EduSmartWelcomeGuideStepDorm::getStepId, stepId));

                if (CollUtil.isNotEmpty(dormList)) {
                    redisService
                        .set(CachePrefixConstant.WELCOME_DORM_DATA + guideId + stepId, JSONObject.toJSON(dormList).toString());
                }
            }
            if (CollUtil.isEmpty(dormList)) {
                log.info("无预分宿舍信息：guideId=【{}】", guideId);
                return;
            }
            //当前校区系部专业性别对应的宿舍
            EduSmartWelcomeGuideRoster finalRoster = roster;
            List<EduSmartWelcomeGuideStepDorm> departMajorGenderDormList = dormList.stream()
                .filter(c -> c.getDepartmentId().equals(finalRoster.getAdmittedDepartmentId()) && c.getMajorId()
                    .equals(finalRoster.getAdmittedMajorId()) && c.getGender().equals(finalRoster.getGender()))
                .collect(
                    Collectors.toList());

            for (EduSmartWelcomeGuideStepDorm eduSmartWelcomeGuideStepDorm : departMajorGenderDormList) {
                if (guideId == 5) {
                    //是否指定宿舍人数
                    if (redisService
                        .hHasKey(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER_BUDING,
                            eduSmartWelcomeGuideStepDorm.getDormRoomId().toString())) {
                        //当前已分配人数
                        Integer alreadyNumber = (Integer) redisService
                            .hget(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER_BUDING,
                                eduSmartWelcomeGuideStepDorm.getDormRoomId().toString());

                        //宿舍可容纳人数
                        Integer planNumber = eduSmartWelcomeGuideStepDorm.getNumber();
                        if (alreadyNumber >= planNumber) {
                            continue;
                        }
                        if (ObjectUtil.isNotNull(eduSmartWelcomeGuideStepDorm.getRealNumber())) {
                            //当前宿舍专业已分配人数
                            if (redisService.hHasKey(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER_BUDING,
                                eduSmartWelcomeGuideStepDorm.getDormRoomId() + "-" + eduSmartWelcomeGuideStepDorm.getId())) {
                                Integer alreadyMajorNumber = (Integer) redisService
                                    .hget(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER_BUDING,
                                        eduSmartWelcomeGuideStepDorm.getDormRoomId() + "-" + eduSmartWelcomeGuideStepDorm
                                            .getId());
                                Integer realNumber = eduSmartWelcomeGuideStepDorm.getRealNumber();
                                if (alreadyMajorNumber >= realNumber) {
                                    continue;
                                }
                            }
                        }
                    }
                    //分配学生到此宿舍
                    //人数+1
                    redisService
                        .hincr(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER_BUDING,
                            eduSmartWelcomeGuideStepDorm.getDormRoomId().toString(),
                            1D);
                    if (ObjectUtil.isNotNull(eduSmartWelcomeGuideStepDorm.getRealNumber())) {
                        redisService
                            .hincr(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER_BUDING,
                                eduSmartWelcomeGuideStepDorm.getDormRoomId() + "-" + eduSmartWelcomeGuideStepDorm.getId(),
                                1D);
                    }
                    dormId = eduSmartWelcomeGuideStepDorm.getDormId();
                    dormRoomId = eduSmartWelcomeGuideStepDorm.getDormRoomId();
                    schoolId = eduSmartWelcomeGuideStepDorm.getSchoolId();
                    log.info("学生【{}】分配到【{}】宿舍寝室【{}】", roster.getFullName(), dormId, dormRoomId);
                    break;
                } else {
                    //是否指定宿舍人数
                    if (redisService
                        .hHasKey(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER,
                            eduSmartWelcomeGuideStepDorm.getDormRoomId().toString())) {
                        //当前已分配人数
                        Integer alreadyNumber = (Integer) redisService
                            .hget(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER,
                                eduSmartWelcomeGuideStepDorm.getDormRoomId().toString());

                        //宿舍可容纳人数
                        Integer planNumber = eduSmartWelcomeGuideStepDorm.getNumber();
                        if (alreadyNumber >= planNumber) {
                            continue;
                        }
                        if (ObjectUtil.isNotNull(eduSmartWelcomeGuideStepDorm.getRealNumber())) {
                            //当前宿舍专业已分配人数
                            if (redisService.hHasKey(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER,
                                eduSmartWelcomeGuideStepDorm.getDormRoomId() + "-" + eduSmartWelcomeGuideStepDorm.getId())) {
                                Integer alreadyMajorNumber = (Integer) redisService
                                    .hget(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER,
                                        eduSmartWelcomeGuideStepDorm.getDormRoomId() + "-" + eduSmartWelcomeGuideStepDorm
                                            .getId());
                                Integer realNumber = eduSmartWelcomeGuideStepDorm.getRealNumber();
                                if (alreadyMajorNumber >= realNumber) {
                                    continue;
                                }
                            }
                        }
                    }
                    //分配学生到此宿舍
                    //人数+1
                    redisService
                        .hincr(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER,
                            eduSmartWelcomeGuideStepDorm.getDormRoomId().toString(),
                            1D);
                    if (ObjectUtil.isNotNull(eduSmartWelcomeGuideStepDorm.getRealNumber())) {
                        redisService
                            .hincr(CachePrefixConstant.WELCOME_DROM_STUDENT_NUMBER,
                                eduSmartWelcomeGuideStepDorm.getDormRoomId() + "-" + eduSmartWelcomeGuideStepDorm.getId(),
                                1D);
                    }
                    dormId = eduSmartWelcomeGuideStepDorm.getDormId();
                    dormRoomId = eduSmartWelcomeGuideStepDorm.getDormRoomId();
                    schoolId = eduSmartWelcomeGuideStepDorm.getSchoolId();
                    log.info("学生【{}】分配到【{}】宿舍寝室【{}】", roster.getFullName(), dormId, dormRoomId);
                    break;
                }
            }
        }
        if (ObjectUtil.isNotNull(dormId) && ObjectUtil.isNotNull(dormRoomId) && ObjectUtil.isNotNull(schoolId)) {
            //增加分宿舍记录
            EduSmartWelcomeGuideDormRecord dormRecord = new EduSmartWelcomeGuideDormRecord();
            dormRecord.setSchoolId(schoolId);
            dormRecord.setRosterId(rosterId);
            dormRecord.setGuideId(guideId);
            dormRecord.setDormId(dormId);
            dormRecord.setDormRoomId(dormRoomId);
            eduSmartWelcomeGuideDormRecordService.save(dormRecord);
            //填充花名册数据
            EduDormitoryRoom dormRoom = eduDormitoryRoomService.getDormRoom(dormRoomId);
            if (ObjectUtil.isNotNull(dormRoom)) {
                roster.setDormitoryId(dormId);
                roster.setDormitory(dormRoom.getDormName());
                roster.setDormitoryRoomId(dormRoomId);
                roster.setDormitoryRoom(dormRoom.getName());
                eduSmartWelcomeGuideRosterMapper.updateById(roster);
            }
        } else {
            log.info("学生【{}无法分配宿舍", roster.getFullName());
        }

    }

    @Override
    public void saveCusTomDormData(ConcurrentHashMap<Integer, CustomDormImportDTO> concurrentHashMap,
        CurrentUser currentUser) {
        int temp = 0;
        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            List<EduDormitory> dormitoryList = eduDormitoryService.list(Wrappers.lambdaQuery(new EduDormitory())
                .eq(EduDormitory::getSchoolId, currentUser.getDeptId()));
            ListDormRoomDTO listDormRoomDTO = new ListDormRoomDTO();
            listDormRoomDTO.setSchoolId(currentUser.getDeptId());
            List<EduDormitoryRoom> eduDormitoryRooms = eduDormitoryRoomService.listDormRoom(listDormRoomDTO);
            List<EduSmartWelcomeDepartment> departmentList = eduSmartWelcomeDepartmentService.list();
            // 保存前判断是否已存在
            List<EduSmartWelcomeGuideStepDorm> dormImportVOList = new ArrayList();
            for (Map.Entry<Integer, CustomDormImportDTO> entry : concurrentHashMap.entrySet()) {
                temp++;
                EduSmartWelcomeGuideStepDorm importVo = new EduSmartWelcomeGuideStepDorm();
                try {
                    CustomDormImportDTO value = entry.getValue();
                    BeanUtils.copyProperties(value, importVo);
                    //宿舍楼
                    List<EduDormitory> dormitories = dormitoryList.stream()
                        .filter(d -> d.getName().equals(importVo.getDormName()))
                        .collect(Collectors.toList());
                    if (CollUtil.isEmpty(dormitories)) {
                        log.info("宿舍无法查找：【{}】", importVo.getDormName());
                        continue;
                    }

                    Long dormId = dormitories.get(0).getId();
                    //寝室号
                    List<EduDormitoryRoom> dormitoryRoomList = eduDormitoryRooms.stream()
                        .filter(d -> d.getDormName().equals(importVo.getDormName()) && d.getName()
                            .equals(importVo.getDormRoomName()))
                        .collect(Collectors.toList());
                    if (CollUtil.isEmpty(dormitoryRoomList)) {
                        log.info("寝室号无法查找：【{}】", importVo.getDormRoomName());
                        continue;
                    }
                    Long dormRoomId = dormitoryRoomList.get(0).getId();
                    //系部ID
                    List<EduSmartWelcomeDepartment> departmentList1 = departmentList.stream()
                        .filter(d -> d.getName().equals(importVo.getDepartmentName()))
                        .collect(Collectors.toList());
                    if (CollUtil.isEmpty(departmentList1)) {
                        log.info("系部无法查找：【{}】", importVo.getDepartmentName());
                        continue;
                    }
                    Long departmentId = departmentList1.get(0).getId();
                    //专业ID
                    List<EduSmartWelcomeDepartment> majorList = departmentList.stream()
                        .filter(d -> d.getName().equals(importVo.getMajorName()))
                        .collect(Collectors.toList());
                    if (CollUtil.isEmpty(majorList)) {
                        log.info("专业无法查找：【{}】", importVo.getMajorName());
                        continue;
                    }
                    Long majorId = majorList.get(0).getId();

                    importVo.setDepartmentId(departmentId);
                    importVo.setMajorId(majorId);
                    importVo.setDormId(dormId);
                    importVo.setDormRoomId(dormRoomId);
                    importVo.setGender("男".equals(value.getGender()) ? 0 : 1);

                    dormImportVOList.add(importVo);
                } catch (Exception e) {
                    log.error("导入自定义宿舍失败");
                } finally {
                }
            }
            if (CollUtil.isNotEmpty(dormImportVOList)) {
                log.info("保存数据", dormImportVOList);
                saveBatch(dormImportVOList);
            }
        }
    }
}
