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

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.saleRuleVO.ProductSaleRulePageReqVO;
import com.yc.ship.module.product.controller.admin.productSpu.saleRuleVO.ProductSaleRuleSaveReqVO;
import com.yc.ship.module.product.dal.dataobject.productSaleRule.ProductSaleRuleDO;
import com.yc.ship.module.product.dal.mysql.productSaleRule.ProductSaleRuleMapper;
import com.yc.ship.module.resource.dal.redis.RedisKeyConstants;
import org.springframework.cache.annotation.Cacheable;
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.SALE_RULE_NOT_EXISTS;


/**
 * 产品销售规则 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductSaleRuleServiceImpl implements ProductSaleRuleService {

    @Resource
    private ProductSaleRuleMapper saleRuleMapper;

    @Override
    public Long createSaleRule(ProductSaleRuleSaveReqVO createReqVO) {
        // 插入
        ProductSaleRuleDO saleRule = BeanUtils.toBean(createReqVO, ProductSaleRuleDO.class);
        saleRuleMapper.insert(saleRule);
        // 返回
        return saleRule.getId();
    }

    @Override
    public void updateSaleRule(ProductSaleRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateSaleRuleExists(updateReqVO.getId());
        // 更新
        ProductSaleRuleDO updateObj = BeanUtils.toBean(updateReqVO, ProductSaleRuleDO.class);
        saleRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteSaleRule(Long id) {
        // 校验存在
        validateSaleRuleExists(id);
        // 删除
        saleRuleMapper.deleteById(id);
    }

    private void validateSaleRuleExists(Long id) {
        if (saleRuleMapper.selectById(id) == null) {
            throw exception(SALE_RULE_NOT_EXISTS);
        }
    }

    @Override
    @Cacheable(cacheNames = RedisKeyConstants.PRODUCT_SALE_RULE+"#60", key = "#id")
    public ProductSaleRuleDO getSaleRule(Long id) {
        return saleRuleMapper.selectById(id);
    }

    @Override
    public PageResult<ProductSaleRuleDO> getSaleRulePage(ProductSaleRulePageReqVO pageReqVO) {
        return saleRuleMapper.selectPage(pageReqVO);
    }

}