package com.bonus.core.marketing.v2.rule.price.handler.deductionfixed.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.deductionfixed.dto.PriceDeductionFixedDTO;
import com.bonus.core.marketing.v2.rule.price.handler.deductionfixed.dto.PriceDeductionFixedItemDTO;
import com.bonus.core.marketing.v2.rule.price.handler.deductionfixed.extension.PriceDeductionFixedHandlerExtension;
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;
import java.util.Objects;

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

   public void handle(RulePriceResultOrderDTO order, MarketRuleVO rule, List<RulePriceResultOrderDTO> orderResults) {
      PriceDeductionFixedDTO fixedDTO = (PriceDeductionFixedDTO)JSONObject.parseObject(rule.getRuleInfo(), PriceDeductionFixedDTO.class);
      PriceDeductionFixedItemDTO item = this.getItem(order, fixedDTO.getItems(), rule);
      BigDecimal discount = Objects.isNull(item.getDiscount()) ? BigDecimal.ZERO : item.getDiscount();
      BigDecimal amount = Objects.isNull(item.getDoorAmount()) ? order.getPayableAmount() : item.getDoorAmount();
      BigDecimal realAmount = discount.compareTo(amount) >= 0 ? BigDecimal.ZERO : amount.subtract(discount);
      order.setRealAmount(realAmount);
      order.setDiscountsAmount(order.getPayableAmount().subtract(realAmount));
   }

   protected PriceDeductionFixedItemDTO getItem(RulePriceResultOrderDTO order, List<PriceDeductionFixedItemDTO> items, MarketRuleVO rule) {
      if (CollUtil.isEmpty(items)) {
         return new PriceDeductionFixedItemDTO(order.getPayableAmount(), BigDecimal.ZERO);
      } else {
         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;
         return count >= items.size() ? (PriceDeductionFixedItemDTO)CollUtil.getLast(items) : (PriceDeductionFixedItemDTO)items.get(records.size());
      }
   }
}
