package cn.iocoder.yudao.module.pms.service.iotdeviceassociate;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceassociate.vo.IotDeviceAssociatePageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceassociate.vo.IotDeviceAssociateSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotdeviceassociate.IotDeviceAssociateDO;
import cn.iocoder.yudao.module.pms.dal.mysql.iotdeviceassociate.IotDeviceAssociateMapper;
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.pms.enums.ErrorCodeConstant.IOT_DEVICE_ASSOCIATE_NOT_EXISTS;

/**
 * 设备关联表(如：瑞都主要设备) Service 实现类
 *
 * @author ruiqi
 */
@Service
@Validated
public class IotDeviceAssociateServiceImpl implements IotDeviceAssociateService {

    @Resource
    private IotDeviceAssociateMapper iotDeviceAssociateMapper;

    @Override
    public Long createIotDeviceAssociate(IotDeviceAssociateSaveReqVO createReqVO) {
        // 插入
        IotDeviceAssociateDO iotDeviceAssociate = BeanUtils.toBean(createReqVO, IotDeviceAssociateDO.class);
        iotDeviceAssociateMapper.insert(iotDeviceAssociate);
        // 返回
        return iotDeviceAssociate.getId();
    }

    @Override
    public void updateIotDeviceAssociate(IotDeviceAssociateSaveReqVO updateReqVO) {
        // 校验存在
        validateIotDeviceAssociateExists(updateReqVO.getId());
        // 更新
        IotDeviceAssociateDO updateObj = BeanUtils.toBean(updateReqVO, IotDeviceAssociateDO.class);
        iotDeviceAssociateMapper.updateById(updateObj);
    }

    @Override
    public void deleteIotDeviceAssociate(Long id) {
        // 校验存在
        validateIotDeviceAssociateExists(id);
        // 删除
        iotDeviceAssociateMapper.deleteById(id);
    }

    private void validateIotDeviceAssociateExists(Long id) {
        if (iotDeviceAssociateMapper.selectById(id) == null) {
            throw exception(IOT_DEVICE_ASSOCIATE_NOT_EXISTS);
        }
    }

    @Override
    public IotDeviceAssociateDO getIotDeviceAssociate(Long id) {
        return iotDeviceAssociateMapper.selectById(id);
    }

    @Override
    public PageResult<IotDeviceAssociateDO> getIotDeviceAssociatePage(IotDeviceAssociatePageReqVO pageReqVO) {
        return iotDeviceAssociateMapper.selectPage(pageReqVO);
    }

}