package com.caimei.www.service;

import com.caimei.www.mapper.CommonDao;
import com.caimei.www.pojo.order.ActivityPrice;
import com.caimei.www.pojo.order.CartItem;
import com.caimei.www.pojo.order.LadderPrice;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.IntStream;

/**
 * Description
 *
 * @author : Charles
 * @date : 2020/7/28
 */
@Service
public class CommonServiceUtil {
    @Resource
    private CommonDao commonDao;
    /**
     * 设置购物车商品价格
     * @param cartItem
     * @param userId
     */
    public void setCartItemPrice(CartItem cartItem, Integer userId) {
        // 活动价
        ActivityPrice activity = commonDao.getActivityPriceByProductId(cartItem.getProductId());
        if (null != activity) {
            cartItem.setPrice(activity.getPrice());
            cartItem.setActivityFlag(1);
            cartItem.setLadderFlag(0);
        } else if (cartItem.getLadderFlag() == 1) {
            // 阶梯价
            List<LadderPrice> ladderPrices = commonDao.getladderPricesByProductId(cartItem.getProductId());
            if (!CollectionUtils.isEmpty(ladderPrices)){
                IntStream.range(0, ladderPrices.size()).forEach(i->{
                    boolean isThisLadder;
                    if (i == ladderPrices.size()-1) {
                        ladderPrices.get(i).setMaxNum(0);
                        isThisLadder = (cartItem.getNumber()>ladderPrices.get(i).getBuyNum());
                    } else {
                        ladderPrices.get(i).setMaxNum(ladderPrices.get(i+1).getBuyNum());
                        isThisLadder = (cartItem.getNumber()>ladderPrices.get(i).getBuyNum() && cartItem.getNumber()<ladderPrices.get(i).getMaxNum());
                    }
                    if (isThisLadder){
                        cartItem.setPrice(ladderPrices.get(i).getBuyPrice());
                    }
                });
                cartItem.setMin(ladderPrices.get(0).getBuyNum());
                cartItem.setLadderPrices(ladderPrices);
            } else {
                cartItem.setLadderFlag(0);
            }
        } else {
            // 复购价
            Double repurchase = commonDao.getRepurchasePrice(cartItem.getProductId(), userId);
            if (null != repurchase && repurchase>0) {
                cartItem.setPrice(repurchase);
            }
        }
    }
}


