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

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.baseRuleVO.ProductBasicRulePageReqVO;
import com.yc.ship.module.product.controller.admin.productSpu.baseRuleVO.ProductBasicRuleSaveReqVO;
import com.yc.ship.module.product.dal.dataobject.productBasicRule.ProductBasicRuleDO;
import com.yc.ship.module.product.dal.mysql.productBasicRule.ProductBasicRuleMapper;
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.BASIC_RULE_NOT_EXISTS;


/**
 * 产品基础规则 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductBasicRuleServiceImpl implements ProductBasicRuleService {

    @Resource
    private ProductBasicRuleMapper basicRuleMapper;

    @Override
    public Long createBasicRule(ProductBasicRuleSaveReqVO createReqVO) {
        // 插入
        ProductBasicRuleDO basicRule = BeanUtils.toBean(createReqVO, ProductBasicRuleDO.class);
        basicRuleMapper.insert(basicRule);
        // 返回
        return basicRule.getId();
    }

    @Override
    public void updateBasicRule(ProductBasicRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateBasicRuleExists(updateReqVO.getId());
        // 更新
        ProductBasicRuleDO updateObj = BeanUtils.toBean(updateReqVO, ProductBasicRuleDO.class);
        basicRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteBasicRule(Long id) {
        // 校验存在
        validateBasicRuleExists(id);
        // 删除
        basicRuleMapper.deleteById(id);
    }

    private void validateBasicRuleExists(Long id) {
        if (basicRuleMapper.selectById(id) == null) {
            throw exception(BASIC_RULE_NOT_EXISTS);
        }
    }

    @Override
    public ProductBasicRuleDO getBasicRule(Long id) {
        return basicRuleMapper.selectById(id);
    }

    @Override
    public PageResult<ProductBasicRuleDO> getBasicRulePage(ProductBasicRulePageReqVO pageReqVO) {
        return basicRuleMapper.selectPage(pageReqVO);
    }

}