package com.jeesharp.business.modules.mall.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.convert.MallPromotionRuleConvert;
import com.jeesharp.business.modules.mall.dto.MallPromotionRuleSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallPromotionRule;
import com.jeesharp.business.modules.mall.service.MallPromotionRuleService;
import com.jeesharp.business.modules.mall.vo.MallPromotionRuleInfoVO;
import com.jeesharp.business.modules.mall.vo.MallPromotionRuleListVO;
import com.jeesharp.business.modules.mall.vo.MallPromotionRuleQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 满减/满赠规则 Application Service
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallPromotionRuleApplicationService {

    private final MallPromotionRuleService mallPromotionRuleService;

    public MallPromotionRuleInfoVO get(String id) {
        return MallPromotionRuleConvert.INSTANCE.toInfoVO(mallPromotionRuleService.get(id));
    }

    public PageRespVO<MallPromotionRuleListVO> findPage(Page<MallPromotionRule> page, MallPromotionRuleQueryVO query) {
        Page<MallPromotionRule> result = mallPromotionRuleService.findPage(page, query);
        return MallPromotionRuleConvert.INSTANCE.toPageRespVO(result);
    }

    @Transactional(readOnly = false)
    public void save(MallPromotionRuleSaveDTO dto) {
        MallPromotionRule entity = MallPromotionRuleConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            mallPromotionRuleService.createRule(entity);
            return;
        }
        mallPromotionRuleService.updateRule(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        mallPromotionRuleService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 获取可用的满减规则
     */
    public List<MallPromotionRule> getAvailableFullReductionRules() {
        return mallPromotionRuleService.getAvailableFullReductionRules();
    }

    /**
     * 获取可用的满赠规则
     */
    public List<MallPromotionRule> getAvailableFullGiftRules() {
        return mallPromotionRuleService.getAvailableFullGiftRules();
    }

    /**
     * 计算订单满减优惠
     */
    public BigDecimal calculateFullReductionDiscount(BigDecimal orderAmount) {
        return mallPromotionRuleService.calculateFullReductionDiscount(orderAmount);
    }

    /**
     * 获取订单可用的赠品
     */
    public List<MallPromotionRule> getAvailableGifts(BigDecimal orderAmount) {
        return mallPromotionRuleService.getAvailableGifts(orderAmount);
    }
}
