package cn.newfeifan.mall.module.distri.service.ordersettlement;

import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;
import cn.newfeifan.mall.module.distri.controller.admin.ordersettlement.vo.OrderSettlementPageReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.ordersettlement.vo.OrderSettlementSaveReqVO;
import cn.newfeifan.mall.module.distri.dal.dataobject.ordersettlement.OrderSettlementDO;
import cn.newfeifan.mall.module.distri.dal.mysql.ordersettlement.OrderSettlementMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.distri.enums.ErrorCodeConstants.ORDER_SETTLEMENT_NOT_EXISTS;

/**
 * 订单结算表,记录有那些订单参与了本次结算 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class OrderSettlementServiceImpl implements OrderSettlementService {

    @Resource
    private OrderSettlementMapper orderSettlementMapper;

    @Override
    public Long createOrderSettlement(OrderSettlementSaveReqVO createReqVO) {
        // 插入
        OrderSettlementDO orderSettlement = BeanUtils.toBean(createReqVO, OrderSettlementDO.class);
        orderSettlementMapper.insert(orderSettlement);
        // 返回
        return orderSettlement.getId();
    }

    @Override
    public void updateOrderSettlement(OrderSettlementSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderSettlementExists(updateReqVO.getId());
        // 更新
        OrderSettlementDO updateObj = BeanUtils.toBean(updateReqVO, OrderSettlementDO.class);
        orderSettlementMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderSettlement(Long id) {
        // 校验存在
        validateOrderSettlementExists(id);
        // 删除
        orderSettlementMapper.deleteById(id);
    }

    private void validateOrderSettlementExists(Long id) {
        if (orderSettlementMapper.selectById(id) == null) {
            throw exception(ORDER_SETTLEMENT_NOT_EXISTS);
        }
    }

    @Override
    public OrderSettlementDO getOrderSettlement(Long id) {
        return orderSettlementMapper.selectById(id);
    }

    @Override
    public PageResult<OrderSettlementDO> getOrderSettlementPage(OrderSettlementPageReqVO pageReqVO) {
        return orderSettlementMapper.selectPage(pageReqVO);
    }

}