package com.org.web.room.service;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.system.enums.YesOrNoState;
import com.org.utils.SecurityUtil;
import com.org.web.room.domain.BcRoomBed;
import com.org.web.room.mapper.BcRoomBedMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
@Slf4j
public class BcRoomBedService extends ServiceImpl<BcRoomBedMapper, BcRoomBed> {

    /**
     * 新增或编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void executeSaveOrUpdate(Long roomId, List<BcRoomBed> resultList) {
        Long userId = SecurityUtil.getUserId();

        for (BcRoomBed bcRoomBed : resultList) {
            if (ObjectUtil.isEmpty(bcRoomBed.getId())) {
                bcRoomBed.setCreateBy(userId);
                bcRoomBed.setCreateTime(new Date());
                bcRoomBed.setIsDelete(YesOrNoState.NO.getState());
            } else {
                bcRoomBed.setUpdateBy(userId);
                bcRoomBed.setUpdateTime(new Date());
            }

            bcRoomBed.setRoomId(roomId);
        }
        this.saveOrUpdateBatch(resultList);

        List<Long> idList = resultList.stream().map(i -> i.getId()).collect(toList());
        // 删除编辑中没有的数据
        baseMapper.deleteWithout(roomId, idList, userId);
    }

    /**
     * 列表
     */
    public List<BcRoomBed> listByRoomId(Long roomId) {
        log.info("BcRoomBedService - listByRoomId roomId:{}", roomId);

        return baseMapper.listByRoomId(roomId);
    }

    /**
     * 删除
     */
    public boolean delByRoomId(Long roomId) {
        log.info("BcRoomBedService - del roomId:{}", roomId);

        baseMapper.deleteByRoomId(roomId, SecurityUtil.getUserId());

        return true;
    }


}
