package com.neusoft.smart.pos.promotion.service;

import com.neusoft.smart.pos.promotion.persistent.domain.PromotionPayChannel;
import com.neusoft.smart.pos.promotion.persistent.ext.domain.PromotionPayChannelQuery;
import com.neusoft.smart.pos.promotion.persistent.repository.PromotionPayChannelRepository;
import com.neusoft.smart.pos.dto.promotion.bean.CalculateBean;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.RoundingMode;

/**
 * 支付渠道营销
 */
@Service
public class PaymentPromotionCalculate implements IPromotionCalculate {
    
    @Autowired
    private PromotionPayChannelRepository promotionPayChannelRepository;
    
    @Override
    public CalculateBean calculatePrice(CalculateBean calculateBean) {
        //h5的微信扫码,没有支付方式,略过此处逻辑
        if (StringUtils.isEmpty(calculateBean.getPayType())) {
            return calculateBean;
        }
        val promotionPayChannelQuery = new PromotionPayChannelQuery();
        promotionPayChannelQuery.setIsPage(false);
        promotionPayChannelQuery.setIsFilteredByRole(false);
        promotionPayChannelQuery.setOrgId(calculateBean.getOrgId());
        //门店结算
        if ("2".equals(calculateBean.getSettlementType())) {
            promotionPayChannelQuery.setStoreId(calculateBean.getShopId());
        } else {
            promotionPayChannelQuery.setStoreId(0);
        }
        promotionPayChannelQuery.setPayChannel(Integer.parseInt(calculateBean.getPayType()));
        val promotionPayChannelList = promotionPayChannelRepository.getList(promotionPayChannelQuery);
        if (!promotionPayChannelList.isEmpty()) {
            PromotionPayChannel promotionPayChannel = promotionPayChannelList.get(0);
            switch (promotionPayChannel.getOffType()) {
                // 0: 折扣
                case 0:
                    calculateBean.setActualPrice(calculateBean.getActualPrice().multiply(promotionPayChannel.getDiscount()).setScale(2, RoundingMode.UP));
                    //根据折扣,计算每件商品的实际价格
                    if (null != calculateBean.getOrderItems()) {
                        calculateBean.getOrderPreferentialItems().forEach(item ->
                                item.setPreferentialUnitPrice(item.getUnitPrice().multiply(promotionPayChannel.getDiscount()).setScale(2, RoundingMode.UP)));
                    }
                    break;
                //1:满减
                case 1:
                    //TODO
                    break;
                // 2:每满减
                case 2:
                    //TODO
                    break;
                //3:满折扣
                case 3:
                    //TODO
                    break;
            }
        }
        return calculateBean;
    }
    
}
