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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.iot.controller.admin.recipeplandetail.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.recipeplandetail.RecipePlanDetailDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.iot.dal.mysql.recipeplandetail.RecipePlanDetailMapper;

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 RecipePlanDetailServiceImpl implements RecipePlanDetailService {

    @Resource
    private RecipePlanDetailMapper recipePlanDetailMapper;

    @Override
    public Long createRecipePlanDetail(RecipePlanDetailSaveReqVO createReqVO) {
        // 校验编码是否存在
        validateCodeOnly(createReqVO.getCode());
        // 插入
        RecipePlanDetailDO recipePlanDetail = BeanUtils.toBean(createReqVO, RecipePlanDetailDO.class);
        recipePlanDetailMapper.insert(recipePlanDetail);
        // 返回
        return recipePlanDetail.getId();
    }
    private void validateCodeOnly(String code) {
        if (recipePlanDetailMapper.exists(Wrappers.<RecipePlanDetailDO>lambdaQuery()
                .eq(RecipePlanDetailDO::getCode, code))) {
            throw exception(RECIPE_PLAN_DETAIL_CODE_EXISTS);
        }
    }

    @Override
    public void updateRecipePlanDetail(RecipePlanDetailSaveReqVO updateReqVO) {
        // 校验存在
        validateRecipePlanDetailExists(updateReqVO.getId());
        // 更新
        RecipePlanDetailDO updateObj = BeanUtils.toBean(updateReqVO, RecipePlanDetailDO.class);
        recipePlanDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteRecipePlanDetail(Long id) {
        // 校验存在
        validateRecipePlanDetailExists(id);
        // 删除
        recipePlanDetailMapper.deleteById(id);
    }

    private void validateRecipePlanDetailExists(Long id) {
        if (recipePlanDetailMapper.selectById(id) == null) {
            throw exception(RECIPE_PLAN_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public RecipePlanDetailDO getRecipePlanDetail(Long id) {
        return recipePlanDetailMapper.selectById(id);
    }

    @Override
    public PageResult<RecipePlanDetailDO> getRecipePlanDetailPage(RecipePlanDetailPageReqVO pageReqVO) {
        return recipePlanDetailMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<RecipePlanDetailPageRespDTO> pageRecipePlanDetail(RecipePlanDetailPageReqVO reqVO) {
        // 直接调用Mapper的联表分页方法，无需手动拼接关联字段
        return recipePlanDetailMapper.selectPageWithRelationsWrap(reqVO);
    }

}