package com.srs.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.bean.BeanUtils;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.dormitory.domain.DmsDormitory;
import com.srs.dormitory.domain.DmsDormitoryBed;
import com.srs.dormitory.domain.Dto.BedDto;
import com.srs.dormitory.domain.Dto.BedInfo;
import com.srs.dormitory.domain.Dto.StuRoomInfo;
import com.srs.dormitory.domain.SrsDormitoryStudent;
import com.srs.dormitory.domain.Vo.DmsDormitoryBedStudent;
import com.srs.dormitory.mapper.DmsDormitoryBedMapper;
import com.srs.dormitory.mapper.SrsDormitoryStudentMapper;
import com.srs.dormitory.service.IDmsDormitoryBedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.dormitory.service.IDmsDormitoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 宿舍床位表 服务实现类
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-14
 */
@Service
public class IDmsDormitoryBedServiceImpl extends ServiceImpl<DmsDormitoryBedMapper, DmsDormitoryBed> implements IDmsDormitoryBedService {
    @Autowired
    private SrsDormitoryStudentMapper srsDormitoryStudentMapper;
    @Autowired
    private SrsStudentMapper srsStudentMapper;
    @Autowired
    private IDmsDormitoryService dmsDormitoryService;


    /***
     * 通过宿舍id查询床位信息
     * @author zhy
     * @date 2023-08-15 10:43:54
     * @param id
     * @return
     **/
    public AjaxResult getBedsByDormId(Long id){
        List<BedInfo> res = srsDormitoryStudentMapper.selectBedInfoByDormId(id);
        return AjaxResult.success(res);
    }

    /**
     * 通过考生号查询宿舍信息
     * @author zhy
     * @date 2023-08-16 16:36:04
     * @param ksh
     * @return
     **/
    public AjaxResult getOwnRoomInfo(String ksh){
        List<StuRoomInfo> res = srsDormitoryStudentMapper.selectStuRoomInfoByKsh(ksh);
        if(res.size() == 0){
            return AjaxResult.success(res);
        }else{
            return AjaxResult.success(res.get(0));
        }
    }


    /**
     * 查看床位详细信息
     * @param id 床位id
     * @return
     */
    @Override
    public AjaxResult getCphDormitoryBedDetail(Long id) {
        DmsDormitoryBed bed = getById(id);
        if (bed==null){
            return AjaxResult.error("床位id错误");
        }
        LambdaQueryWrapper<SrsDormitoryStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SrsDormitoryStudent::getBedId,id);
        SrsDormitoryStudent dormitoryStudent = srsDormitoryStudentMapper.selectOne(wrapper);
        SrsStudent srsStudent = null;
        if (dormitoryStudent!=null){
            srsStudent = srsStudentMapper.selectSrsStudentByStuNo(dormitoryStudent.getStuNo());
        }
        DmsDormitoryBedStudent dmsDormitoryBedStudent = new DmsDormitoryBedStudent();
        BeanUtils.copyProperties(bed, dmsDormitoryBedStudent);
        dmsDormitoryBedStudent.setStudent(srsStudent);
        return AjaxResult.success(dmsDormitoryBedStudent);
    }

    /**
     * 查看宿舍床位
     * @param id 宿舍id
     * @return
     */
    @Override
    public AjaxResult getCphDormitoryByDormitoryId(Long id) {
        List<Map<String, Object>> mapList = baseMapper.getDmsDormitoryByDormitoryId(id);
        return AjaxResult.success(mapList);
    }
    /**
     * 修改宿舍床位
     * @param bedDto 请求参数
     * @param username 操作人
     * @return
     */
    @Override
    public AjaxResult updateDmsDormitoryBed(BedDto bedDto, String username) {
        if (bedDto.getId()==null){
            return AjaxResult.error("请输入床位ID");
        }
        Long bedId = bedDto.getId();
        DmsDormitoryBed bed = baseMapper.selectById(bedId);
        if (bed==null) return AjaxResult.error("id错误");
        bed.setDormitoryId(bedDto.getDormitoryId()==null?bed.getDormitoryId():bedDto.getDormitoryId());
        bed.setBedCode(bedDto.getBedCode()==null?bed.getBedCode(): bedDto.getBedCode());
        bed.setBedCharge(bedDto.getBedChange()==null? bed.getBedCharge() : bedDto.getBedChange());
        int i = baseMapper.updateById(bed);
        if (i>0){
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }
    /**
     * 添加宿舍床位
     * @param bedDto 请求参数
     * @param username 操作人
     * @return
     */
    @Transactional
    @Override
    public AjaxResult addDmsDormitoryBed(BedDto bedDto, String username) {
        DmsDormitoryBed bed = new DmsDormitoryBed();
        if (bedDto.getDormitoryId()==null){
            return AjaxResult.error("请输入宿舍ID");
        }
        if (bedDto.getBedCode() == null) {
            return AjaxResult.error("请输入床位编号");
        }
        boolean updateDormitory = dmsDormitoryService.lambdaUpdate()
                .eq(DmsDormitory::getId, bedDto.getDormitoryId())
                .setSql("bed_num = bed_num + 1")
                .update();
        if (!updateDormitory) throw new RuntimeException("修改宿舍床位数失败");
        bed.setCreateBy(username);
        bed.setBedCode(bedDto.getBedCode());
        bed.setDormitoryId(bedDto.getDormitoryId());
        boolean saveBed = save(bed);
        if (!saveBed) throw new RuntimeException("添加床位失败");
        return AjaxResult.success();
    }

    /**
     * 根据id删除床位
     * @param id
     * @return
     */
    @Transactional
    @Override
    public AjaxResult deleteById(Long id) {
        DmsDormitoryBed bed = baseMapper.selectById(id);
        boolean updateDormitory = dmsDormitoryService.lambdaUpdate()
                .eq(DmsDormitory::getId,bed.getDormitoryId())
                .setSql("bed_num = bed_num -1")
                .update();
        if (!updateDormitory) throw new RuntimeException("修改宿舍床位数失败");
        boolean remove = removeById(id);
        if (!remove) throw new RuntimeException("删除床位失败");
        return AjaxResult.success();
    }

    /**
     * 批量删除床位
     * @param ids 床位id列表
     * @return
     */
    @Transactional
    @Override
    public AjaxResult batchDeleteDormitoryBed(List<Long> ids) {
        List<DmsDormitoryBed> bedList = lambdaQuery().in(DmsDormitoryBed::getId, ids).list();
        Map<Long,Integer> map = new HashMap<>();
        for (DmsDormitoryBed bed : bedList){
            map.merge(bed.getDormitoryId(),1,Integer::sum);
        }
        for (Long key : map.keySet()){
            boolean updateDormitory = dmsDormitoryService.lambdaUpdate()
                    .eq(DmsDormitory::getId, key)
                    .setSql("bed_num = bed_num - " + map.get(key))
                    .update();
            if (!updateDormitory) throw new RuntimeException("修改宿舍床位失败");
        }
        boolean removeBed = lambdaUpdate().in(DmsDormitoryBed::getId, ids).remove();
        if (!removeBed) throw new RuntimeException("删除床位失败");
        return AjaxResult.success();
    }
}
