package com.bonus.core.marketing.v2.rule.recharge.handler.sumamount.extension.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.core.account.v3.api.AccTradeApi;
import com.bonus.core.account.v3.api.dto.AccRechargeSumApiDTO;
import com.bonus.core.account.v3.api.vo.AccRechargeSumApiVO;
import com.bonus.core.marketing.v2.constants.MarketRangeTypeEnum;
import com.bonus.core.marketing.v2.model.MarketRuleRange;
import com.bonus.core.marketing.v2.rule.recharge.constants.RuleRechargeSumEnum;
import com.bonus.core.marketing.v2.rule.recharge.dto.RuleRechargeResultDTO;
import com.bonus.core.marketing.v2.rule.recharge.handler.sumamount.dto.RechargeSumAmountDTO;
import com.bonus.core.marketing.v2.rule.recharge.handler.sumamount.extension.RechargeSumAmountHandlerExtension;
import com.bonus.core.marketing.v2.service.MarketRuleRangeService;
import com.bonus.core.marketing.vo.MarketRuleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Service
public class DefaultRechargeSumAmountHandlerImpl implements RechargeSumAmountHandlerExtension {
    private static final Logger log = LoggerFactory.getLogger(DefaultRechargeSumAmountHandlerImpl.class);
    @Resource
    private AccTradeApi accTradeApi;
    @Resource
    private MarketRuleRangeService rangeService;

    @Override
    public void handle(RuleRechargeResultDTO resultDTO, MarketRuleVO rule) {
        RechargeSumAmountDTO ruleInfo = (RechargeSumAmountDTO) JSONObject.parseObject(rule.getRuleInfo(), RechargeSumAmountDTO.class);
        List<MarketRuleRange> rangeList = this.rangeService.getRangeByRuleId(rule.getRuleId());
        List<Integer> payChannelList = this.rangeService.filterRangeDetailByType(rangeList, MarketRangeTypeEnum.RANGE_PAY_CHANNEL);
        AccRechargeSumApiDTO sumApiDTO = RuleRechargeSumEnum.getSumParam(ruleInfo.getSumType(), payChannelList, resultDTO);
        AccRechargeSumApiVO accRechargeSum = this.accTradeApi.getAccRechargeSum(sumApiDTO);
        if (!Objects.isNull(accRechargeSum)) {
            BigDecimal totalAmount = accRechargeSum.getSumAmount().add(resultDTO.getAmount());
            Assert.isTrue(totalAmount.compareTo(ruleInfo.getMaxAmount()) <= 0, () -> {
                log.error("累计充值金额已达到上限");
                return new ServiceException("累计充值金额已达到上限");
            });
        }
    }
}
