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

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.mqttrecord.vo.MqttRecordPageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.mqttrecord.vo.MqttRecordSaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.mqttrecord.MqttRecordDO;
import cn.iocoder.yudao.module.iot.dal.mysql.mqttrecord.MqttRecordMapper;
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.MQTT_RECORD_NOT_EXISTS;

/**
 * 数采记录 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class MqttRecordServiceImpl implements MqttRecordService {

    @Resource
    private MqttRecordMapper mqttRecordMapper;

    @Override
    public Long createMqttRecord(MqttRecordSaveReqVO createReqVO) {
        // 插入
        MqttRecordDO mqttRecord = BeanUtils.toBean(createReqVO, MqttRecordDO.class);
        mqttRecordMapper.insert(mqttRecord);
        // 返回
        return mqttRecord.getId();
    }

    @Override
    public void updateMqttRecord(MqttRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateMqttRecordExists(updateReqVO.getId());
        // 更新
        MqttRecordDO updateObj = BeanUtils.toBean(updateReqVO, MqttRecordDO.class);
        mqttRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteMqttRecord(Long id) {
        // 校验存在
        validateMqttRecordExists(id);
        // 删除
        mqttRecordMapper.deleteById(id);
    }

    private void validateMqttRecordExists(Long id) {
        if (mqttRecordMapper.selectById(id) == null) {
            throw exception(MQTT_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public MqttRecordDO getMqttRecord(Long id) {
        return mqttRecordMapper.selectById(id);
    }
    @Override
    public MqttRecordDO getDeviceAttr(String code) {
        return mqttRecordMapper.selectLastOne(code);
    }

    @Override
    public PageResult<MqttRecordDO> getMqttRecordPage(MqttRecordPageReqVO pageReqVO) {
        return mqttRecordMapper.selectPage(pageReqVO);
    }

}