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

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.refundRuleVO.ProductRefundRulePageReqVO;
import com.yc.ship.module.product.controller.admin.productSpu.refundRuleVO.ProductRefundRuleSaveReqVO;
import com.yc.ship.module.product.dal.dataobject.productRefundRule.ProductRefundRuleDO;
import com.yc.ship.module.product.dal.mysql.productRefundRule.ProductRefundRuleMapper;
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.REFUND_RULE_NOT_EXISTS;


/**
 * 产品退款规则 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductRefundRuleServiceImpl implements ProductRefundRuleService {

    @Resource
    private ProductRefundRuleMapper refundRuleMapper;

    @Override
    public Long createRefundRule(ProductRefundRuleSaveReqVO createReqVO) {
        // 插入
        ProductRefundRuleDO refundRule = BeanUtils.toBean(createReqVO, ProductRefundRuleDO.class);
        refundRuleMapper.insert(refundRule);
        // 返回
        return refundRule.getId();
    }

    @Override
    public void updateRefundRule(ProductRefundRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateRefundRuleExists(updateReqVO.getId());
        // 更新
        ProductRefundRuleDO updateObj = BeanUtils.toBean(updateReqVO, ProductRefundRuleDO.class);
        refundRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteRefundRule(Long id) {
        // 校验存在
        validateRefundRuleExists(id);
        // 删除
        refundRuleMapper.deleteById(id);
    }

    private void validateRefundRuleExists(Long id) {
        if (refundRuleMapper.selectById(id) == null) {
            throw exception(REFUND_RULE_NOT_EXISTS);
        }
    }

    @Override
    public ProductRefundRuleDO getRefundRule(Long id) {
        return refundRuleMapper.selectById(id);
    }

    @Override
    public PageResult<ProductRefundRuleDO> getRefundRulePage(ProductRefundRulePageReqVO pageReqVO) {
        return refundRuleMapper.selectPage(pageReqVO);
    }

}