package com.srs.dormitory.service.impl;

import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.SecurityUtils;
import com.srs.dormitory.domain.*;
import com.srs.dormitory.domain.Dto.AddBuildingDto;
import com.srs.dormitory.domain.Dto.BuildingDto;
import com.srs.dormitory.mapper.DmsDormitoryBuildingMapper;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 宿舍楼表 服务实现类
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-14
 */
@Service
public class IDmsDormitoryBuildingServiceImpl extends ServiceImpl<DmsDormitoryBuildingMapper, DmsDormitoryBuilding> implements IDmsDormitoryBuildingService {

    @Autowired
    private IDmsDormitoryBuildingInfoService dmsDormitoryBuildingInfoService;
    @Autowired
    private IDmsDormitoryFloorService dmsDormitoryFloorService;
    @Autowired
    private IDmsDormitoryParkService dmsDormitoryParkService;

    /**
     * 添加宿舍楼
     *
     * @param buildingDto 请求参数
     * @param username    操作人
     * @return
     */
    @Transactional
    @Override
    public AjaxResult addDmsDormitoryBuilding(AddBuildingDto buildingDto, String username) {
        DmsDormitoryPark park = null;
        if (buildingDto.getParkId() == 0) {
            park = dmsDormitoryParkService.lambdaQuery()
                    .eq(DmsDormitoryPark::getName, "default")
                    .one();
            buildingDto.setParkId(park.getId());
        } else {
            park = dmsDormitoryParkService.getById(buildingDto.getParkId());
            if (park == null) return AjaxResult.error("园区id错误");
        }
        DmsDormitoryBuilding checkName = lambdaQuery()
                .eq(DmsDormitoryBuilding::getName, buildingDto.getName())
                .eq(DmsDormitoryBuilding::getParkId,buildingDto.getParkId())
                .one();
        if (checkName != null) return AjaxResult.error("宿舍楼名称已存在");
        DmsDormitoryBuilding dmsDormitoryBuilding = new DmsDormitoryBuilding();
        DmsDormitoryBuildingInfo dmsDormitoryBuildingInfo = new DmsDormitoryBuildingInfo();
        BeanUtils.copyProperties(buildingDto, dmsDormitoryBuildingInfo);
        BeanUtils.copyProperties(buildingDto, dmsDormitoryBuilding);
        dmsDormitoryBuilding.setCreateBy(username);
        int insert = baseMapper.insert(dmsDormitoryBuilding);
        dmsDormitoryBuildingInfo.setBuildingId(dmsDormitoryBuilding.getId());
        dmsDormitoryBuildingInfo.setCreateBy(username);
        boolean save = dmsDormitoryBuildingInfoService.save(dmsDormitoryBuildingInfo);
        if (insert <= 0 || !save) {
            throw new RuntimeException("操作失败");
        }
        List<DmsDormitoryFloor> floorList = new ArrayList<>();
        for (int i = 0; i < buildingDto.getFloorNumber(); i++) {
            DmsDormitoryFloor floor = new DmsDormitoryFloor();
            floor.setCreateBy(username);
            floor.setBuildingId(dmsDormitoryBuilding.getId());
            floor.setFloor((long) (i + 1));
            floorList.add(floor);
        }
        boolean b = dmsDormitoryFloorService.saveBatch(floorList);
        if (!b) {
            throw new RuntimeException("操作失败");
        }
        return AjaxResult.success();
    }

    /**
     * 查看宿舍楼列表
     *
     * @param buildingDto 请求参数
     * @return
     */
    @Override
    public List<Map<String, Object>> getDmsDormitoryBuildingList(BuildingDto buildingDto) {
        return baseMapper.getDmsDormitoryList(buildingDto);
    }

    /**
     * 修改宿舍信息
     *
     * @param buildingDto 请求参数
     * @return
     */
    @Transactional
    @Override
    public AjaxResult updateDmsDormitoryBuilding(BuildingDto buildingDto, String username) {
        if (buildingDto.getId() == null) {
            return AjaxResult.error("请输入宿舍楼Id");
        }
        DmsDormitoryBuilding building = baseMapper.selectById(buildingDto.getId());
        if (building == null) return AjaxResult.error("id不存在");
        DmsDormitoryBuildingInfo buildingInfo = dmsDormitoryBuildingInfoService.lambdaQuery()
                .eq(DmsDormitoryBuildingInfo::getBuildingId, building.getId())
                .one();
        Long bid=buildingInfo.getId();
        BeanUtils.copyProperties(buildingDto, buildingInfo);
        BeanUtils.copyProperties(buildingDto, building);
        buildingInfo.setUpdateBy(username);
        building.setUpdateBy(username);
        int i = baseMapper.updateById(building);
        buildingInfo.setId(bid);
        boolean b = dmsDormitoryBuildingInfoService.updateById(buildingInfo);
        if(buildingDto.getGender().equals("男")||buildingDto.getGender().equals("女")){ //整栋楼修改性别，为男或者是女，混合不能修改
            baseMapper.updateDormitoryGenderBatch(buildingInfo);
        }
        if (i <= 0 || !b) {
            throw new RuntimeException();
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除宿舍楼
     *
     * @param ids 宿舍楼id列表
     * @return
     */
    @Transactional
    @Override
    public AjaxResult batchDeleteDmsDormitoryBuilding(List<Long> ids) {
        for (Long id : ids) {
            if (!check(id)) {
                return AjaxResult.error("请先删除id为" + id + "的宿舍楼相对应的楼层");
            }
        }
        boolean removeBuildingInfo = dmsDormitoryBuildingInfoService.lambdaUpdate()
                .in(DmsDormitoryBuildingInfo::getBuildingId, ids)
                .remove();

        boolean b = removeBatchByIds(ids);
        if (!b || !removeBuildingInfo) {
            throw new RuntimeException("删除宿舍楼错误");
        }
        return AjaxResult.success();
    }

    /**
     * 校验该宿舍楼下是否还有楼层和单元
     *
     * @param id 宿舍楼id
     * @return
     */
    boolean check(Long id) {
        List<DmsDormitoryFloor> floor = dmsDormitoryFloorService.lambdaQuery()
                .eq(DmsDormitoryFloor::getBuildingId, id)
                .list();
        return floor.size() == 0;
    }

    /**
     * 查看宿舍楼详细信息
     *
     * @param id 宿舍楼id
     * @return
     */
    @Override
    public AjaxResult dmsDormitoryBuilding(Long id) {
        Map<String, Object> building = baseMapper.selectBuildingById(id);
        if (building == null) return AjaxResult.error("id不存在");
        Integer occupancy = baseMapper.selectTotalOccupancy(id);
        building.put("occupancy", occupancy);
        return AjaxResult.success("操作成功", building);
    }
}
