package com.yc.ship.module.trade.service.shipSaleRule;

import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.yc.ship.module.trade.controller.admin.shipSaleRule.vo.ShipSaleRulePageReqVO;
import com.yc.ship.module.trade.controller.admin.shipSaleRule.vo.ShipSaleRuleSaveReqVO;
import com.yc.ship.module.trade.dal.dataobject.shipSaleRule.ShipSaleRuleDO;
import com.yc.ship.module.trade.dal.mysql.shipSaleRule.ShipSaleRuleMapper;
import lombok.extern.slf4j.Slf4j;
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;

/**
 * 时间规则配置 Service 实现类
 *
 * @author qsl
 */
@Slf4j
@Service
@Validated
public class ShipSaleRuleServiceImpl implements ShipSaleRuleService {

    @Resource
    private ShipSaleRuleMapper shipSaleRuleMapper;

    @Override
    public Long createShipSaleRule(ShipSaleRuleSaveReqVO createReqVO) {
        // 插入
        ShipSaleRuleDO shipSaleRule = BeanUtils.toBean(createReqVO, ShipSaleRuleDO.class);
        shipSaleRuleMapper.insert(shipSaleRule);
        // 返回
        return shipSaleRule.getId();
    }

    @Override
    public void updateShipSaleRule(ShipSaleRuleSaveReqVO updateReqVO) {
        if(updateReqVO.getId() == null){
            createShipSaleRule(updateReqVO);
            return;
        }
        // 校验存在
        validateShipSaleRuleExists(updateReqVO.getId());
        // 更新
        ShipSaleRuleDO updateObj = BeanUtils.toBean(updateReqVO, ShipSaleRuleDO.class);
        shipSaleRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteShipSaleRule(Long id) {
        // 校验存在
        validateShipSaleRuleExists(id);
        // 删除
        shipSaleRuleMapper.deleteById(id);
    }

    private void validateShipSaleRuleExists(Long id) {
        if (shipSaleRuleMapper.selectById(id) == null) {
            throw exception(500,"不存在");
        }
    }

    @Override
    public ShipSaleRuleDO getShipSaleRule(Long id) {
        return shipSaleRuleMapper.selectById(id);
    }

    @Override
    public ShipSaleRuleDO getShipSaleRuleOne() {
        return shipSaleRuleMapper.selectOne(new LambdaQueryWrapperX<ShipSaleRuleDO>().eq(ShipSaleRuleDO::getDeleted, false).last("limit 1"));
    }

    @Override
    public PageResult<ShipSaleRuleDO> getShipSaleRulePage(ShipSaleRulePageReqVO pageReqVO) {
        return shipSaleRuleMapper.selectPage(pageReqVO);
    }

}