package com.xjrsoft.module.room.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.module.base.entity.BaseOfficeBuild;
import com.xjrsoft.module.base.mapper.BaseOfficeBuildMapper;
import com.xjrsoft.module.room.dto.AddRoomDto;
import com.xjrsoft.module.room.dto.RoomPageDto;
import com.xjrsoft.module.room.entity.Room;
import com.xjrsoft.module.room.entity.RoomBed;
import com.xjrsoft.module.room.entity.RoomRule;
import com.xjrsoft.module.room.entity.RoomRuleItem;
import com.xjrsoft.module.room.mapper.RoomBedMapper;
import com.xjrsoft.module.room.mapper.RoomMapper;
import com.xjrsoft.module.room.mapper.RoomRuleMapper;
import com.xjrsoft.module.room.service.IRoomService;
import com.xjrsoft.module.room.vo.RoomExcelVo;
import com.xjrsoft.module.room.vo.RoomPageVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @title: 寝室
* @Author dzx
* @Date: 2023-12-27
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class RoomServiceImpl extends MPJBaseServiceImpl<RoomMapper, Room> implements IRoomService {
    private final RoomMapper roomMapper;
    private final RoomBedMapper roomBedMapper;
    private final RoomRuleMapper roomRuleRoomRuleMapper;
    private final BaseOfficeBuildMapper baseOfficeBuildMapper;
    @Override
    public Page<RoomPageVo> getPage(Page<RoomPageVo> page, RoomPageDto dto) {
        Page<RoomPageVo> result = roomMapper.getPage(page, dto);
        return result;
    }

    @Override
    public List<RoomExcelVo> getList(RoomPageDto dto) {
        List<RoomExcelVo> list = roomMapper.getList(dto);
        for (RoomExcelVo roomExcelVo : list) {
            if("1".equals(roomExcelVo.getIsMax())){
                roomExcelVo.setIsMax("是");
            }else if("0".equals(roomExcelVo.getIsMax())){
                roomExcelVo.setIsMax("否");
            }
        }
        return list;
    }

    @Override
    public String saveBatch(AddRoomDto dto) {
        MPJLambdaWrapper<RoomRule> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.leftJoin(RoomRuleItem.class, RoomRuleItem::getRoomRuleId, RoomRule::getId)
                .eq(RoomRuleItem::getOfficeBuildId, dto.getOfficeBuildId());
        RoomRule roomRule = roomRuleRoomRuleMapper.selectJoinOne(RoomRule.class, queryWrapper);
        if(roomRule == null){
            throw new MyException("该楼栋未配置规则，请先配置规则") ;
        }
        BaseOfficeBuild build = baseOfficeBuildMapper.selectById(dto.getOfficeBuildId());

        Integer maxSortCode = roomMapper.getMaxSortCode();
        Date createDate = new Date();
        long createUserId = StpUtil.getLoginIdAsLong();
        String[] split = dto.getFloorNumber().split(",");
        List<Integer> floorList = new ArrayList<>();
        for (String floorStr : split) {
            floorList.add(Integer.parseInt(floorStr));
        }
        Collections.sort(floorList);
        for (Integer floorNumber : floorList) {
            for (int i = 0; i < dto.getFloorRoomsCount(); i ++){
                String roomName = "";
                if(roomRule.getRule().contains("1") && build.getBuildNumber() != null){
                    roomName += build.getBuildNumber();
                }
                if(roomRule.getRule().contains("2")){
                    roomName += floorNumber;
                }
                if(roomRule.getRule().contains("3")){
                    roomName += String.format("%02d", (i + 1));
                }

                Map<String, Object> param = new HashMap<>();
                param.put("room_name", roomName);
                param.put("floor_number", floorNumber);
                param.put("office_build_id", dto.getOfficeBuildId());
                List<Room> rooms = roomMapper.selectByMap(param);
                if(rooms != null && !rooms.isEmpty()){
                    continue;
                }

                //先添加寝室
                maxSortCode ++;
                Room room = BeanUtil.toBean(dto, Room.class);
                room.setSortCode(maxSortCode);
                room.setFloorNumber(floorNumber);
                room.setCreateDate(createDate);
                room.setCreateUserId(createUserId);
                room.setDeleteMark(0);
                room.setEnabledMark(1);
                room.setRoomName(roomName);
                roomMapper.insert(room);

                Long roomId = room.getId();
                Integer bedMaxSortCode = roomBedMapper.getMaxSortCode() + 1;
                //生成床位数据
                for (int j = 1; j <= dto.getBedCount(); j ++){
                    RoomBed bed = new RoomBed();
                    bed.setRoomId(roomId);
                    bed.setSortCode(bedMaxSortCode + j - 1);
                    bed.setCreateDate(createDate);
                    bed.setCreateUserId(createUserId);
                    bed.setDeleteMark(0);
                    bed.setEnabledMark(1);
                    bed.setBedNumber(j);
                    roomBedMapper.insert(bed);
                }
            }
        }
        return "ok";
    }

    @Override
    public String deleteReachBed(Long id) {
        List<RoomBed> bedList = roomBedMapper.selectList(
            MPJWrappers.<RoomBed>lambdaJoin()
            .select(RoomBed::getStudentUserId)
            .eq(RoomBed::getRoomId, id).isNotNull(RoomBed::getStudentUserId)
        );
        if(bedList != null && !bedList.isEmpty()){
            return "寝室里面已安排学生，无法删除";
        }
        roomMapper.deleteById(id);
        Map<String, Object> param = new HashMap<>();
        param.put("room_id", id);
        roomBedMapper.deleteByMap(param);
        return "ok";
    }
}
