package cn.iocoder.yudao.module.system.service.nursing;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.NursingShiftPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.NursingShiftSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.NursingShiftDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.NursingShiftMapper;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

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

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 护理班次 Service 实现类
 *
 * @author 源码
 */
@Service
@Validated
public class NursingShiftServiceImpl implements NursingShiftService {

    @Resource
    private NursingShiftMapper shiftMapper;
    @Resource
    private TenantMapper tenantMapper;


    @Override
    public void createShift(NursingShiftSaveReqVO createReqVO) {
        List<NursingShiftDO> nursingShiftList = shiftMapper.selectList(new LambdaQueryWrapperX<NursingShiftDO>()
                .eq(NursingShiftDO::getName, createReqVO.getName())
                .eqIfPresent(NursingShiftDO::getTenantId,createReqVO.getTenantId()));
        if (CollectionUtil.isNotEmpty(nursingShiftList)){
            throw exception(ErrorCodeConstants.COMMON_EXIST_ERROR);
        }
        NursingShiftDO shiftDO = new NursingShiftDO();
        BeanUtils.copyProperties(createReqVO, shiftDO);
        shiftDO.setCreatedTime(new Date());
        shiftDO.setCreatedBy(SecurityFrameworkUtils.getLoginUserNickname());
        shiftMapper.insert(shiftDO);
    }

    @Override
    public NursingShiftDO getNursingShift(Long id) {
        return shiftMapper.selectById(id);
    }

    @Override
    public void deleteShift(Long[] ids) {
        shiftMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public PageResult<NursingShiftDO> getNursingShiftPage(NursingShiftPageReqVO pageReqVO) {
        PageResult<NursingShiftDO> pageResult = shiftMapper.selectPage(pageReqVO);
        for (NursingShiftDO shiftDO : pageResult.getList()) {
            shiftDO.setTenantName(tenantMapper.selectById(shiftDO.getTenantId()).getName());
        }
        return pageResult;
    }

    @Override
    public void updateShift(NursingShiftDO updateReqVO) {
        shiftMapper.updateById(updateReqVO);
    }

    @Override
    public List<NursingShiftDO> getList() {
        return shiftMapper.selectList(null);
    }

}