package cn.iocoder.yudao.module.iot.service.frps;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.iot.controller.admin.frps.vo.FrpsServerPageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.frps.vo.FrpsServerSaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.frps.FrpsServerDO;
import cn.iocoder.yudao.module.iot.dal.mysql.frps.FrpsServerMapper;
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.iot.enums.ErrorCodeConstants.FRPS_SERVER_NOT_EXISTS;

/**
 * 代理服务器 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class FrpsServerServiceImpl implements FrpsServerService {

    @Resource
    private FrpsServerMapper frpsServerMapper;

    @Override
    public Long createFrpsServer(FrpsServerSaveReqVO createReqVO) {
        // 插入
        FrpsServerDO frpsServer = BeanUtils.toBean(createReqVO, FrpsServerDO.class);
        frpsServerMapper.insert(frpsServer);
        // 返回
        return frpsServer.getId();
    }

    @Override
    public void updateFrpsServer(FrpsServerSaveReqVO updateReqVO) {
        // 校验存在
        validateFrpsServerExists(updateReqVO.getId());
        // 更新
        FrpsServerDO updateObj = BeanUtils.toBean(updateReqVO, FrpsServerDO.class);
        frpsServerMapper.updateById(updateObj);
    }

    @Override
    public void deleteFrpsServer(Long id) {
        // 校验存在
        validateFrpsServerExists(id);
        // 删除
        frpsServerMapper.deleteById(id);
    }

    private void validateFrpsServerExists(Long id) {
        if (frpsServerMapper.selectById(id) == null) {
            throw exception(FRPS_SERVER_NOT_EXISTS);
        }
    }

    @Override
    public FrpsServerDO getFrpsServer(Long id) {
        return frpsServerMapper.selectById(id);
    }

    @Override
    public PageResult<FrpsServerDO> getFrpsServerPage(FrpsServerPageReqVO pageReqVO) {
        return frpsServerMapper.selectPage(pageReqVO);
    }

}