/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: CouponService
 * @Package cn.freemud.service
 * @Description:
 * @author: pengfei.liu
 * @date: 2020/11/23
 * @version V1.0
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

package cn.freemud.service.active.impl;

import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountRequestDto;
import cn.freemud.entities.dto.calculate.CalculationDiscountResult;
import cn.freemud.entities.dto.calculate.Goods;
import cn.freemud.entities.dto.calculate.GoodsDiscount;
import cn.freemud.entities.dto.product.info.ProductBean;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartInfoRequestVo;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.CalculationGoodsType;
import cn.freemud.service.active.ActiveService;
import cn.freemud.service.cache.GiftCacheManager;
import cn.freemud.service.impl.BuyAndGiftsPromotionService;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("platformActiveService")
public class PlatformActiveServiceImpl implements ActiveService {

    @Autowired
    private BuyAndGiftsPromotionService buyAndGiftsPromotionService;
    @Autowired
    private GiftCacheManager giftCacheManager;

    /**
     * 用户选择的商品和数量都要传给促销
     * @param calculationSharingDiscountRequestDto
     * @param chooseGoods
     */
    @Override
    public void buildChooseGoodsService(ActivityCalculationDiscountRequestDto calculationSharingDiscountRequestDto, List<ShoppingCartInfoRequestVo.ChooseGood> chooseGoods) {

        // 买一赠一寄件活动
        List<ActivityCalculationDiscountRequestDto.CalculationActivityReqVO> selectActivityList = calculationSharingDiscountRequestDto.getSelectActivityList() == null ? new ArrayList<>() : calculationSharingDiscountRequestDto.getSelectActivityList();

        if(null != chooseGoods && !chooseGoods.isEmpty()){

            ActivityCalculationDiscountRequestDto.CalculationActivityReqVO  calculationActivityReqVO = new ActivityCalculationDiscountRequestDto.CalculationActivityReqVO();

            List<ActivityCalculationDiscountRequestDto.CalculationSendGoodsReqVO> sendGoods = new ArrayList<>();

            chooseGoods.forEach(chooseGood -> {
                calculationActivityReqVO.setActivityCode(chooseGood.getActiveCode());
                calculationActivityReqVO.setActivityType(ActivityTypeEnum.TYPE_63.getCode());
                ActivityCalculationDiscountRequestDto.CalculationSendGoodsReqVO sendGood = new ActivityCalculationDiscountRequestDto.CalculationSendGoodsReqVO();
                sendGood.setGoodsId(chooseGood.getGoodsId());
                sendGood.setGoodsQuantity(1);
                sendGoods.add(sendGood);
            });
            selectActivityList.add(calculationActivityReqVO);

        }
        calculationSharingDiscountRequestDto.setSelectActivityList(selectActivityList);

    }

    @Override
    public void gifAddCart(List<CartGoods> oldcartGoodsLists,
                           List<CartGoods> addcartGoodsList,
                           List<ProductBean> products ,
                           ShoppingCartInfoRequestVo shoppingCartInfoRequestVo,
                           CalculationDiscountResult discountResult,
                           String partnerId,
                           String storeId,
                           String userId,
                           Integer flag) {
        Map<String, ProductBean> productMap = products.stream().collect(Collectors.toMap(ProductBean::getPid, k -> k, (k1, k2) -> k1));
        List<CartGoods> list = new ArrayList<>();
        for (Goods goods : discountResult.getGoods()) {
            // 过滤掉非赠品的商品
            if (! CalculationGoodsType.TYPE_1.getType().equals(goods.getCartGoodType())) continue;
            ProductBean product = productMap.get(goods.getGoodsId());
            GoodsDiscount discount = goods.getDiscounts()
                    .stream()
                    .filter(g -> ActivityTypeEnum.TYPE_63.getCode().equals(g.getType()) ||ActivityTypeEnum.TYPE_62.getCode().equals(g.getType()) || ActivityTypeEnum.TYPE_61.getCode().equals(g.getType()) ||  ActivityTypeEnum.TYPE_230.getCode().equals(g.getType()))
                    .findFirst()
                    .get();
            CartGoods cartGood = new CartGoods();
            cartGood.setGoodsId(goods.getGoodsId());
            cartGood.setOriginalGoodsUid(goods.getOriginalGoodsUid());
            cartGood.setGoodsType(1);
            cartGood.setLinkedId(product.getLinkedId());
            cartGood.setSpuId(Objects.equals(product.getIsSkuProduct(), 1) ? product.getSpecProductId() : goods.getGoodsId());
            cartGood.setSkuId(goods.getGoodsId());
            cartGood.setOriginalPrice(product.getFinalPrice());
            cartGood.setPackPrice(product.getPackPrice());
            cartGood.setOriginalAmount(goods.getOriginalPrice() * goods.getGoodsQuantity());
            cartGood.setAmount(goods.getRealAmount());
            cartGood.setName(product.getName());
            cartGood.setSpuName(product.getName());
            cartGood.setCategoryName(product.getName());
            cartGood.setPic(product.getPicture());
            cartGood.setSkuName(product.getName());
            cartGood.setActivityType(discount.getType());
            cartGood.setActivityCode(discount.getActivityCode());
            cartGood.setStockLimit(ObjectUtils.equals(1, product.getStockLimit()));
            cartGood.setCustomerCode(product.getCustomerCode());
            cartGood.setUnit(product.getUnit());
            cartGood.setWeight(product.getWeight());
            cartGood.setQty(goods.getGoodsQuantity());
            cartGood.setClassificationId(product.getCategory());
            cartGood.setClassificationName(product.getCategoryName());
            // nodeId标识activeCode,用于计算均摊时每个商品在每个活动上均摊金额
            cartGood.setNodeId(discount.getActivityCode());
            list.addAll(buyAndGiftsPromotionService.setGiftExtra(cartGood, product, oldcartGoodsLists));
        }
        // 因为有涉及到用户选择的属性，存入redis
        addcartGoodsList.addAll(giftCacheManager.resetGiftCache(list, null, partnerId, storeId, userId));
    }

}
