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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.recipepointrecord.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.recipepointrecord.RecipePointRecordDO;
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.recipepointrecord.RecipePointRecordMapper;

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

/**
 * IoT配方点位记录 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class RecipePointRecordServiceImpl implements RecipePointRecordService {

    @Resource
    private RecipePointRecordMapper recipePointRecordMapper;

    @Override
    public Long createRecipePointRecord(RecipePointRecordSaveReqVO createReqVO) {
        List<RecipePointRecordDO> recipePointRecordDOS = recipePointRecordMapper.selectList(Wrappers.<RecipePointRecordDO>lambdaQuery().eq(RecipePointRecordDO::getRecipeId, createReqVO.getRecipeId()));
        if (!recipePointRecordDOS.isEmpty()){
            recipePointRecordMapper.deleteByIds(recipePointRecordDOS);
        }

        // 插入
        RecipePointRecordDO recipePointRecord = BeanUtils.toBean(createReqVO, RecipePointRecordDO.class);
        recipePointRecordMapper.insert(recipePointRecord);
        // 返回
        return recipePointRecord.getId();
    }

    @Override
    public void updateRecipePointRecord(RecipePointRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateRecipePointRecordExists(updateReqVO.getId());
        // 更新
        RecipePointRecordDO updateObj = BeanUtils.toBean(updateReqVO, RecipePointRecordDO.class);
        recipePointRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteRecipePointRecord(Long id) {
        // 校验存在
        validateRecipePointRecordExists(id);
        // 删除
        recipePointRecordMapper.deleteById(id);
    }

    private void validateRecipePointRecordExists(Long id) {
        if (recipePointRecordMapper.selectById(id) == null) {
            throw exception(RECIPE_POINT_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public RecipePointRecordDO getRecipePointRecord(Long id) {
        return recipePointRecordMapper.selectById(id);
    }

    @Override
    public PageResult<RecipePointRecordDO> getRecipePointRecordPage(RecipePointRecordPageReqVO pageReqVO) {
        return recipePointRecordMapper.selectPage(pageReqVO);
    }

}