package com.yc.ship.module.product.service.productNoticeRule;

import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.product.controller.admin.productSpu.noticeRuleVO.ProductNoticeRulePageReqVO;
import com.yc.ship.module.product.controller.admin.productSpu.noticeRuleVO.ProductNoticeRuleSaveReqVO;
import com.yc.ship.module.product.dal.dataobject.productNoticeRule.ProductNoticeRuleDO;
import com.yc.ship.module.product.dal.mysql.productNoticeRule.ProductNoticeRuleMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.product.enums.ErrorCodeConstants.NOTICE_RULE_NOT_EXISTS;


/**
 * 产品通知规则 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductNoticeRuleServiceImpl implements ProductNoticeRuleService {

    @Resource
    private ProductNoticeRuleMapper noticeRuleMapper;

    @Override
    public Long createNoticeRule(ProductNoticeRuleSaveReqVO createReqVO) {
        // 插入
        ProductNoticeRuleDO noticeRule = BeanUtils.toBean(createReqVO, ProductNoticeRuleDO.class);
        noticeRuleMapper.insert(noticeRule);
        // 返回
        return noticeRule.getId();
    }

    @Override
    public void updateNoticeRule(ProductNoticeRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateNoticeRuleExists(updateReqVO.getId());
        // 更新
        ProductNoticeRuleDO updateObj = BeanUtils.toBean(updateReqVO, ProductNoticeRuleDO.class);
        noticeRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteNoticeRule(Long id) {
        // 校验存在
        validateNoticeRuleExists(id);
        // 删除
        noticeRuleMapper.deleteById(id);
    }

    private void validateNoticeRuleExists(Long id) {
        if (noticeRuleMapper.selectById(id) == null) {
            throw exception(NOTICE_RULE_NOT_EXISTS);
        }
    }

    @Override
    public ProductNoticeRuleDO getNoticeRule(Long id) {
        return noticeRuleMapper.selectById(id);
    }

    @Override
    public PageResult<ProductNoticeRuleDO> getNoticeRulePage(ProductNoticeRulePageReqVO pageReqVO) {
        return noticeRuleMapper.selectPage(pageReqVO);
    }

}