/**
 * 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.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Service;

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

@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());

            List<CartGoods> products = shoppingCartGoodsResponseVo.getProducts();
            List<String> gifeProductIds = new ArrayList<>();
            if(products != null && !products.isEmpty()){
                // 获取赠品的商品id
                gifeProductIds = products.stream().filter(product -> Objects.equals(product.getActivityType(),ActivityTypeEnum.TYPE_63.getCode())).map(CartGoods::getGoodsId).collect(Collectors.toList());
            }

            Map<String,CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods> goodsDiscountsMap = new HashMap<>();

            Map<String,CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> halfDiscountsMap = new HashMap<>();
            // 商品优惠信息
            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods> goodsDiscounts = discountResult.getGoods();
            if(goodsDiscounts == null || goodsDiscounts.isEmpty()){
                return;
            }

            goodsDiscountsMap = goodsDiscounts.stream().collect(Collectors.toMap(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods::getCartGoodsUid, g -> g,(k1,k2)->k1));

            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())){
                        halfDiscountsMap.put(goodsDiscount.getCartGoodsUid() + "-" + discount.getGoodsId(),discount);
                    }

                });
            });

            List<CartGoods> newProducts = new ArrayList<>();

            if(!Objects.equals(flag,1)){// 非结算页
                if(products == null || products.isEmpty()){
                    return;
                }

                List<CartGoods> halfProduct = new ArrayList<>();

                for(int x = 0 ; x < products.size() ; x ++){
                    CartGoods product = products.get(x);
                    // 要添加的半价行数量，该字段从促销返回
                    Integer num = 0;
                    // 商品优惠的金额
                    Long discountAmount = 0L;
                    if(halfDiscountsMap.get(product.getCartGoodsUid() + "-" + product.getGoodsId()) != null){
                        CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount discount = halfDiscountsMap.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;
                    // 数量减去购物车行之后如果为0就不加入购物车
                    // 主商品行要数量，价格
                    if(!Objects.equals(newQty,0)){
                        product.setAmount(product.getAmount() - discountAmount * num);
                        product.setOriginalAmount(product.getOriginalAmount() - product.getOriginalPrice() * num);
                        product.setQty(newQty);

                        // 商品的现单价使用促销返回的现单价
                        // 但是要排除赠品行、半价行
                        if(!ObjectUtils.equals(product.getActivityType(),ActivityTypeEnum.TYPE_63.getCode()) && !ObjectUtils.equals(product.getActivityType(),ActivityTypeEnum.TYPE_53.getCode())){
                            product.setFinalPrice(goodsDiscountsMap.get(product.getCartGoodsUid()).getNowPrice());
                        }

                        // num代表拆出来的半价行数量，gifeProductIds代表赠品
                        // 只要符合条件就需要设置为空
                        // 因为前端指挥在半价行、赠品行上打标
                        // 前端是从商品活动信息中查找活动，在商品列表中找商品
                        if((gifeProductIds.contains(product.getGoodsId()) && product.getActivityType() == null) || !Objects.equals(num,0)){
                            product.setGoodsId(null);
                        }

                        // num代表拆出来的半价行数量
                        // 所以只要不等于0就需要把ActivityType设置为空
                        // 因为前端用这个判断是否能加减
                        if(!Objects.equals(num,0)){
                            product.setActivityType(null);
                        }

                        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());
        // 这个地方不要放置商品id，因为半价行的商品不打活动标签
        // 前端会根据这个活动检索
        newCartGoods.setGoodsType(cgs.getGoodsType());
        newCartGoods.setGoodsId(cgs.getGoodsId());
        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;
    }

}
