package cn.freemud.service.impl;

import cn.freemud.adapter.PromotionAdapter;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.promotion.*;
import cn.freemud.entities.dto.shoppingCart.ActivityDiscountsDto;
import cn.freemud.entities.vo.ActivityDiscountsVo;
import cn.freemud.service.IPromotionService;
import com.freemud.application.sdk.api.ordercenter.enums.ProductTypeEnum;
import com.freemud.application.sdk.api.promotioncenter.dto.promotion.ApportionGoodsDTO;
import com.freemud.application.sdk.api.promotioncenter.response.CalculationDiscountResponseDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title:
 * @Package: com.freemud.sdk.api.assortment.promotion.service.calculationService.impl
 * @Descripttion:
 * @author: shuhu.hou
 * @date: 2019/9/16
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
@Service
public class SetMealPromotionService implements IPromotionService {
    @Override
    public void updateDiscountApportion(ShoppingCartGoodsResponse shoppingCartGoodsResponse, OrderBeanRequest request, CalculationDiscountResultDto calculationDiscountResult, CouponPromotionDto couponPromotionDto, ActivityQueryDto activityQueryDto ,Boolean isApportion) {
        // 套餐商品
        List<OrderBeanRequest.ProductBean> setMealProducts = request.getProductList().stream()
                .filter(productBean -> {
                    boolean isSetMeal = ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productBean.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productBean.getProductType());
                    boolean hasPrice = productBean.getSettlementPrice() > 0;
                    return isSetMeal && hasPrice;
                }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(setMealProducts)) {
            return;
        }

        List<CalculationApportionGoodsDto> apportionGoodsList = (calculationDiscountResult == null || calculationDiscountResult.getApportionGoods() == null) ? new ArrayList<>() : calculationDiscountResult.getApportionGoods();

        //套餐原价
        Long totalOriginalAmount = setMealProducts.stream().mapToLong(p -> p.getNumber() * p.getPrice()).sum();
        //套餐现价
        long totalAmount = setMealProducts.stream().mapToLong(OrderBeanRequest.ProductBean::getSettlementPrice).sum();



        Map<String, String> duplicateGoodsMap = new HashMap<>();
        setMealProducts.stream().collect(Collectors.groupingBy(OrderBeanRequest.ProductBean::getProductId, Collectors.counting())).forEach((goodsId, count) -> {
            duplicateGoodsMap.put(goodsId,String.format("%s,0", count));
        });

        // 更新套餐商品明细
        List<ShoppingCartGoodsResponse.CartGoodsDetailDto> products = shoppingCartGoodsResponse.getProducts();
        // 套餐商品总优惠
        Long totalDiscountAmount = 0L;
        for (OrderBeanRequest.ProductBean productBean : setMealProducts) {
            Long discountAmount = productBean.getPrice() * productBean.getNumber() - productBean.getSettlementPrice();
            Long productGroupDiscountAmount = productBean.getComboProduct().stream().filter(t -> !t.getIsFixedProduct()).mapToLong(t -> t.getPrice() * t.getNumber() - t.getSettlementPrice()).sum();
            totalDiscountAmount += discountAmount - productGroupDiscountAmount;
            // 设置套餐主商品
            ShoppingCartGoodsResponse.CartGoodsDetailDto cartGoodsDetailDto = PromotionAdapter.convertCartGoods2DetailGoods(productBean, discountAmount.intValue(), apportionGoodsList, duplicateGoodsMap, isApportion);
            cartGoodsDetailDto.getActivityDiscountsDtos().add(getActivityDiscountsDto(discountAmount.intValue() - productGroupDiscountAmount.intValue()));
            long apportionAmount = cartGoodsDetailDto.getTotalDiscountAmount() - discountAmount;
            Long comboFixedProductTotalDiscountAmount = discountAmount - productGroupDiscountAmount + apportionAmount;
            // 设置套餐固定子商品
            List<OrderBeanRequest.ProductBean> fixedProductBeanList = productBean.getComboProduct().stream().filter(OrderBeanRequest.ProductBean::getIsFixedProduct).collect(Collectors.toList());
            List<ShoppingCartGoodsResponse.CartGoodsDetailDto> comboCartGoodsDetailDtoList = new ArrayList<>();
            comboCartGoodsDetailDtoList.addAll(PromotionAdapter.convertCartGoods2DetailGoods(fixedProductBeanList, comboFixedProductTotalDiscountAmount));
            // 套餐可选子商品
            List<OrderBeanRequest.ProductBean> productGroupList = productBean.getComboProduct().stream().filter(t -> !t.getIsFixedProduct()).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(productGroupList)) {
                comboCartGoodsDetailDtoList.addAll(PromotionAdapter.convertCartGoods2DetailGoods(productGroupList, productGroupDiscountAmount));
            }
            cartGoodsDetailDto.setComboList(comboCartGoodsDetailDtoList);
            products.add(cartGoodsDetailDto);
        }

        //订单级别，套餐优惠活动
        if (totalDiscountAmount > 0) {
            shoppingCartGoodsResponse.getActivityDiscountsDtos().add(getActivityDiscountsDto(-totalDiscountAmount.intValue()));
        }

        shoppingCartGoodsResponse.setTotalDiscountAmount(shoppingCartGoodsResponse.getTotalDiscountAmount() + totalOriginalAmount - totalAmount);
    }

    private ActivityDiscountsDto getActivityDiscountsDto(Integer totalDiscountAmount) {
        ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
        activityDiscountsDto.setActivityCode("setMeal");
        activityDiscountsDto.setActivityName("套餐商品优惠");
        activityDiscountsDto.setActivityType(211);
        activityDiscountsDto.setDiscountAmount(totalDiscountAmount);
        return activityDiscountsDto;
    }

}
