package cn.iocoder.yudao.module.system.service.attendance.group;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.group.vo.AttendanceGroupPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.group.vo.AttendanceGroupSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.attendance.group.AttendanceGroupDO;
import cn.iocoder.yudao.module.system.dal.mysql.attendance.group.AttendanceGroupMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.GROUP_NOT_EXISTS;

/**
 * 考勤组 Service 实现类
 *
 * @author 艾楷
 */
@Service
@Validated
public class AttendanceGroupServiceImpl implements AttendanceGroupService {

    @Resource
    private AttendanceGroupMapper groupMapper;

    @Override
    public Long createGroup(AttendanceGroupSaveReqVO createReqVO) {
        // 插入
        AttendanceGroupDO group = BeanUtils.toBean(createReqVO, AttendanceGroupDO.class);
        groupMapper.insert(group);
        // 返回
        return group.getId();
    }

    @Override
    public void updateGroup(AttendanceGroupSaveReqVO updateReqVO) {
        // 校验存在
        validateGroupExists(updateReqVO.getId());
        // 更新
        AttendanceGroupDO updateObj = BeanUtils.toBean(updateReqVO, AttendanceGroupDO.class);
        groupMapper.updateById(updateObj);
    }

    @Override
    public void deleteGroup(Long id) {
        // 校验存在
        validateGroupExists(id);
        // 删除
        groupMapper.deleteById(id);
    }

    private void validateGroupExists(Long id) {
        if (groupMapper.selectById(id) == null) {
            throw exception(GROUP_NOT_EXISTS);
        }
    }

    @Override
    public AttendanceGroupDO getGroup(Long id) {
        return groupMapper.selectById(id);
    }

    @Override
    public PageResult<AttendanceGroupDO> getGroupPage(AttendanceGroupPageReqVO pageReqVO) {
        return groupMapper.selectPage(pageReqVO);
    }

    @Override
    public AttendanceGroupDO getByUserId(Long userId) {
        List<AttendanceGroupDO> dos = groupMapper.getByUserId(userId);
        if (!dos.isEmpty()) {
            return dos.get(0);
        }
        return null;
    }

}