package cn.iocoder.yudao.module.portal.service.user;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.portal.controller.admin.portaluser.vo.*;
import cn.iocoder.yudao.module.portal.dal.dataobject.portaluser.PortalUserDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.portal.dal.mysql.portaluser.PortalUserMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.portal.enums.ErrorCodeConstants.*;

/**
 * 用户 Service 实现类
 *
 * @author 篮智科技
 */
@Service
@Validated
public class PortalServiceImpl implements PortalUserService {

    @Resource
    private PortalUserMapper portalUserMapper;

    @Override
    public Long createUser(PortalUserSaveReqVO createReqVO) {
        // 插入
        PortalUserDO user = BeanUtils.toBean(createReqVO, PortalUserDO.class);
        portalUserMapper.insert(user);
        // 返回
        return user.getId();
    }

    @Override
    public void updateUser(PortalUserSaveReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        PortalUserDO updateObj = BeanUtils.toBean(updateReqVO, PortalUserDO.class);
        portalUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);
        // 删除
        portalUserMapper.deleteById(id);
    }

    private void validateUserExists(Long id) {
        if (portalUserMapper.selectById(id) == null) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public PortalUserDO getUser(Long id) {
        return portalUserMapper.selectById(id);
    }

    @Override
    public PageResult<PortalUserDO> getUserPage(PortalUserPageReqVO pageReqVO) {
        return portalUserMapper.selectPage(pageReqVO);
    }

}