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

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.iot.controller.admin.devicemodelrules.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.devicemodelrules.DeviceModelRulesDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.iot.dal.mysql.devicemodelrules.DeviceModelRulesMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.*;

/**
 * 点位规则关联模型 Service 实现类
 *
 * @author 必硕科技
 */
@Service
@Validated
public class DeviceModelRulesServiceImpl implements DeviceModelRulesService {

    @Resource
    private DeviceModelRulesMapper deviceModelRulesMapper;

    @Override
    public Long createDeviceModelRules(DeviceModelRulesSaveReqVO createReqVO) {
        // 插入
        DeviceModelRulesDO deviceModelRules = BeanUtils.toBean(createReqVO, DeviceModelRulesDO.class);
        deviceModelRulesMapper.insert(deviceModelRules);
        // 返回
        return deviceModelRules.getId();
    }

    @Override
    public void updateDeviceModelRules(DeviceModelRulesSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceModelRulesExists(updateReqVO.getId());
        // 更新
        DeviceModelRulesDO updateObj = BeanUtils.toBean(updateReqVO, DeviceModelRulesDO.class);
        if (!updateReqVO.getPointRulesVOList().isEmpty()){
            String jsonString = JSON.toJSONString(updateReqVO.getPointRulesVOList());
            updateObj.setFieldRule(jsonString);

        }

        deviceModelRulesMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceModelRules(Long id) {
        // 校验存在
        validateDeviceModelRulesExists(id);
        // 删除
        deviceModelRulesMapper.deleteById(id);
    }

    private void validateDeviceModelRulesExists(Long id) {
        if (deviceModelRulesMapper.selectById(id) == null) {
            throw exception(DEVICE_MODEL_RULES_NOT_EXISTS);
        }
    }

    @Override
    public DeviceModelRulesDO getDeviceModelRules(Long id) {
        return deviceModelRulesMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceModelRulesDO> getDeviceModelRulesPage(DeviceModelRulesPageReqVO pageReqVO) {
        return deviceModelRulesMapper.selectPage(pageReqVO);
    }

}