package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.controller.vo.DeviceConnetRulePageReqVO;
import cn.gintone.controller.vo.DeviceConnetRuleSaveReqVO;
import cn.gintone.dal.DeviceConnetRuleInfoMapper;
import cn.gintone.dal.DeviceConnetRuleMapper;
import cn.gintone.entity.DeviceConnetRuleDO;
import cn.gintone.entity.DeviceConnetRuleInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

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

/**
 * 设备连接规则 Service 实现类
 *
 * @author 胡懿
 */
@Service
@Validated
public class DeviceConnetRuleServiceImpl implements DeviceConnetRuleService {

    @Resource
    private DeviceConnetRuleMapper connetRuleMapper;
    @Resource
    private DeviceConnetRuleInfoMapper connetRuleInfoMapper;

    @Override
    public Long createConnetRule(DeviceConnetRuleSaveReqVO createReqVO) {
        // 插入
        DeviceConnetRuleDO connetRule = BeanUtils.toBean(createReqVO, DeviceConnetRuleDO.class);
        connetRuleMapper.insert(connetRule);
        // 返回
        return connetRule.getId();
    }

    @Override
    public void updateConnetRule(DeviceConnetRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateConnetRuleExists(updateReqVO.getId());
        // 更新
        DeviceConnetRuleDO updateObj = BeanUtils.toBean(updateReqVO, DeviceConnetRuleDO.class);
        connetRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteConnetRule(Long id) {
        // 校验存在
        validateConnetRuleExists(id);
        // 删除
        connetRuleMapper.deleteById(id);
        connetRuleInfoMapper.delete(new QueryWrapper<DeviceConnetRuleInfoDO>().lambda().eq(DeviceConnetRuleInfoDO::getDeviceRuleId, id));
    }

    private void validateConnetRuleExists(Long id) {
        if (connetRuleMapper.selectById(id) == null) {
            throw exception(ErrorInfo.CONNET_RULE_NOT_EXISTS);
        }
    }

    @Override
    public DeviceConnetRuleDO getConnetRule(Long id) {
        return connetRuleMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceConnetRuleDO> getConnetRulePage(DeviceConnetRulePageReqVO pageReqVO) {
        return connetRuleMapper.selectPage(pageReqVO);
    }

}