package com.bonus.canteen.core.marketing.v2.rule.price.handler.reductiontotal.extension.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.bonus.canteen.core.marketing.v2.constants.MarketModuleTypeEnum;
import com.bonus.canteen.core.marketing.v2.model.MarketRule;
import com.bonus.canteen.core.marketing.v2.model.MarketRuleRecord;
import com.bonus.canteen.core.marketing.v2.rule.price.dto.RulePriceResultOrderDTO;
import com.bonus.canteen.core.marketing.v2.rule.price.handler.reductiontotal.dto.PriceReductionTotalDTO;
import com.bonus.canteen.core.marketing.v2.rule.price.handler.reductiontotal.extension.PriceReductionTotalHandlerExtension;
import com.bonus.canteen.core.marketing.v2.service.MarketRuleRecordService;
import com.bonus.canteen.core.marketing.v2.service.MarketRuleService;
import com.bonus.canteen.core.marketing.vo.MarketRuleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class DefaultReductionTotalHandlerImpl implements PriceReductionTotalHandlerExtension {
   private static final Logger log = LoggerFactory.getLogger(DefaultReductionTotalHandlerImpl.class);
   @Autowired
   private MarketRuleRecordService recordService;
   @Autowired
   private MarketRuleService ruleService;

   public void handle(RulePriceResultOrderDTO order, MarketRuleVO rule, List<RulePriceResultOrderDTO> orderResults) {
      PriceReductionTotalDTO reductionTotalDTO = (PriceReductionTotalDTO)JSONObject.parseObject(rule.getRuleInfo(), PriceReductionTotalDTO.class);
      List<MarketRule> rules = this.ruleService.listRuleByType(MarketModuleTypeEnum.RULE_PRICE.getKey(), rule.getRuleType());
      List<Long> ruleIds = (List)rules.stream().map(MarketRule::getRuleId).collect(Collectors.toList());
      List<MarketRuleRecord> records = this.recordService.getRuleRecordByRule(order.getCustId(), order.getOrderDate(), order.getOrderDate(), CollUtil.newArrayList(new Integer[]{order.getMealtimeType()}), ruleIds);
      BigDecimal totalReduceAmount = (BigDecimal)records.stream().map(MarketRuleRecord::getDiscountsAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
      BigDecimal remainReduceAmount = reductionTotalDTO.getReduceAmount().compareTo(totalReduceAmount) <= 0 ? BigDecimal.ZERO : reductionTotalDTO.getReduceAmount().subtract(totalReduceAmount);
      BigDecimal amount = order.getPayableAmount();
      BigDecimal discountAmount;
      BigDecimal realAmount;
      if (amount.compareTo(remainReduceAmount) <= 0) {
         realAmount = BigDecimal.ZERO;
         discountAmount = amount;
      } else {
         realAmount = amount.subtract(remainReduceAmount);
         discountAmount = remainReduceAmount;
      }

      order.setRealAmount(realAmount);
      order.setDiscountsAmount(discountAmount);
   }
}
