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

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.authentication.vo.AuthenticationPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.authentication.vo.AuthenticationSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.authentication.AuthenticationDO;
import cn.iocoder.yudao.module.system.dal.mysql.authentication.AuthenticationMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

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

/**
 * 认证 Service 实现类
 *
 * @author ruiqi
 */
@Service
@Validated
public class AuthenticationServiceImpl implements AuthenticationService {

    @Resource
    private AuthenticationMapper authenticationMapper;

    @Override
    public Long createAuthentication(AuthenticationSaveReqVO createReqVO) {
        // 插入
        AuthenticationDO authentication = BeanUtils.toBean(createReqVO, AuthenticationDO.class);
        authenticationMapper.insert(authentication);
        // 返回
        return authentication.getId();
    }

    @Override
    public void updateAuthentication(AuthenticationSaveReqVO updateReqVO) {
        // 校验存在
        validateAuthenticationExists(updateReqVO.getId());
        // 更新
        AuthenticationDO updateObj = BeanUtils.toBean(updateReqVO, AuthenticationDO.class);
        authenticationMapper.updateById(updateObj);
    }

    @Override
    public void deleteAuthentication(Long id) {
        // 校验存在
        validateAuthenticationExists(id);
        // 删除
        authenticationMapper.deleteById(id);
    }

    private void validateAuthenticationExists(Long id) {
        if (authenticationMapper.selectById(id) == null) {
            throw exception(AUTHENTICATION_NOT_EXISTS);
        }
    }

    @Override
    public AuthenticationDO getAuthentication(Long id) {
        return authenticationMapper.selectById(id);
    }

    @Override
    public PageResult<AuthenticationDO> getAuthenticationPage(AuthenticationPageReqVO pageReqVO) {
        return authenticationMapper.selectPage(pageReqVO);
    }

}