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

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
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.ly.vo.LyDevicePageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.ly.vo.LyDeviceSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.ly.LyDeviceDO;
import cn.iocoder.yudao.module.pms.dal.mysql.IotDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.ly.LyDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * 连油设备信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class LyDeviceServiceImpl implements LyDeviceService {

    @Resource
    private LyDeviceMapper lyDeviceMapper;
    @Autowired
    private IotDeviceMapper iotDeviceMapper;

    @Override
    public Long createLyDevice(LyDeviceSaveReqVO createReqVO) {
        // 插入
        LyDeviceDO lyDevice = BeanUtils.toBean(createReqVO, LyDeviceDO.class);
        lyDevice.setDeleted(false);
        lyDeviceMapper.insert(lyDevice);
        // 返回
        return lyDevice.getId();
    }

    @Override
    public void updateLyDevice(LyDeviceSaveReqVO updateReqVO) {
        // 校验存在
        validateLyDeviceExists(updateReqVO.getId());
        // 更新
        LyDeviceDO updateObj = BeanUtils.toBean(updateReqVO, LyDeviceDO.class);
        lyDeviceMapper.updateById(updateObj);
    }

    @Override
    public void deleteLyDevice(Long id) {
        // 校验存在
        validateLyDeviceExists(id);
        // 删除
        lyDeviceMapper.deleteById(id);
    }

    private void validateLyDeviceExists(Long id) {
        if (lyDeviceMapper.selectById(id) == null) {
            throw exception(new ErrorCode(1, "不存在"));
        }
    }

    @Override
    public LyDeviceDO getLyDevice(Long id) {
        return lyDeviceMapper.selectById(id);
    }

    @Override
    public PageResult<LyDeviceDO> getLyDevicePage(LyDevicePageReqVO pageReqVO) {
        return lyDeviceMapper.selectPage(pageReqVO);
    }

}