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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.bonus.core.marketing.v2.model.MarketRuleRecord;
import com.bonus.core.marketing.v2.rule.price.dto.RulePriceResultOrderDTO;
import com.bonus.core.marketing.v2.rule.price.handler.reductionfixed.dto.PriceReductionFixedDTO;
import com.bonus.core.marketing.v2.rule.price.handler.reductionfixed.extension.PriceReductionFixedHandlerExtension;
import com.bonus.core.marketing.v2.service.MarketRuleRecordService;
import com.bonus.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;

@Service
public class DefaultReductionFixedHandlerImpl implements PriceReductionFixedHandlerExtension {
   private static final Logger log = LoggerFactory.getLogger(DefaultReductionFixedHandlerImpl.class);
   @Autowired
   private MarketRuleRecordService recordService;

   public void handle(RulePriceResultOrderDTO order, MarketRuleVO rule, List<RulePriceResultOrderDTO> orderResults) {
      PriceReductionFixedDTO reductionFixedDTO = (PriceReductionFixedDTO)JSONObject.parseObject(rule.getRuleInfo(), PriceReductionFixedDTO.class);
      List<BigDecimal> items = reductionFixedDTO.getItems();
      List<MarketRuleRecord> records = this.recordService.getRuleRecordByRule(order.getCustId(), order.getOrderDate(), order.getOrderDate(), CollUtil.newArrayList(new Integer[]{order.getMealtimeType()}), CollUtil.newArrayList(new Long[]{rule.getRuleId()}));
      int count = records.size() + 1;
      BigDecimal reduceAmount = count >= items.size() ? (BigDecimal)CollUtil.getLast(items) : (BigDecimal)items.get(records.size());
      BigDecimal payableAmount = order.getPayableAmount();
      BigDecimal realAmount;
      BigDecimal discountAmount;
      if (payableAmount.compareTo(reduceAmount) <= 0) {
         realAmount = BigDecimal.ZERO;
         discountAmount = payableAmount;
      } else {
         realAmount = payableAmount.subtract(reduceAmount);
         discountAmount = reduceAmount;
      }

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