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

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.skuVO.ProductSkuPageReqVO;
import com.yc.ship.module.product.controller.admin.productSpu.skuVO.ProductSkuSaveReqVO;
import com.yc.ship.module.product.dal.dataobject.productSku.ProductSkuDO;
import com.yc.ship.module.product.dal.mysql.productSku.ProductSkuMapper;
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.SKU_NOT_EXISTS;


/**
 * 产品sku Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductSkuServiceImpl implements ProductSkuService {

    @Resource
    private ProductSkuMapper skuMapper;

    @Override
    public Long createSku(ProductSkuSaveReqVO createReqVO) {
        // 插入
        ProductSkuDO sku = BeanUtils.toBean(createReqVO, ProductSkuDO.class);
        skuMapper.insert(sku);
        // 返回
        return sku.getId();
    }

    @Override
    public void updateSku(ProductSkuSaveReqVO updateReqVO) {
        // 校验存在
        validateSkuExists(updateReqVO.getId());
        // 更新
        ProductSkuDO updateObj = BeanUtils.toBean(updateReqVO, ProductSkuDO.class);
        skuMapper.updateById(updateObj);
    }

    @Override
    public void deleteSku(Long id) {
        // 校验存在
        validateSkuExists(id);
        // 删除
        skuMapper.deleteById(id);
    }

    private void validateSkuExists(Long id) {
        if (skuMapper.selectById(id) == null) {
            throw exception(SKU_NOT_EXISTS);
        }
    }

    @Override
    public ProductSkuDO getSku(Long id) {
        return skuMapper.selectById(id);
    }

    @Override
    public PageResult<ProductSkuDO> getSkuPage(ProductSkuPageReqVO pageReqVO) {
        return skuMapper.selectPage(pageReqVO);
    }

}