package com.srs.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysDept;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.core.page.TableDataInfo;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.StringUtils;
import com.srs.common.utils.bean.BeanValidators;
import com.srs.comprehensive.domain.CphTeacher;
import com.srs.comprehensive.domain.SrsClass;
import com.srs.comprehensive.domain.Vo.CphSearch;
import com.srs.comprehensive.mapper.CphTeacherMapper;
import com.srs.comprehensive.mapper.SrsClassMapper;
import com.srs.dormitory.domain.*;
import com.srs.dormitory.domain.Dto.*;
import com.srs.dormitory.domain.Vo.ClassInfo;
import com.srs.dormitory.domain.Vo.DomInfo;
import com.srs.dormitory.domain.Vo.FloorsVo;
import com.srs.dormitory.domain.Vo.SelectDormByStuVo;
import com.srs.dormitory.mapper.DmsDormitoryClassMapper;
import com.srs.dormitory.mapper.DmsDormitoryDeptMapper;
import com.srs.dormitory.mapper.DmsDormitoryMapper;
import com.srs.dormitory.mapper.DmsNewRegMapper;
import com.srs.dormitory.service.*;
import com.srs.dormitory.utils.BeanCopyUtils;
import com.srs.stureg.domain.SrsStuReg;
import com.srs.stureg.domain.VO.TeacherVo;
import com.srs.stureg.mapper.SrsStuRegMapper;
import com.srs.stureg.service.impl.SrsStuRegServiceImpl;
import com.srs.system.domain.SysDeptMap;
import com.srs.system.domain.SysUserRole;
import com.srs.system.mapper.SysDeptMapper;
import com.srs.system.mapper.SysUserRoleMapper;
import com.srs.system.service.ISysConfigService;
import com.srs.system.service.ISysDeptMapService;
import com.srs.system.service.ISysDeptService;
import com.srs.system.service.ISysUserService;
import liquibase.pro.packaged.A;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Validator;
import java.awt.image.DirectColorModel;
import java.util.*;
import java.util.stream.Collectors;

import static com.srs.common.utils.PageUtils.startPage;
import static com.srs.common.utils.SecurityUtils.getDeptId;
import static com.srs.common.utils.SecurityUtils.getUsername;
import static com.srs.dormitory.utils.PageUtil.getDataTable;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-25
 */
@Service
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IDmsDormitoryClassServiceImpl extends ServiceImpl<DmsDormitoryClassMapper, DmsDormitoryClass> implements IDmsDormitoryClassService {
    @Autowired
    private IDmsDormitoryFloorService floorService;
    @Autowired
    private IDmsDormitoryService dormitoryService;
    @Autowired
    private IDmsPhotosService photosService;
    @Autowired
    ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IDmsDormitoryDeptService dormitoryDeptService;
    @Autowired
    private DmsDormitoryTeacherService teacherService;
    @Autowired
    private CphTeacherMapper teacherMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SrsStuRegMapper stuRegMapper;
    @Autowired
    public SysDeptMapper _deptMapper;
    @Autowired
    public DmsDormitoryClassMapper _classMapper;
    @Autowired
    public PlatformTransactionManager transactionManager;
    @Autowired
    public DmsDormitoryDeptMapper _domDeptMapper;
    @Autowired
    public DmsDormitoryMapper _domMapper;
    @Autowired
    public SrsClassMapper _srsClassMapper;
    @Autowired
    public SrsStuRegMapper _srsStuRegMapper;
    @Autowired
    public DmsNewRegMapper _regMapper;
    @Autowired
    public IDmsNewRegService _regService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    protected Validator validator;

    @Override
    public AjaxResult lockDmsClass(Long id) {
        try {

            DmsDormitoryClass entity = _classMapper.selectById(id);
            if (entity == null) {
                throw new Exception("该分配记录不存在");
            }

            if (Objects.equals(entity.isLock, "1")) {
                throw new Exception("该记录已锁定");
            }

            entity.isLock = "1";

            int res = _classMapper.updateById(entity);
            if (res == 0) {
                throw new Exception("锁定失败");
            }

            return AjaxResult.success();
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult cancelReg(DmsNewReg param) {
        try {
            QueryWrapper<DmsNewReg> query = new QueryWrapper<>();
            query.eq("ksh", param.getKsh())
                    .eq("dormitory_id", param.getDormitoryId());

            int res = _regMapper.delete(query);
            if (res == 0) {
                throw new Exception("删除记录失败");
            }

            return AjaxResult.success();
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public AjaxResult addReg(DmsNewReg param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            DmsDormitory dormitory = _domMapper.selectById(param.getDormitoryId());
            if (dormitory == null) {
                throw new Exception("该宿舍不存在");
            }

            List<String> kshList = new ArrayList<>();

            List<DmsNewReg> needAddList = new ArrayList<>();

            for (SrsStuReg stu : param.stuList) {
                kshList.add(stu.getKSH());
                DmsNewReg reg = new DmsNewReg();
                reg.setKsh(stu.getKSH());
                reg.setDormitoryId(dormitory.getId());
                needAddList.add(reg);
            }


            QueryWrapper<SrsStuReg> stuQuery = new QueryWrapper<>();
            stuQuery.in("KSH", kshList)
                    .eq("XB", dormitory.gender);
            List<SrsStuReg> stu = _srsStuRegMapper.selectList(stuQuery);
            if (stu == null) {
                throw new Exception("考生号错误，该生不存在");
            }

            if (stu.size() != param.stuList.size()) {
                throw new Exception("学生性别与宿舍不符");
            }

            String classCode = stu.get(0).getBJDM();
            QueryWrapper<DmsDormitoryClass> dmsDormitoryClassQueryWrapper = new QueryWrapper<>();
            dmsDormitoryClassQueryWrapper.eq("dormitory_id", param.getDormitoryId())
                    //.eq("BJDM",classCode)
                    .last("limit 1");
            DmsDormitoryClass dormClass = _classMapper.selectOne(dmsDormitoryClassQueryWrapper);
            if (dormClass == null) {
                throw new Exception("当前宿舍未分配给该班级");
            }
            int limit = dormClass.bedCount;
            DmsSearch search = new DmsSearch();
            search.classCode = classCode;
            search.dormitoryId = dormitory.getId();
            List<SrsStuReg> inStu = _regMapper.listStuInDorm(search);
            if (inStu.size() == limit || inStu.size() + param.stuList.size() > limit) {
                throw new Exception("该宿舍 当前班级可分配人数已达上限");
            }

            QueryWrapper<DmsNewReg> regQuery = new QueryWrapper<>();
            regQuery.in("ksh", kshList);
            _regMapper.delete(regQuery);

            boolean res = _regService.saveBatch(needAddList);
            if (!res) {
                throw new Exception("插入新生宿舍表失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }

    }

    @Override
    public AjaxResult listClassCanStu(SrsStuReg param) {
        Map m = new HashMap();
        m.put("tNo", getUsername());
        param.setParams(m);
        List<SrsStuReg> list = _srsStuRegMapper.listCanStu(param);
        return AjaxResult.success(list);
    }


    @Override
    public AjaxResult listClassStu(String classCode) {
        SrsStuReg srsStuReg = new SrsStuReg();
        srsStuReg.setBJDM(classCode);
        List<SrsStuReg> list = _srsStuRegMapper.selectSrsStuRegList(srsStuReg);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getRegByRoom(Long id) {
        DmsSearch query = new DmsSearch();
        query.dormitoryId = id;
        List<SrsStuReg> list = _regMapper.listStuInDorm(query);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult fastAllot(String tNo) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            DmsSearch searchDorm = new DmsSearch();
            searchDorm.isMixed = 1;
            searchDorm.tNo = tNo;
            List<DomInfo> dormList = _classMapper.listFdyRoom(searchDorm);

            CphSearch searchStu = new CphSearch();
            searchStu.setTNo(tNo);
            List<SrsStuReg> stuList = _srsStuRegMapper.listFdyStu(searchStu);
            List<DmsDormitoryClass> needInsertList = new ArrayList<>();

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public AjaxResult listOwnCanSelectDorm(String ksh) {
        try {
            QueryWrapper<SrsStuReg> regQuery = new QueryWrapper<>();
            regQuery.eq("KSH", ksh)
                    .last("limit 1");
            SrsStuReg stu = _srsStuRegMapper.selectOne(regQuery);
            if (stu == null) {
                throw new Exception("考生号不正确");
            }

            String classCode = stu.getBJDM();
            DmsSearch search = new DmsSearch();
            search.classCode = classCode;
            search.isMixed = 1;
            List<DomInfo> list = _classMapper.listFdyRoom(search);

            return AjaxResult.success(list);
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }


    }

    @Override
    public AjaxResult changeRoomIsMixed(@RequestBody DmsDormitoryClass param) {
        try {
            QueryWrapper<DmsDormitoryClass> searchQuery = new QueryWrapper<>();
            searchQuery.eq("dormitory_id", param.getDormitoryId());
            //.eq("BJDM",param.getBJDM());
            DmsDormitoryClass ddc = _classMapper.selectOne(searchQuery);
            if (ddc == null) {
                throw new Exception("该宿舍未分配给该班级");
            }

            ddc.setIsMixed(param.getIsMixed());
            int res = _classMapper.updateById(ddc);
            if (res == 0) {
                throw new Exception("修改失败");
            }

            return AjaxResult.success();
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public List<DomInfo> selectXwDom(SelectDormDto param) {
        Long oldId = getDeptId();
        SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
        Long deptId = null;
        if (dept != null) {
            deptId = dept.getOldDeptId();
        }
        SysDept dept1 = _deptMapper.selectById(deptId);
        param.xydm = dept1.getDeptCode();
        startPage();
        List<DomInfo> list = _classMapper.selectXwDom(param);
        list.forEach(x -> {
            Long domId = x.dormitoryId;
            QueryWrapper<DmsDormitoryClass> domClassQuery = new QueryWrapper<>();
            domClassQuery.eq("dormitory_id", domId);
            List<DmsDormitoryClass> dormitoryClasses = _classMapper.selectList(domClassQuery);
            //List<String> classCodes = new ArrayList<>();
            /*for(DmsDormitoryClass domClass : dormitoryClasses){
                classCodes.add(domClass.getBJDM());
            }*/
            List<String> tNos = new ArrayList<>();
            for (DmsDormitoryClass domClass : dormitoryClasses) {
                tNos.add(domClass.getTNo());
            }
            if (tNos.size() != 0) {
                MPJLambdaWrapper<DmsDormitoryClass> classQuery = new MPJLambdaWrapper<>();
                classQuery.selectAll(DmsDormitoryClass.class)
                        .selectAs(CphTeacher::getName, ClassInfo::getTeacherName)
                        .selectAs(DmsDormitoryClass::getTNo, ClassInfo::getTNo)
                        .selectAs(DmsDormitoryClass::getId, ClassInfo::getId)
                        .selectAs(DmsDormitoryClass::getIsLock, ClassInfo::getIsLock)
                        .selectAs(DmsDormitoryClass::getDormitoryId, ClassInfo::getDormitoryId)
                        .leftJoin(CphTeacher.class, on -> on.eq(DmsDormitoryClass::getTNo, CphTeacher::getEmployeeId))
                        .in("t_no", tNos)
                        .eq(DmsDormitoryClass::getDormitoryId, x.dormitoryId);
                x.hasTeachers = _classMapper.selectJoinList(ClassInfo.class, classQuery);
            } else {
                x.hasClass = new ArrayList<>();
            }
        });

        return list;
    }

    @Override
    public List<DormitoryModelDto> getModelRoom(DormitoryModelDto param) {
        return _classMapper.selectFdyModel(param);
    }

    @Autowired
    ISysDeptMapService _deptMap;

    @Override
    public AjaxResult selectXwClass() {
        CphSearch search = new CphSearch();
        Long oldId = getDeptId();
        SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
        Long deptId = null;
        if (dept != null) {
            deptId = dept.getOldDeptId();
        }
        search.setDeptId(deptId);
        List<ClassInfo> list = _classMapper.selectXwClass(search);
        return AjaxResult.success(list);
    }

    @Override
    public List<DomInfo> listFdyRoom(DmsSearch param) {
        return _classMapper.listFdyRoom(param);
    }


    @Override
    public AjaxResult changeClassBed(List<ClassInfo> param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            List<DmsDormitoryClass> needUpdate = new ArrayList<>();
            for (ClassInfo dto : param) {
                QueryWrapper<DmsDormitoryClass> classQuery = new QueryWrapper<>();
                classQuery.eq("dormitory_id", dto.dormitoryId)
                        .eq("t_no", dto.getTNo());
                DmsDormitoryClass find = _classMapper.selectOne(classQuery);
                if (find == null) {
                    continue;
                }
                DmsDormitoryClass temp = new DmsDormitoryClass();
                temp.setBedCount(dto.bedCount);
                temp.setDormitoryId(dto.dormitoryId);
                //temp.setBJDM( dto.classCode);
                temp.setTNo(dto.tNo);
                temp.setId(find.getId());
                needUpdate.add(temp);
            }

            boolean res = this.updateBatchById(needUpdate);
            if (!res) {
                throw new Exception("保存失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult xwDomClass(DeptClassDto param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            //List<String> classCodes = param.classCode;
            List<Long> dormitoryIds = param.dormitoryId;
            List<String> tNos = param.tNo;
            List<DmsDormitoryClass> addList = new ArrayList<>();

            Long oldId = getDeptId();
            SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
            Long deptId = null;
            if (dept != null) {
                deptId = dept.getOldDeptId();
            }
            SysDept sysDept = _deptMapper.selectById(deptId);
            String deptCode = sysDept.getDeptCode();

            for (Long domId : dormitoryIds) {
                Map<String, Object> domQuery = new HashMap<>();
                domQuery.put("dormitoryId", domId);

                List<Map<String, Object>> domInfo = _domMapper.getDormitoryInfoList(domQuery);
                if (domInfo.size() != 0) {
                    String gender = domInfo.get(0).get("gender").toString();

                    QueryWrapper<DmsDormitoryClass> classDomQuery = new QueryWrapper<>();
                    classDomQuery.eq("dormitory_id", domId);
                    List<DmsDormitoryClass> classes = _classMapper.selectList(classDomQuery);
                    List<Long> isExistIds = new ArrayList<>();
                    for (DmsDormitoryClass domClass : classes) {
                        isExistIds.add(domClass.getId());
                    }

                    if (isExistIds.size() != 0) {
                        _classMapper.deleteBatchIds(isExistIds);
                    }

                    QueryWrapper<DmsDormitoryDept> domDeptQuery = new QueryWrapper<>();
                    domDeptQuery.eq("dormitory_id", domId)
                            .eq("XYDM", deptCode);

                    DmsDormitoryDept domDept = _domDeptMapper.selectOne(domDeptQuery);
                    int canBed = domDept.bedCount;
                    if(tNos.size()>0) {
                        int classCount = tNos.size();
                        int avgBedNum = canBed / classCount;
                        int i = 1;
                        for (String tno : tNos) {
                            DmsDormitoryClass temp = new DmsDormitoryClass();
                            temp.setDormitoryId(domId);
                            //temp.setBJDM(classCode);
                            temp.setTNo(tno);
                            temp.setGender(gender);
                            if (i == classCount) {
                                int bedCount = canBed - (avgBedNum * (classCount - 1));
                                temp.setBedCount(bedCount);
                            } else {
                                temp.setBedCount(avgBedNum);
                                i++;
                            }
                            addList.add(temp);
                        }
                    }else{
                        throw new Exception("辅导员不能为空");
                    }
                }
            }
            boolean res = this.saveBatch(addList);
            if (!res) {
                throw new Exception("保存失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 划分宿舍区域
     *
     * @param allocateDto 划分宿舍区域的参数，包括班级代码（BJ                                                                            DM）、宿舍ID列表（dormitoryIds）和性别（gender）
     * @return 操作结果，成功则返回成功信息，否则抛出异常
     */
    @Override
    @Transactional
    public AjaxResult allocate(AllocateDto allocateDto) {
        // 查询已经被选择的宿舍
        List<DmsDormitoryClass> selectedDorms = lambdaQuery()
                .eq(DmsDormitoryClass::getBJDM, allocateDto.getBJDM())
                .in(DmsDormitoryClass::getDormitoryId, allocateDto.getDormitoryIds())
                .list();

        if (!selectedDorms.isEmpty()) {
            List<Long> selectedRoomNos = selectedDorms
                    .stream()
                    .map(DmsDormitoryClass::getDormitoryId)
                    .collect(Collectors.toList());

            List<DmsDormitory> dormitories = dormitoryService.listByIds(selectedRoomNos);
            List<Long> selectedRooms = dormitories
                    .stream()
                    .map(DmsDormitory::getRoomNo)
                    .collect(Collectors.toList());

            throw new RuntimeException("宿舍" + selectedRooms + "已被班级" + "[" + allocateDto.getBJDM() + "]" + "选择，请不要重复选择");
        }

        List<DmsDormitoryClass> list = lambdaQuery()
                .in(DmsDormitoryClass::getDormitoryId, allocateDto.getDormitoryIds())
                .list();


        // 构建宿舍分配记录并保存
        List<DmsDormitoryClass> dormitoryClasses = allocateDto
                .getDormitoryIds()
                .stream()
                .map(dormitoryId -> DmsDormitoryClass.builder()
                        .dormitoryId(dormitoryId)
                        .BJDM(allocateDto.getBJDM())
                        .gender(allocateDto.getGender())
                        .isMixed(!list.isEmpty() ? 1 : 0)
                        .build())
                .collect(Collectors.toList());

        boolean saveBatch = saveBatch(dormitoryClasses);
        if (!saveBatch) throw new RuntimeException("操作失败");
        if (!list.isEmpty()) {
            List<Long> collect = list
                    .stream()
                    .map(DmsDormitoryClass::getDormitoryId)
                    .collect(Collectors.toList());
            boolean set = lambdaUpdate()
                    .in(DmsDormitoryClass::getDormitoryId, collect)
                    .set(DmsDormitoryClass::getIsMixed, 1)
                    .update();
            if (!set) throw new RuntimeException("操作失败");
        }

        return AjaxResult.success();
    }


    @Override
    @Transactional
    public AjaxResult delete(List<Long> ids) {
        if (ids.isEmpty()) return AjaxResult.error();
        boolean remove = remove(new LambdaQueryWrapper<DmsDormitoryClass>().in(DmsDormitoryClass::getDormitoryId, ids));
        if (!remove) throw new RuntimeException("操作失败");
        return AjaxResult.success();

    }

    @Override
    public DmsDormitory getcount(Long id) {
        return _classMapper.getcount(id);
    }

    @Override
    public String importUser(List<DormitoryModelDto> dormList, boolean isupdateSupport, String operName) {
        if (StringUtils.isNull(dormList) || dormList.size() == 0) {
            throw new ServiceException("导入宿舍成员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (DormitoryModelDto reg : dormList) {
            try {
                // 学生信息验证
                SrsStuReg stuReg=_srsStuRegMapper.getOwnInfoByKsh(reg.getKSH());
                if (stuReg==null) {
                    failureMsg.append("考生号:"+reg.getKSH()+"错误"+"该生不存在");
                    continue;
                }
                //查询插入宿舍是否存在
                DmsDormitory dormitory = _domMapper.selectById(reg.getId());
                if (dormitory == null) {
                    failureMsg.append(reg.getDorm()+"该宿舍不存在");
                    continue;
                }
                // 检查学生的宿舍是否已经存在
                DmsNewReg dmsreg=new DmsNewReg();
                dmsreg.setKsh(reg.getKSH());
                List<DmsNewReg> DMS=_regMapper.selectDmsNewRegList(dmsreg);
                if (DMS.size()!=0){
                    failureNum++;
                    failureMsg.append( "考生号:" + reg.getKSH()+"已经存在宿舍");
                    continue;
                }
                //验证学生性别与宿舍的匹配
                QueryWrapper<DmsDormitory> stuQuery=new QueryWrapper<>();
                stuQuery.in("id",reg.getId())
                        .eq("gender",stuReg.getXB());
                DmsDormitory stu=_domMapper.selectOne(stuQuery);
                if(stu == null){
                    failureNum++;
                    failureMsg.append( "考生号:" + reg.getKSH()+"学生性别与宿舍不符");
                    continue;
                }
                //验证成员是否在班级老师分配成员中存在
                TeacherVo t = new TeacherVo();
                t.setTno(getUsername());
                t.setKSH(reg.getKSH());
                TeacherVo teacher = stuRegMapper.getDmsClass(t);
                if (teacher==null){
                    failureNum++;
                    failureMsg.append("考生号："+ reg.getKSH()+"不属于"+ teacher.TeacherName+"的管理学生");
                    continue;
                }

                DmsNewReg dorm = new DmsNewReg();
                if (StringUtils.isNotNull(stuReg)) {
                    BeanValidators.validateWithException(validator, dorm);
                    dorm.setDormitoryId(reg.getId());
                    dorm.setKsh(reg.getKSH());
                    dorm.setStatus(0L);
                    dorm.setDelFlag("0");
                    _regMapper.insertDmsNewReg(dorm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、考生号" + dorm.getKsh() + "导入宿舍成功");
                }
                else if (isupdateSupport) {
                    BeanValidators.validateWithException(validator, dorm);
                    dorm.setUpdateBy(operName);
                    dorm.setDormitoryId(reg.getId());
                    dorm.setKsh(reg.getKSH());
                    dorm.setStatus(0L);
                    dorm.setDelFlag("0");
                    _regMapper.updateDmsNewReg(dorm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、考生号" + dorm.getKsh() + "更新宿舍成员成功");
                }

            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + reg.getKSH() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                continue;
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    public List<Map<String, Object>> selectClass() {
        startPage();
        return baseMapper.selectClass();
    }

    /**
     * 获取当前用户所属班级信息列表，并为每个班级添加床位分配信息
     *
     * @return 所属班级信息列表，每个元素是一个包含班级代码（classCode）和班级名称（className）的 Map 对象，
     * 同时包含床位分配信息（bedSelected）列表，每个元素是一个包含性别（gender）和分配床位数量（count）的 Map 对象
     */
    @Override
    public TableDataInfo selectMajor() {
        // 获取当前用户的用户名
        String username = SecurityUtils.getUsername();


        // 分页查询所属班级信息
        startPage();
        // 获取班级信息列表
        List<Map<String, Object>> mapList = baseMapper.selectMajor(username);

        // 获取性别和床位分配信息
        List<Map<String, Object>> gender = baseMapper.selectGender();

        // 为每个班级添加床位分配信息
        mapList.forEach(map -> {
            List<Map<String, Object>> filteredGender = gender
                    .stream()
                    .filter(genderMap -> map.get("classCode").equals(genderMap.get("BJDM")))
                    .collect(Collectors.toList());
            map.put("bedSelected", filteredGender);
        });

        return getDataTable(mapList, null);
    }


    @Override
    public List<Map<String, Object>> selectBuilding(SelectBuildingDto dto) {
        startPage();
        return baseMapper.selectBuilding(dto);
    }

    @Override
    public List<Map<String, Object>> selectDorm(SelectDormDto dto) {
        startPage();
        Long oldId = getDeptId();
        SysDeptMap dept1 = _deptMap.getOldDeptByNewId(oldId);
        Long deptId = null;
        if (dept1 != null) {
            deptId = dept1.getOldDeptId();
        }

        SysDept dept = _deptMapper.selectDeptById(deptId);
        dto.xydm = dept.getDeptCode();

        List<Map<String, Object>> ss = baseMapper.selectDorm(dto);
        ss.forEach(s -> {
            List<Map<String, Object>> bj = baseMapper.selectBJ(s.get("id"));
            s.put("BJ", bj);
        });
        return ss;
    }


    @Override
    public List<FloorsVo> selectFloor(Long build) {
        startPage();
        List<DmsDormitoryFloor> floors = floorService
                .lambdaQuery()
                .eq(DmsDormitoryFloor::getBuildingId, build)
                .list();
        return BeanCopyUtils.copyBeanList(floors, FloorsVo.class);
    }

    @Override
    public List<SelectDormByStuVo> selectDormByStu() {

        Map<String, Object> map = baseMapper.selectBJDM(SecurityUtils.getUsername());
        System.out.println(map);
        if (map == null) throw new RuntimeException("操作失败，请查看账号是否正确");
        List<DmsDormitoryClass> dormitory = baseMapper.selectList(new LambdaQueryWrapper<DmsDormitoryClass>()
                .eq(DmsDormitoryClass::getBJDM, map.get("BJDM")));
        List<Long> dorms = dormitory.stream().map(DmsDormitoryClass::getDormitoryId).collect(Collectors.toList());
        System.out.println(dorms);
        if (!dorms.isEmpty()) {
            startPage();
            List<SelectDormByStuVo> stuVos = baseMapper.selectDormByIds(dorms, map.get("XB"));
            List<Map<String, Object>> beds = baseMapper.selectBeds(null);
            List<DmsPhotos> photos = photosService.lambdaQuery().isNotNull(DmsPhotos::getDormId).list();

            stuVos.forEach(vo -> {
                List<String> photoUrls = photos.stream()
                        .filter(photo -> photo.getDormId().equals(vo.getId())).map(DmsPhotos::getUrl)
                        .collect(Collectors.toList());
                vo.setPhotos(photoUrls);

                List<Map<String, Object>> bedMapList = beds.stream()
                        .filter(bed -> bed.get("dormId").toString().equals(vo.getId().toString()))
                        .collect(Collectors.toList());
                vo.setBeds(bedMapList);
            });
            return stuVos;
        } else {
            throw new RuntimeException("暂未安排宿舍");
        }
    }
}
