package cn.iocoder.yudao.module.system.service.discount;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.discount.vo.DiscountRulePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.discount.vo.DiscountRuleSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.discount.DiscountRuleDO;
import cn.iocoder.yudao.module.system.dal.mysql.discount.DiscountRuleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.DISCOUNT_RULE_NOT_EXISTS;


/**
 * 长者优惠规则 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class DiscountRuleServiceImpl implements DiscountRuleService {

    @Resource
    private DiscountRuleMapper discountRuleMapper;

    @Override
    public void createDiscountRule(@Valid List<DiscountRuleSaveReqVO> createReqVO) {
        for (DiscountRuleSaveReqVO discountRuleSaveReqVO : createReqVO) {
            // 插入
            DiscountRuleDO discountRule = BeanUtils.toBean(discountRuleSaveReqVO, DiscountRuleDO.class);
            discountRuleMapper.insert(discountRule);
        }
    }

    @Override
    public void updateDiscountRule(@Valid DiscountRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateDiscountRuleExists(updateReqVO.getId());
        // 更新
        DiscountRuleDO updateObj = BeanUtils.toBean(updateReqVO, DiscountRuleDO.class);
        discountRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteDiscountRule(Long id) {
        // 校验存在
        validateDiscountRuleExists(id);
        // 删除
        discountRuleMapper.deleteById(id);
    }

    private void validateDiscountRuleExists(Long id) {
        if (discountRuleMapper.selectById(id) == null) {
            throw exception(DISCOUNT_RULE_NOT_EXISTS);
        }
    }

    @Override
    public DiscountRuleDO getDiscountRule(Long id) {
        return discountRuleMapper.selectById(id);
    }

    @Override
    public PageResult<DiscountRuleDO> getDiscountRulePage(DiscountRulePageReqVO pageReqVO) {
        return discountRuleMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DiscountRuleDO> getDiscountRuleList(List<Long> ids) {
        return discountRuleMapper.selectBatchIds(ids);
    }

    @Override
    public List<DiscountRuleDO> getDiscountRuleListByElderId(Long elderId) {
        return discountRuleMapper.selectList(new LambdaQueryWrapperX<DiscountRuleDO>()
                .eq(DiscountRuleDO::getElderId, elderId));
    }

}