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.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.StringUtils;
import com.srs.comprehensive.domain.SrsGrade;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.mapper.SrsGradeMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.dormitory.domain.*;
import com.srs.dormitory.domain.Dto.AddDormitoryPhotosDto;
import com.srs.dormitory.domain.Dto.DmsSearch;
import com.srs.dormitory.domain.Dto.DormitoryDto;
import com.srs.dormitory.domain.Dto.ImportDormitoryModel;
import com.srs.dormitory.domain.Vo.DmsFdyStu;
import com.srs.dormitory.domain.Vo.DomInfo;
import com.srs.dormitory.domain.Vo.DormitoryVo;
import com.srs.dormitory.domain.Vo.ExportDormInfo;
import com.srs.dormitory.mapper.*;
import com.srs.dormitory.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.*;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.srs.common.utils.DateUtils.getNowDate;

/**
 * <p>
 * 宿舍信息表 服务实现类
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-14
 */
@Service
public class IDmsDormitoryServiceImpl extends ServiceImpl<DmsDormitoryMapper, DmsDormitory> implements IDmsDormitoryService {
    @Autowired
    private IDmsDormitoryBedService bedService;
    @Autowired
    private DmsDormitoryBedMapper dmsDormitoryBedMapper;
    @Autowired
    private DmsDormitoryBuildingInfoMapper dmsDormitoryBuildingInfoMapper;
    @Autowired
    private IDmsPhotosService dmsPhotosService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ISrsDormitoryStudentService srsDormitoryStudentService;
    @Autowired
    private IDmsCampusService dmsCampusService;
    @Autowired
    private IDmsDormitoryParkService dmsDormitoryParkService;
    @Autowired
    private IDmsDormitoryBuildingService dmsDormitoryBuildingService;
    @Autowired
    private IDmsDormitoryFloorService dmsDormitoryFloorService;
    @Autowired
    private SrsDormitoryStudentMapper srsDormitoryStudentMapper;
    @Autowired
    private SrsGradeMapper srsGradeMapper;
    @Autowired
    private IDmsDormitoryDeptService dmsDormitoryDeptService;
    @Autowired
    public DmsDormitoryMapper _dormMapper;
    @Autowired
    public DmsPhotosMapper _photoMapper;
    @Autowired
    public DmsCampusMapper _campusMapper;
    @Autowired
    public DmsDormitoryParkMapper _parkMapper;
    @Autowired
    public DmsDormitoryBuildingMapper _buildingMapper;
    @Autowired
    public DmsDormitoryFloorMapper _floorMapper;
    @Autowired
    public DmsNewWenmingMapper _wenmingMapper;

    @Autowired
    public DmsDormitoryDeptMapper _dormDeptMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;

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

    @Override
    public AjaxResult countGenderBed() {
        List<DomInfo> res = _dormMapper.countGenderBed();
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult countDeptBed() {
        List<DomInfo> res = _dormMapper.countDeptBed();
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult countStuIn() {
        List<DomInfo> res = _dormMapper.countStuIn();
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult cleanNotStu() {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            List<SrsDormitoryStudent> nowStuList = _dormMapper.findNotStu();
            List<String> stuNos = new ArrayList<>();
            nowStuList.forEach(x -> {
                stuNos.add(x.getStuNo());
            });
            if (stuNos.size() == 0) {
                throw new Exception("当前没有不在校学生可释放");
            }
            QueryWrapper<SrsDormitoryStudent> deleteQuery = new QueryWrapper<>();
            deleteQuery.in("stu_no", stuNos);
            int res = srsDormitoryStudentMapper.delete(deleteQuery);
            if (res == 0) {
                throw new Exception("释放失败");
            }

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


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

    @Override
    public List<DmsFdyStu> exportDept(DmsSearch param) {
        return _dormMapper.exportDept(param);
    }

    @Override
    public List<DmsFdyStu> exportFdy(DmsSearch param) {
        return _dormMapper.exportFdy(param);
    }


    @Override
    public AjaxResult signWenming(Long id) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = formatter.format(getNowDate());
            QueryWrapper<DmsNewWenming> wenmingQuery = new QueryWrapper<>();
            wenmingQuery.eq("dormitory_id", id)
                    .eq("make_time", dateStr);
            List<DmsNewWenming> list = _wenmingMapper.selectList(wenmingQuery);
            if (list.size() > 0) {
                throw new Exception("该宿舍今日已被标记为文明宿舍");
            }
            DmsSearch par = new DmsSearch();
            par.dormitoryId = id;
            List<DomInfo> info=_dormMapper.listRoomStu(par);
            int res=0;
            for(DomInfo item:info){
                DmsNewWenming param = new DmsNewWenming();
                param.setDormitoryId(id);
                param.setMakeTime(getNowDate());
                param.setDeptName(item.getDeptName());
                param.setClassName(item.getClassName());
                res = _wenmingMapper.insert(param);
            }
            if (res == 0) {
                throw new Exception("插入文明宿舍记录失败");
            }
            return AjaxResult.success();
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }

    }


    @Override
    public AjaxResult changeDormIsNew(DmsDormitory param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

            if(Objects.equals(param.getIsNew(), "0")){

                QueryWrapper<DmsDormitoryDept> query = new QueryWrapper<>();
                query.eq("dormitory_id",param.getId());
                List<DmsDormitoryDept> list = _dormDeptMapper.selectList(query);
                if(list.size() != 0){
                    throw new Exception("该宿舍已有学院分配记录，不可关闭");
                }
            }
            // 1.如果宿舍有人住，就删除所有已住学生
            QueryWrapper<SrsDormitoryStudent> queryds = new QueryWrapper<>();
            queryds.eq("dormitory_id",param.getId());
            List list=srsDormitoryStudentService.list(queryds);
            if(list!=null&&list.size()>0){
                srsDormitoryStudentService.remove(queryds);
            }
            // 结束：如果宿舍有人住，就删除所有已住学生
            DmsDormitory dorm = new DmsDormitory();
            dorm.setId(param.getId());
            dorm.setIsNew(param.getIsNew());


            int res = _dormMapper.updateById(dorm);
            if (res == 0) {
                throw new Exception("修改失败");
            }
            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public AjaxResult changeHead(String stuNo) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

            QueryWrapper<SrsDormitoryStudent> dormStuQuery1 = new QueryWrapper<>();
            dormStuQuery1.eq("stu_no", stuNo)
                    .orderByDesc("id")
                    .last("limit 1");
            SrsDormitoryStudent stu = srsDormitoryStudentMapper.selectOne(dormStuQuery1);
            if (stu == null) {
                throw new Exception("该生不在学生宿舍表中");
            }

            Long dormId = stu.getDormitoryId();
            QueryWrapper<SrsDormitoryStudent> dormStuQuery2 = new QueryWrapper<>();
            dormStuQuery2.eq("dormitory_id", dormId);
            List<SrsDormitoryStudent> list = srsDormitoryStudentMapper.selectList(dormStuQuery2);
            list.forEach(x -> {
                if (Objects.equals(x.getStuNo(), stuNo)) {
                    x.setIsDormitoryHead(1);
                } else {
                    x.setIsDormitoryHead(0);
                }
            });
            boolean res = srsDormitoryStudentService.updateBatchById(list);
            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 listRoomStu(DmsSearch param) {
        List<DomInfo> list = _dormMapper.listRoomStu(param);
        return AjaxResult.success(list);
    }


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

    @Override
    public List<ExportDormInfo> exportListRoomDeptLive(DmsSearch param){
        return _dormMapper.exportListRoomDeptLive(param);
    }


    @Override
    public AjaxResult listBuildingInfo() {
        List<DomInfo> list = _dormMapper.listBuildingInfo();
        return AjaxResult.success(list);
    }


    @Override
    public AjaxResult listRoomByFloor(Long id) {
        QueryWrapper<DmsDormitory> searchQuery = new QueryWrapper<>();
        searchQuery.eq("floor_id", id)
                .eq("is_new", 1);
        List<DmsDormitory> list = _dormMapper.selectList(searchQuery);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult listAllRoomByFloor(@PathVariable("id") Long id) {
        QueryWrapper<DmsDormitory> searchQuery = new QueryWrapper<>();
        searchQuery.eq("floor_id", id);
        List<DmsDormitory> list = _dormMapper.selectList(searchQuery);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult listFloorByBuilding(Long id) {
        QueryWrapper<DmsDormitoryFloor> searchQuery = new QueryWrapper<>();
        searchQuery.eq("building_id", id);
        List<DmsDormitoryFloor> list = _floorMapper.selectList(searchQuery);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult listBuildingByPark(@PathVariable("id") Long id) {
        QueryWrapper<DmsDormitoryBuilding> searchQuery = new QueryWrapper<>();
        searchQuery.eq("park_id", id);
        List<DmsDormitoryBuilding> list = _buildingMapper.selectList(searchQuery);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult listParkByCampus(Long id) {
        QueryWrapper<DmsDormitoryPark> searchQuery = new QueryWrapper<>();
        searchQuery.eq("campus_id", id);
        List<DmsDormitoryPark> list = _parkMapper.selectList(searchQuery);
        return AjaxResult.success(list);
    }


    @Override
    public AjaxResult listAllCampus() {
        List<DmsCampus> list = _campusMapper.selectList(null);
        return AjaxResult.success(list);
    }


    @Override
    public AjaxResult syncOccupancy() {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

            List<DmsDormitory> dormList1 = _dormMapper.selectList(null);
            dormList1.forEach(x -> {
                x.setOccupancy(0);
            });
            boolean res1 = this.updateBatchById(dormList1);
            if (!res1) {
                throw new Exception("清空宿舍入住人数失败");
            }
            List<DmsDormitory> dormList2 = _dormMapper.listDormCount();
            boolean res2 = this.updateBatchById(dormList2);
            if (!res2) {
                throw new Exception("修改宿舍入住人数失败");
            }

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

    @Override
    public AjaxResult manyOpen(List<Long> ids) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            List<DmsDormitory> updateList = new ArrayList<>();
            for (Long id : ids) {
                DmsDormitory item = new DmsDormitory();
                item.setId(id);
                item.setIsNew("1");
                updateList.add(item);
            }

            boolean res = this.updateBatchById(updateList);
            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 openNotFull() {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            _dormMapper.openNotFull();

            _dormMapper.closeFull();

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


    @Override
    public AjaxResult updateDorm(DmsDormitory param) {
        try {

            _dormMapper.updateById(param);

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

    /**
     * 批量添加宿舍
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult batchAdd(DormitoryDto dto) {
        String username = SecurityUtils.getUsername();
        long bedCount = 0;
        //要存储的宿舍列表
        List<DmsDormitory> dormitoryList = new ArrayList<>();
        //获取该楼层该单元的所有宿舍
        List<DmsDormitory> checkDormitoryList = lambdaQuery()
                .eq(DmsDormitory::getFloorId, dto.getFloorId())
                .list();
        //将该楼层该单元所有宿舍的宿舍号提取出来装进一个链表
        List<Long> roomNoList = checkDormitoryList.stream()
                .map(DmsDormitory::getRoomNo)
                .collect(Collectors.toList());
        Long startNo = dto.getStartNo();
        for (int i = 0; i < dto.getNum(); i++) {
            //校验宿舍号是否存在
            if (roomNoList.contains(startNo)) {
                throw new RuntimeException(startNo + "号宿舍已经存在");
            }
            DmsDormitory dormitory = new DmsDormitory();
            dormitory.setBedNum(dto.getBedNum());
            dormitory.setFloorId(dto.getFloorId());
            dormitory.setRoomNo(startNo);
            dormitory.setChargeStandard(BigDecimal.valueOf(dto.getBedChange()));
            dormitory.setCreateBy(username);
            startNo += 1;
            dormitoryList.add(dormitory);
            bedCount += dto.getBedNum();
        }
        boolean saveDormitory = saveBatch(dormitoryList);
        if (!saveDormitory) throw new RuntimeException("添加宿舍错误");


        dormitoryList.forEach(dor -> {
            if (dto.getPhotoList() != null) {
                QueryWrapper<DmsPhotos> dpQuery = new QueryWrapper<>();
                dpQuery.eq("dorm_id", dor.getId())
                        .last("limit 1");
                DmsPhotos dmsPhotos = _photoMapper.selectOne(dpQuery);
                if (dmsPhotos == null) {
                    dmsPhotos = new DmsPhotos();
                    dmsPhotos.setDormId(dor.getId());
                }
                dmsPhotos.setUrl(dto.getPhotoList());
                boolean savePhotos = dmsPhotosService.saveOrUpdate(dmsPhotos);
                if (!savePhotos) throw new RuntimeException("修改图片信息错误");
            }

        });

        int updateBuilding = dmsDormitoryBuildingInfoMapper.updateBedCountByDormitoryId(bedCount, dormitoryList.get(0).getId());
        if (updateBuilding <= 0) throw new RuntimeException("系统错误，请稍后重试");
        return AjaxResult.success("添加成功");
    }

    /**
     * 查看宿舍列表
     *
     * @param params 请求参数
     * @return
     */
    @Override
    public List<DormitoryVo> getDormitoryList(Map<String, Object> params) {
        return baseMapper.getDormitoryList(params);
    }

    @Override
    public List<DormitoryVo> getCanDormList(Map<String, Object> params) {
        return baseMapper.getCanDormList(params);
    }

    @Override
    public List<DormitoryVo> getAllDormList(DmsSearch params) {
        return baseMapper.getAllDormList(params);
    }

    /**
     * 修改宿舍信息
     *
     * @param dormitoryDto 请求参数
     * @param username     操作人
     * @return
     */
    @Transactional
    @Override
    public AjaxResult updateDmsDormitory(DormitoryDto dormitoryDto, String username) {
        if (dormitoryDto.getId() == null) {
            return AjaxResult.error("请输入宿舍ID");
        }
        if (dormitoryDto.getFloorId() == null) {
            return AjaxResult.error("请输入楼层ID");
        }
        DmsDormitory dmsDormitory = baseMapper.selectById(dormitoryDto.getId());
        if (dmsDormitory == null) {
            return AjaxResult.error("宿舍ID不存在");
        }
        if (dormitoryDto.getRoomNo() != null) {
            boolean hasNo = lambdaQuery()
                    .eq(DmsDormitory::getRoomNo, dormitoryDto.getRoomNo())
                    .eq(DmsDormitory::getFloorId, dormitoryDto.getFloorId())
                    .ne(DmsDormitory::getId, dormitoryDto.getId())
                    .last("limit 1")
                    .one() == null;
            if (!hasNo) {
                return AjaxResult.error("该宿舍号已存在，无法修改");
            }
        }

        if (dormitoryDto.getPhotoList() != null) {
            QueryWrapper<DmsPhotos> dpQuery = new QueryWrapper<>();
            dpQuery.eq("dorm_id", dormitoryDto.getId())
                    .last("limit 1");
            DmsPhotos dmsPhotos = _photoMapper.selectOne(dpQuery);
            if (dmsPhotos == null) {
                dmsPhotos = new DmsPhotos();
                dmsPhotos.setDormId(dormitoryDto.getId());
            }
            dmsPhotos.setUrl(dormitoryDto.getPhotoList());
            boolean savePhotos = dmsPhotosService.saveOrUpdate(dmsPhotos);
            if (!savePhotos) throw new RuntimeException("修改图片信息错误");
        }


        dmsDormitory.setUpdateBy(username);
        BeanUtils.copyProperties(dormitoryDto, dmsDormitory);
        int i = baseMapper.updateById(dmsDormitory);
        if (i > 0) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    /**
     * 添加宿舍
     *
     * @param dormitoryDto 请求参数
     * @param username     操作人
     * @return
     */
    @Transactional
    @Override
    public AjaxResult addDmsDormitory(DormitoryDto dormitoryDto, String username) {
        DmsDormitory dmsDormitory = new DmsDormitory();
        if (dormitoryDto.getRoomNo() == null) {
            return AjaxResult.error("请填写房间号");
        }
        if (dormitoryDto.getFloorId() == null) {
            return AjaxResult.error("请填写楼层ID");
        }
        if (dormitoryDto.getBedNum() == null) {
            return AjaxResult.error("请填写床位数");
        }

        boolean hasNo = lambdaQuery()
                .eq(DmsDormitory::getFloorId, dormitoryDto.getFloorId())
                .eq(DmsDormitory::getRoomNo, dormitoryDto.getRoomNo()).last("limit 1").one() == null;
        if (!hasNo) {
            return AjaxResult.error("该房间已存在");
        }
        BeanUtils.copyProperties(dormitoryDto, dmsDormitory);
        dmsDormitory.setCreateBy(username);
        dmsDormitory.setOccupancy(0);
        dmsDormitory.setStatus(0);
        int insert = baseMapper.insert(dmsDormitory);
        if (insert <= 0) {
            throw new RuntimeException("操作失败");
        }
        if (dormitoryDto.getPhotoList() != null) {
            QueryWrapper<DmsPhotos> dpQuery = new QueryWrapper<>();
            dpQuery.eq("dorm_id", dmsDormitory.getId())
                    .last("limit 1");
            DmsPhotos dmsPhotos = _photoMapper.selectOne(dpQuery);
            if (dmsPhotos == null) {
                dmsPhotos = new DmsPhotos();
                dmsPhotos.setDormId(dormitoryDto.getId());
            }
            dmsPhotos.setUrl(dormitoryDto.getPhotoList());
            boolean savePhotos = dmsPhotosService.saveOrUpdate(dmsPhotos);
            if (!savePhotos) throw new RuntimeException("修改图片信息错误");
        }

        List<DmsDormitoryBed> bedList = new ArrayList<>();
        for (int i = 0; i < dormitoryDto.getBedNum(); i++) {
            DmsDormitoryBed dmsDormitoryBed = new DmsDormitoryBed();
            dmsDormitoryBed.setDormitoryId(dmsDormitory.getId());
            dmsDormitoryBed.setBedCode((i + 1) + "");
            dmsDormitoryBed.setCreateBy(username);
            dmsDormitoryBed.setBedCharge(dormitoryDto.getBedChange());
            bedList.add(dmsDormitoryBed);
        }
        boolean saveBed = bedService.saveBatch(bedList);
        if (!saveBed) throw new RuntimeException("添加床位失败");
        long bedCount = dormitoryDto.getBedNum();
        int count = dmsDormitoryBuildingInfoMapper.updateBedCountByDormitoryId(bedCount, dmsDormitory.getId());
        if (count < 0) {
            throw new RuntimeException("操作失败");
        }
        return AjaxResult.success("添加成功");
    }

    /**
     * 批量删除宿舍
     *
     * @param ids 宿舍id列表
     * @return
     */
    @Transactional
    @Override
    public AjaxResult batchDeleteDmsDormitory(List<Long> ids) {
        List<DmsDormitoryBed> list = bedService.lambdaQuery()
                .in(DmsDormitoryBed::getDormitoryId, ids)
                .list();
        if (!CollectionUtils.isEmpty(list)) {
            boolean removeBed = bedService.removeBatchByIds(list);
            if (!removeBed) {
                throw new RuntimeException("操作失败");
            }
        }
        boolean removeDormitory = removeBatchByIds(ids);
        if (removeDormitory) {
            return AjaxResult.success();
        }
        throw new RuntimeException("操作失败");
    }

    /**
     * 根据id删除宿舍
     *
     * @param id 宿舍id
     * @return
     */
    @Transactional
    @Override
    public AjaxResult deleteDmsDormitory(Long id) {
        int i1 = baseMapper.deleteById(id);
        if (i1 <= 0) {
            throw new RuntimeException();
        }
        LambdaQueryWrapper<DmsDormitoryBed> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DmsDormitoryBed::getDormitoryId, id);
        long i = bedService.getBaseMapper().delete(wrapper);
        if (i <= 0) {
            throw new RuntimeException("操作失败");
        }
        int count = dmsDormitoryBuildingInfoMapper.updateBedCountByDormitoryId(-i, id);
        if (count <= 0) {
            throw new RuntimeException("操作失败");
        }
        return AjaxResult.success();
    }

    /**
     * 查看宿舍详细信息
     *
     * @param id 宿舍id
     * @return
     */
    @Override
    public AjaxResult getDormitoryInfo(Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("dormitoryId", id);
        List<Map<String, Object>> dormitoryInfoList = baseMapper.getDormitoryInfoList(map);
        if (dormitoryInfoList.isEmpty()) {
            return AjaxResult.error("宿舍id错误");
        }
        List<SrsDormitoryStudent> dormitoryStudents = srsDormitoryStudentService.lambdaQuery()
                .eq(SrsDormitoryStudent::getDormitoryId, id)
                .list();
        List<String> stuNoList = dormitoryStudents.stream().map(SrsDormitoryStudent::getStuNo).collect(Collectors.toList());
        List<Map<String, Object>> studentList = null;
        if (!CollectionUtils.isEmpty(stuNoList)) {
            studentList = srsDormitoryStudentMapper.selectStudentByStuNoList(stuNoList);
        }
        DmsPhotos photos = dmsPhotosService.lambdaQuery()
                .eq(DmsPhotos::getDormId, id)
                .last("limit 1")
                .one();

        dormitoryInfoList.get(0).put("photoList", photos == null ? "" : photos.getUrl());
        dormitoryInfoList.get(0).put("studentList", studentList);
        return AjaxResult.success(dormitoryInfoList.get(0));
    }

    /**
     * 批量清空宿舍照片
     *
     * @param ids 宿舍id列表
     * @return
     */
    @Override
    public AjaxResult batchDeleteDormitoryPhoto(List<Long> ids) {
        boolean remove = dmsPhotosService.lambdaUpdate()
                .in(DmsPhotos::getDormId, ids)
                .remove();
        if (remove) return AjaxResult.success();
        return AjaxResult.error();
    }

    /**
     * 批量添加宿舍照片
     *
     * @param dto 请求参数
     * @return
     */
    @Override
    public AjaxResult batchAddDormitoryPhoto(AddDormitoryPhotosDto dto) {
        List<DmsPhotos> photosList = new ArrayList<>();
        for (Long id : dto.getIds()) {
            for (String url : dto.getUrls()) {
                DmsPhotos photos = new DmsPhotos();
                photos.setDormId(id);
                photos.setUrl(url);
                photosList.add(photos);
            }
        }
        boolean saveBatch = dmsPhotosService.saveBatch(photosList);
        if (!saveBatch) return AjaxResult.error();
        return AjaxResult.success();
    }

    /**
     * 导出宿舍信息表
     *
     * @param params
     * @return
     */
    @Override
    public List<DormitoryVo> exportDormitoryList(Map<String, Object> params) {
        return baseMapper.exportDormitoryList(params);
    }

    /**
     * 导入宿舍
     *
     * @param list
     * @return
     */
    @Override
    @Transactional
    public AjaxResult importDormitory(List<ImportDormitoryModel> list) {
        List<DmsDormitoryPark> parkList = dmsDormitoryParkService.list();
        Map<String, Map<String, Map<Long, Long>>> map = new HashMap<>();
        parkList.forEach(park -> {
            Map<String, Map<Long, Long>> buildingMap = new HashMap<>();
            List<DmsDormitoryBuilding> buildingList = dmsDormitoryBuildingService.lambdaQuery().eq(DmsDormitoryBuilding::getParkId, park.getId()).list();
            buildingList.forEach(building -> {
                Map<Long, Long> floorMap = new HashMap<>();
                List<DmsDormitoryFloor> floorList = dmsDormitoryFloorService.lambdaQuery().eq(DmsDormitoryFloor::getBuildingId, building.getId())
                        .orderByDesc(DmsDormitoryFloor::getFloor)
                        .list();
                floorList.forEach(floor -> {
                    floorMap.put(floor.getFloor(), floor.getId());
                });
                buildingMap.put(building.getName(), floorMap);
            });
            map.put(park.getName(), buildingMap);
        });
        List<DmsDormitory> dormitoryList = new ArrayList<>();
        list.forEach(dor -> {
            if (dor.getOccupancy() == null) dor.setOccupancy(0);
            if (dor.getBed() == null) dor.setBed(0);
            DmsDormitory dormitory = new DmsDormitory();
            dormitory.setOccupancy(0);
            dormitory.setBedNum(dor.getBed() + dor.getOccupancy());
            dormitory.setRoomNo(dor.getRoomNo());
            dormitory.setFloorId(map.get(dor.getParkName()).get(dor.getBuildingName()).get(Long.valueOf(dor.getRoomNo().toString().charAt(0) + "")));
            dormitory.setChargeStandard(new BigDecimal(100));
            dormitoryList.add(dormitory);
        });
        boolean b = saveBatch(dormitoryList);
        if (!b) return AjaxResult.error("导入失败");


        return AjaxResult.success();
    }

    /**
     * 根据宿舍id查看宿舍学生
     *
     * @param id 宿舍Id
     * @return
     */
    @Override
    public AjaxResult getStudentById(Long id) {
        List<Map<String, Object>> studentList = baseMapper.getStudentById(id);
        return AjaxResult.success(studentList);
    }


    @Override
    public List<DomInfo> countParkStuIn() {
        return _dormMapper.countParkStuIn();
    }

    @Override
    public List<DomInfo> countRecordConfirmStatus() {
        return _dormMapper.countRecordConfirmStatus();
    }

    @Override
    public AjaxResult importDorm(List<DomInfo> param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            StringBuilder resMsg = new StringBuilder();
            List<DmsDormitory> saveList = new ArrayList<>();

            List<DomInfo> viewDormList = _dormMapper.viewDormInfo();

            List<DomInfo> viewFloorList = _floorMapper.viewFloorInfo();

            for(DomInfo dorm : param){
                DmsDormitory temp = new DmsDormitory();
                temp.setIsNew("0");

                DomInfo findDorm = viewDormList.stream().filter(
                        x-> Objects.equals(x.parkName, dorm.parkName) &&
                                Objects.equals(x.buildingName, dorm.buildingName) &&
                                Objects.equals(x.floor, dorm.floor) &&
                                Objects.equals(x.roomNo, dorm.roomNo)
                ).findAny().orElse(null);

                temp.setBedNum(Integer.valueOf(dorm.bedNum));
                temp.gender = dorm.gender;
                temp.setChargeStandard(dorm.chargeStandard);

                if(findDorm != null){
                    temp.setId(findDorm.id);
                }else{
                    DomInfo findFloor = viewFloorList.stream().filter(
                            x->
                                Objects.equals(x.parkName, dorm.parkName) &&
                                        Objects.equals(x.buildingName, dorm.buildingName) &&
                                        Objects.equals(x.floor, dorm.floor)
                    ).findAny().orElse(null);

                    if(findFloor == null){
                        resMsg.append("房间号为:").append(dorm.roomNo).append("的楼层不存在，请先去添加;");
                        continue;
                    }else{
                        temp.setRoomNo(Long.valueOf(Long.parseLong(dorm.roomNo )));
                        temp.setFloorId(findFloor.floorId);
                    }
                }
                saveList.add(temp);
            }

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


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

    @Override
    public DomInfo getDormHas(Long id){
        return _dormMapper.getDormHas(id);
    }


}
