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

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.formula.vo.FormulaRecordPageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.formula.vo.FormulaRecordSaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.formula.FormulaRecordDO;
import cn.iocoder.yudao.module.iot.dal.mysql.formula.FormulaRecordMapper;
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.FORMULA_RECORD_NOT_EXISTS;

/**
 * 变量记录 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class FormulaRecordServiceImpl implements FormulaRecordService {

    @Resource
    private FormulaRecordMapper formulaRecordMapper;

    @Override
    public Long createFormulaRecord(FormulaRecordSaveReqVO createReqVO) {
        // 插入
        FormulaRecordDO formulaRecord = BeanUtils.toBean(createReqVO, FormulaRecordDO.class);
        formulaRecordMapper.insert(formulaRecord);
        // 返回
        return formulaRecord.getId();
    }

    @Override
    public void updateFormulaRecord(FormulaRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateFormulaRecordExists(updateReqVO.getId());
        // 更新
        FormulaRecordDO updateObj = BeanUtils.toBean(updateReqVO, FormulaRecordDO.class);
        formulaRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteFormulaRecord(Long id) {
        // 校验存在
        validateFormulaRecordExists(id);
        // 删除
        formulaRecordMapper.deleteById(id);
    }

    private void validateFormulaRecordExists(Long id) {
        if (formulaRecordMapper.selectById(id) == null) {
            throw exception(FORMULA_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public FormulaRecordDO getFormulaRecord(Long id) {
        return formulaRecordMapper.selectById(id);
    }

    @Override
    public PageResult<FormulaRecordDO> getFormulaRecordPage(FormulaRecordPageReqVO pageReqVO) {
        return formulaRecordMapper.selectPage(pageReqVO);
    }

}