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

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.productTakeRule.vo.ProductTakeRulePageReqVO;
import com.yc.ship.module.product.controller.admin.productTakeRule.vo.ProductTakeRuleSaveReqVO;
import com.yc.ship.module.product.dal.dataobject.productTakeRule.ProductTakeRuleDO;
import com.yc.ship.module.product.dal.mysql.productTakeRule.ProductTakeRuleMapper;
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.TAKE_RULE_NOT_EXISTS;


/**
 * 产品取票规则 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductTakeRuleServiceImpl implements ProductTakeRuleService {

    @Resource
    private ProductTakeRuleMapper takeRuleMapper;

    @Override
    public Long createTakeRule(ProductTakeRuleSaveReqVO createReqVO) {
        // 插入
        ProductTakeRuleDO takeRule = BeanUtils.toBean(createReqVO, ProductTakeRuleDO.class);
        takeRuleMapper.insert(takeRule);
        // 返回
        return takeRule.getId();
    }

    @Override
    public void updateTakeRule(ProductTakeRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateTakeRuleExists(updateReqVO.getId());
        // 更新
        ProductTakeRuleDO updateObj = BeanUtils.toBean(updateReqVO, ProductTakeRuleDO.class);
        takeRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteTakeRule(Long id) {
        // 校验存在
        validateTakeRuleExists(id);
        // 删除
        takeRuleMapper.deleteById(id);
    }

    private void validateTakeRuleExists(Long id) {
        if (takeRuleMapper.selectById(id) == null) {
            throw exception(TAKE_RULE_NOT_EXISTS);
        }
    }

    @Override
    public ProductTakeRuleDO getTakeRule(Long id) {
        return takeRuleMapper.selectById(id);
    }

    @Override
    public PageResult<ProductTakeRuleDO> getTakeRulePage(ProductTakeRulePageReqVO pageReqVO) {
        return takeRuleMapper.selectPage(pageReqVO);
    }

}