package cn.iocoder.yudao.module.system.service.biz;

/**
 * @Author: jinyd
 * @CreateTime: 2024/8/19  11:42
 * @Description:
 * @Version: 4.0
 */


import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.DeviceModelPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.DeviceModelSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ModelFieldPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ModelFieldSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.DeviceModelDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ModelFieldDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.DeviceModelMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ModelFieldMapper;
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.system.enums.ErrorCodeConstants.DEVICE_MODEL_FIELD_NOT_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.DEVICE_MODEL_NOT_EXISTS;

@Service
@Validated
public class ModelFieldServiceImpl implements ModelFieldService {

    @Resource
    private ModelFieldMapper modelFieldMapper;

    @Override
    public Long createModelField(ModelFieldSaveReqVO createReqVO) {
        // 插入
        ModelFieldDO modelField = BeanUtils.toBean(createReqVO, ModelFieldDO.class);
        modelFieldMapper.insert(modelField);
        // 返回
        return modelField.getId();
    }

    @Override
    public void updateModelField(ModelFieldSaveReqVO updateReqVO) {
        // 校验存在
        validateModelFieldExists(updateReqVO.getId());
        // 更新
        ModelFieldDO updateObj = BeanUtils.toBean(updateReqVO, ModelFieldDO.class);
        modelFieldMapper.updateById(updateObj);
    }

    @Override
    public void deleteModelField(Long id) {
        // 校验存在
        validateModelFieldExists(id);
        // 删除
        modelFieldMapper.deleteById(id);
    }

    private void validateModelFieldExists(Long id) {
        if (modelFieldMapper.selectById(id) == null) {
            throw exception(DEVICE_MODEL_FIELD_NOT_EXISTS);
        }
    }

    @Override
    public ModelFieldDO getModelField(Long id) {
        return modelFieldMapper.selectById(id);
    }

    @Override
    public PageResult<ModelFieldDO> getModelFieldPage(ModelFieldPageReqVO pageReqVO) {
        return modelFieldMapper.selectPage(pageReqVO);
    }

}
