/**
 * 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.shoppingCart.impl;

import cn.freemud.entities.dto.calculate.CalculationSharingDiscountResponseDto;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartGoodsResponseVo;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.shoppingCart.ShoppingCartRelationService;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("cocoShoppingCartRelationService")
public class CocoShoppingCartRelationServiceImpl implements ShoppingCartRelationService {


    @Override
    public void buildShoppingCartGoodsResponse(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo,
                                               CalculationSharingDiscountResponseDto.CalculationDiscountResult discountResult,
                                               Integer flag) {

        if(discountResult != null){

            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount> discounts = new ArrayList<>();

            // coco返回的活动中剔除集点活动
            if(discountResult.getDiscounts() != null && !discountResult.getDiscounts().isEmpty()){
                discountResult.getDiscounts().forEach(discount -> {
                    if(ActivityTypeEnum.TYPE_221.getCode().equals(discount.getType())){
                        return;
                    }
                    discounts.add(discount);
                });
            }

            shoppingCartGoodsResponseVo.setDiscounts(discounts);
            shoppingCartGoodsResponseVo.setGoods(discountResult.getGoods());

            // 第二件优惠活动，在点餐页需要给优惠商品单独显示一行
            // 第二件优惠活动Map
            Map<String,CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> goodsDiscountsMap = new HashMap<>();
            // 商品优惠信息
            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods> goodsDiscounts = discountResult.getGoods();
            if(goodsDiscounts == null || goodsDiscounts.isEmpty()){
                return;
            }

            goodsDiscounts.forEach(goodsDiscount ->{
                List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> oneGoodsDiscounts = goodsDiscount.getDiscounts();
                if(oneGoodsDiscounts == null || oneGoodsDiscounts.isEmpty()){
                    return;
                }
                oneGoodsDiscounts.forEach(discount -> {
                    if(Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_53.getCode())){
                        goodsDiscountsMap.put(goodsDiscount.getCartGoodsUid() + "-" + discount.getGoodsId(),discount);
                    }

                });
            });

            List<CartGoods> newProducts = new ArrayList<>();
            List<CartGoods> products = shoppingCartGoodsResponseVo.getProducts();
            if(!Objects.equals(flag,1)){// 非结算页
                if(products == null || products.isEmpty()){
                    return;
                }

                List<CartGoods> halfProduct = new ArrayList<>();
                products.forEach(product -> {
                    Integer num = 0;
                    // 商品优惠的金额
                    Long discountAmount = 0L;
                    if(goodsDiscountsMap.get(product.getCartGoodsUid() + "-" + product.getGoodsId()) != null){
                        CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount discount = goodsDiscountsMap.get(product.getCartGoodsUid() + "-" + product.getGoodsId());
                        if(discount == null){
                            return;
                        }
                        num = discount.getActualGoodsNumber();
                        for(int i = 0 ; i < num ; i++){
                            // 复制商品加到购物车
                            discountAmount = discount.getDiscount();
                            Long newPrice = product.getOriginalPrice() - discountAmount;
                            CartGoods cartGoods = buildNewLine(product,ActivityTypeEnum.TYPE_53.getCode(),1,newPrice);
                            halfProduct.add(cartGoods);
                        }
                    }
                    Integer newQty = product.getQty() - num;
                    // 主商品行要数量，价格
                    if(!Objects.equals(newQty,0)){
                        product.setAmount(product.getAmount() - discountAmount * num);
                        product.setOriginalAmount(product.getOriginalAmount() - product.getOriginalPrice() * num);
                        product.setQty(newQty);
                        newProducts.add(product);
                    }
                    newProducts.addAll(halfProduct);

                });

                shoppingCartGoodsResponseVo.setProducts(newProducts);
            }
        }
    }


    public CartGoods buildNewLine(CartGoods cgs,Integer activityType,Integer qty,Long newPrice){
        CartGoods newCartGoods = new CartGoods();
        newCartGoods.setCartGoodsUid(cgs.getCartGoodsUid());
        newCartGoods.setGoodsId(cgs.getGoodsId());
        newCartGoods.setGoodsType(cgs.getGoodsType());
        newCartGoods.setSpuId(cgs.getSpuId());
        newCartGoods.setSkuId(cgs.getSkuId());
        newCartGoods.setSpecProductId(cgs.getSpecProductId());
        // 价格只用一个商品的价格
        newCartGoods.setOriginalPrice(cgs.getOriginalPrice());
        // 价格只用一个商品的价格
        newCartGoods.setPackPrice(cgs.getPackPrice());
        // 价格只用一个商品的价格
        newCartGoods.setOriginalAmount(cgs.getOriginalPrice());
        // 价格只用一个商品的价格
        newCartGoods.setFinalPrice(newPrice);
        // 价格只用一个商品的价格
        newCartGoods.setAmount(newPrice);
        newCartGoods.setName(cgs.getName());
        newCartGoods.setSpuName(cgs.getSpuName());
        newCartGoods.setSubName(cgs.getSubName());
        newCartGoods.setNodeId(cgs.getNodeId());
        newCartGoods.setCategoryName(cgs.getCategoryName());
        List<CartGoods.CartGoodsExtra> extra = Lists.newArrayList();
        List<CartGoods.CartGoodsExtra> cartGoodsExtras = cgs.getExtra();
        if (CollectionUtils.isNotEmpty(cartGoodsExtras)) {
            cartGoodsExtras.forEach(cartGoodsExtra -> {
                CartGoods.CartGoodsExtra goodsExtra = new CartGoods.CartGoodsExtra();
                goodsExtra.setAttributeId(cartGoodsExtra.getAttributeId());
                goodsExtra.setAttributeName(cartGoodsExtra.getAttributeName());
                extra.add(goodsExtra);
            });
        }
        newCartGoods.setExtra(extra);
        newCartGoods.setPic(cgs.getPic());
        newCartGoods.setCreateTimeMili(cgs.getCreateTimeMili());
        newCartGoods.setSkuName(cgs.getSkuName());
        newCartGoods.setSkuName(cgs.getSkuName());
        newCartGoods.setClassificationId(cgs.getClassificationId());
        newCartGoods.setClassificationName(cgs.getClassificationName());
        //newCartGoods.setActivityType(activityType);
        newCartGoods.setQty(qty);

        return newCartGoods;
    }

}
