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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.convert.MallGiftRuleConvert;
import com.jeesharp.business.modules.mall.dto.MallGiftRuleSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallGiftRule;
import com.jeesharp.business.modules.mall.service.MallGiftRuleService;
import com.jeesharp.business.modules.mall.vo.MallGiftRuleInfoVO;
import com.jeesharp.business.modules.mall.vo.MallGiftRuleListVO;
import com.jeesharp.business.modules.mall.vo.MallGiftRuleQueryVO;
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.util.List;
import java.util.Map;

/**
 * 赠品规则 Application Service
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallGiftRuleApplicationService {

    private final MallGiftRuleService mallGiftRuleService;

    public MallGiftRuleInfoVO get(String id) {
        return MallGiftRuleConvert.INSTANCE.toInfoVO(mallGiftRuleService.get(id));
    }

    public PageRespVO<MallGiftRuleListVO> findPage(Page<MallGiftRule> page, MallGiftRuleQueryVO query) {
        Page<MallGiftRule> result = mallGiftRuleService.findPage(page, query);
        return MallGiftRuleConvert.INSTANCE.toPageRespVO(result);
    }

    @Transactional(readOnly = false)
    public void save(MallGiftRuleSaveDTO dto) {
        MallGiftRule entity = MallGiftRuleConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            mallGiftRuleService.createRule(entity);
            return;
        }
        mallGiftRuleService.updateRule(entity);
    }

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

    /**
     * 获取可用的赠品规则
     */
    public List<MallGiftRule> getAvailableGiftRules() {
        return mallGiftRuleService.getAvailableGiftRules();
    }

    /**
     * 根据SKU ID获取可用的赠品规则
     */
    public List<MallGiftRule> getGiftRulesBySku(String skuId) {
        return mallGiftRuleService.getGiftRulesBySku(skuId);
    }

    /**
     * 检查订单是否满足满件赠条件
     */
    public List<MallGiftRule> checkFullItemGifts(Map<String, Integer> skuQuantities) {
        return mallGiftRuleService.checkFullItemGifts(skuQuantities);
    }
}
