package com.yc.ship.module.resource.service.baseprice;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.resource.controller.admin.baseprice.vo.ProductBasePricePageReqVO;
import com.yc.ship.module.resource.controller.admin.baseprice.vo.ProductBasePriceRespVO;
import com.yc.ship.module.resource.controller.admin.baseprice.vo.ProductBasePriceSaveReqVO;
import com.yc.ship.module.resource.dal.dataobject.baseprice.ProductBasePriceDO;
import com.yc.ship.module.resource.dal.mysql.baseprice.ProductBasePriceMapper;
import com.yc.ship.module.resource.enums.ErrorCodeConstants;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;


/**
 * 基础产品价格 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProductBasePriceServiceImpl implements ProductBasePriceService {

    @Resource
    private ProductBasePriceMapper basePriceMapper;

    @Override
    public Long createBasePrice(ProductBasePriceSaveReqVO createReqVO) {
        // 插入
        ProductBasePriceDO basePrice = BeanUtils.toBean(createReqVO, ProductBasePriceDO.class);
        Long id= IdWorker.getId(basePrice);
        basePrice.setId(id);
        basePrice.setDeleted(false);
        basePriceMapper.insert(basePrice);
        // 返回
        return basePrice.getId();
    }

    @Override
    public void updateBasePrice(ProductBasePriceSaveReqVO updateReqVO) {
        // 校验存在
        validateBasePriceExists(updateReqVO.getId());
        // 更新
        ProductBasePriceDO updateObj = BeanUtils.toBean(updateReqVO, ProductBasePriceDO.class);
        basePriceMapper.updateById(updateObj);
    }

    @Override
    public void deleteBasePrice(Long id) {
        // 校验存在
        validateBasePriceExists(id);
        // 删除
        basePriceMapper.deleteById(id);
    }

    @Override
    public void deleteByProductBaseId(Long baseId) {
        basePriceMapper.delete(ProductBasePriceDO::getProductBaseId, baseId);
    }

    private void validateBasePriceExists(Long id) {
        if (basePriceMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.BASE_PRICE_NOT_EXISTS);
        }
    }

    @Override
    public ProductBasePriceDO getBasePrice(Long id) {
        return basePriceMapper.selectById(id);
    }

    @Override
    public PageResult<ProductBasePriceDO> getBasePricePage(ProductBasePricePageReqVO pageReqVO) {
        return basePriceMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ProductBasePriceRespVO> queryPriceByBase(Long baseId) {
        return basePriceMapper.selectByBaseId(baseId);
    }
}