package cn.freemud.service.impl;

import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.constant.ShoppingCartConstant;
import cn.freemud.entities.dto.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.GetMenuResponseDto;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.IPromotionService;
import cn.freemud.service.ItemService;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.cn
 * 加价购
 * @version V1.0
 * @Title: AdditionalPromotionService
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: jiaxin.liu
 * @date: 2019/4/18 11:00
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class AdditionalPromotionService implements IPromotionService {

    @Autowired
    private ItemService itemService;
    @Autowired
    private ShoppingCartConvertAdapter shoppingCartConvertAdapter;
    @Autowired
    private AssortmentSdkService assortmentSdkService;
    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;

    @Override
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, UserLoginInfoDto userLoginInfoDto, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (shoppingCartInfoRequestVo == null || CollectionUtils.isEmpty(shoppingCartInfoRequestVo.getSendGoods()) || calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getSendGoods())) {
            return;
        }
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> sendActivities = calculationDiscountResult.getSendGoods().stream().filter(sendActivity -> ObjectUtils.equals(ActivityTypeEnum.TYPE_81.getCode(), sendActivity.getActivityType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(sendActivities)) {
            return;
        }
        // TODO: 2019/8/13 hubowen 需要校验合法性
        List<CreateOrderVo.PremiumExchangeActivity.Product> additionalProducts = buildPremiumExchangeActivityProduct(shoppingCartInfoRequestVo);
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> additionalActivityList = calculationDiscountResult.getSendGoods();
        ResponseResult checkResult = checkAdditionalGoods(additionalProducts, additionalActivityList);
        if (!ObjectUtils.equals(ResponseResult.SUCCESS, checkResult)) {
            throw new ServiceException(checkResult);
        }

        Long totalDiscountPrice = 0L;
        Long totalNowPrice = 0L;
        Map<String, Integer> map = shoppingCartInfoRequestVo.getSendGoods().stream().collect(Collectors.toMap(ShoppingCartInfoRequestVo.SendGoods::getGoodsId, ShoppingCartInfoRequestVo.SendGoods::getQty));
        Map<String, Long> OriginalPrice = sendActivities.get(0).getSendGoods().stream().collect(Collectors.toMap(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getGoodsId, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getOriginalPrice));
        Map<String, Long> newPrice = sendActivities.get(0).getSendGoods().stream().collect(Collectors.toMap(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getGoodsId, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getNowPrice));
        for (String str : map.keySet()) {
            Integer qty = map.get(str);
            if (OriginalPrice.get(str) != null && OriginalPrice.get(str) != 0) {
                totalDiscountPrice += qty * (OriginalPrice.get(str) - newPrice.get(str));
                totalNowPrice += qty * newPrice.get(str);
            }
        }
        shoppingCartGoodsResponseVo.setTotalAmount(calculationDiscountResult.getTotalAmount() + totalNowPrice);
        shoppingCartGoodsResponseVo.setTotalDiscountAmount(shoppingCartGoodsResponseVo.getTotalDiscountAmount() + totalDiscountPrice);
    }

    /**
     * 构建加价购商品校验参数
     *
     * @param shoppingCartInfoRequestVo 入参
     * @return 返回商品
     */
    private List<CreateOrderVo.PremiumExchangeActivity.Product> buildPremiumExchangeActivityProduct(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        //获取
        List<ShoppingCartInfoRequestVo.SendGoods> sendGoods = shoppingCartInfoRequestVo.getSendGoods();
        List<String> goodsIds = sendGoods.stream().map(ShoppingCartInfoRequestVo.SendGoods::getGoodsId).collect(Collectors.toList());
        Map<String, ShoppingCartInfoRequestVo.SendGoods> goodQtyMap = sendGoods.stream().collect(Collectors.toMap(ShoppingCartInfoRequestVo.SendGoods::getGoodsId, Function.identity(), (k1, k2) -> k1));
        List<ProductBeanDTO> productBeanList = assortmentSdkService.getProductsInfoSdk(shoppingCartInfoRequestVo.getPartnerId()
                , shoppingCartInfoRequestVo.getShopId(), goodsIds,shoppingCartInfoRequestVo.getBusinessType(), shoppingCartBaseService);
        if (CollectionUtils.isEmpty(productBeanList)) {
            throw new ServiceException(ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_EXIST);
        }
        return productBeanList.stream().map(productBean -> {
            CreateOrderVo.PremiumExchangeActivity.Product product = new CreateOrderVo.PremiumExchangeActivity.Product();
            List<ProductBeanDTO.SkuProductBean> skuList = productBean.getSkuList();
            List<String> skuIds = null;
            if (null != skuList) {
                skuIds = skuList.stream().map(ProductBeanDTO.SkuProductBean::getSkuId).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(skuIds)) {
                for (String skuId : skuIds) {
                    ShoppingCartInfoRequestVo.SendGoods sendGood = goodQtyMap.get(skuId);
                    if (null != sendGood) {
                        product.setQty(sendGood.getQty());
                        product.setSpuId(productBean.getPid());
                        product.setSkuId(sendGood.getGoodsId());
                        product.setStatus(productBean.getStatus());
                        break;
                    }
                }
            } else {
                ShoppingCartInfoRequestVo.SendGoods sendGood = goodQtyMap.get(productBean.getPid());
                if (null != sendGood) {
                    product.setQty(sendGood.getQty());
                    product.setSpuId(sendGood.getGoodsId());
                    product.setSkuId(sendGood.getGoodsId());
                    product.setStatus(productBean.getStatus());
                }
            }
            return product;
        }).collect(Collectors.toList());

    }

    /**
     * check加价购
     *
     * @param additionalProducts     购物车添加的加价购商品
     * @param additionalActivityList 加价购活动
     * @return
     */
    private ResponseResult checkAdditionalGoods(List<CreateOrderVo.PremiumExchangeActivity.Product> additionalProducts, List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> additionalActivityList) {
        //无加价购活动
        if (CollectionUtils.isEmpty(additionalActivityList)) {
            return ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_EXIST;
        }
        //加价购活动中换购商品为空
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> additionalActivity = additionalActivityList.stream().filter(activity -> ObjectUtils.equals(ActivityTypeEnum.TYPE_81.getCode(), activity.getActivityType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(additionalActivity)) {
            return ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_EXIST;
        }
        //购物车中总加价购数量>每单可换购总数量
        Integer totalAdditionalProductCount = additionalProducts.stream().mapToInt(CreateOrderVo.PremiumExchangeActivity.Product::getQty).sum();
        if (totalAdditionalProductCount > additionalActivity.get(0).getMaxNum()) {
            return ResponseResult.PREMIUM_EXCHANGE_GOODS_OUT_OF_LIMIT;
        }
        //加价购活动中的换购商品列表Map
        Map<String, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> sendGoodsMap = additionalActivity.get(0).getSendGoods().stream().collect(Collectors.toMap(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getGoodsId, Function.identity(), (k1, k2) -> k1));
        for (CreateOrderVo.PremiumExchangeActivity.Product product : additionalProducts) {
            if (ShoppingCartConstant.OFF_LINE_PRODUCT.equals(product.getStatus()) || ShoppingCartConstant.SOLD_OUT_PRODUCT.equals(product.getStatus())) {
                return ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_EXIST;
            }
            if (ShoppingCartConstant.NOT_ON_LINE_PRODUCT.equals(product.getStatus())) {
                return ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_ON_LINE;
            }
            // 购物车中加价购商品不在活动商品列表中 或  每个商品的换购数量>活动限制数量
            ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods sendGoods = Objects.isNull(sendGoodsMap.get(product.getSkuId())) ? sendGoodsMap.get(product.getSpuId()) : sendGoodsMap.get(product.getSkuId());
            if (Objects.isNull(sendGoods)) {
                return ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_EXIST;
            }
            if (product.getQty() > sendGoods.getSendNumber()) {
                return ResponseResult.PREMIUM_EXCHANGE_GOODS_OUT_OF_LIMIT;
            }
        }
        return ResponseResult.SUCCESS;
    }

    @Override
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {

        //购物车中无加价购商品，直接返回
        if (premiumExchangeActivity == null || CollectionUtils.isEmpty(premiumExchangeActivity.getProducts())) {
            return;
        }
        //购物车中加价购商品
        List<CreateOrderVo.PremiumExchangeActivity.Product> additionalProducts = premiumExchangeActivity.getProducts();
        // 加价购活动
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> additionalActivityList = calculationDiscountResult == null ? null : calculationDiscountResult.getSendGoods();
        // check加价购是否合法
        // TODO: 2019/8/13 hubowen 暂时去掉
        ResponseResult checkResult = checkAdditionalGoods(additionalProducts, additionalActivityList);
        if (!ObjectUtils.equals(ResponseResult.SUCCESS, checkResult)) {
            throw new ServiceException(checkResult);
        }
        //无加价购活动
        if (CollectionUtils.isEmpty(additionalActivityList)) {
            throw new ServiceException(ResponseResult.PREMIUM_EXCHANGE_ACTIVITY_NOT_EXIST);
        }
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtoList = shoppingCartGoodsDto.getProducts();
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos();

        //加价购活动中的换购商品列表Map
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity1 = additionalActivityList.stream().filter(activity -> ObjectUtils.equals(ActivityTypeEnum.TYPE_81.getCode(), activity.getActivityType())).collect(Collectors.toList()).get(0);
        Map<String, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> sendGoodsMap = sendActivity1.getSendGoods().stream().collect(Collectors.toMap(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getGoodsId, Function.identity(), (k1, k2) -> k1));
        //添加商品行
        List<String> productIds = premiumExchangeActivity.getProducts().parallelStream().map(p -> StringUtils.isEmpty(p.getSkuId()) ? p.getSpuId() : p.getSkuId()).collect(Collectors.toList());
        Map<String, GetProductsVo> getProductsVoMap = itemService.getProducts(productIds, shoppingCartInfoRequestVo.getPartnerId(), shoppingCartInfoRequestVo.getShopId());
        // 获取计算返回的价格
        Long originalTotalAmount = shoppingCartGoodsResponseVo.getOriginalTotalAmount();
        Long totalAmount = shoppingCartGoodsResponseVo.getTotalAmount();
        Long totalDiscountAmount = shoppingCartGoodsResponseVo.getTotalDiscountAmount();
        //加价换购活动总优惠
        Long currenttotalDiscountAmount = 0L;
        //购物车中添加加价购商品,并计算购物车总优惠价格
        for (CreateOrderVo.PremiumExchangeActivity.Product product : additionalProducts) {
            String goodsId = StringUtils.isEmpty(product.getSkuId()) ? product.getSpuId() : product.getSkuId();
            GetProductsVo getProductsVo = getProductsVoMap.get(goodsId);
            if (null == getProductsVo) {
               continue;
            }
            ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods sendGoods = sendGoodsMap.get(goodsId);
            //1.向购物车中添加商品
            ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = shoppingCartConvertAdapter.getCartGoodsDetailDto(product, getProductsVo, goodsId, sendGoods);
            cartGoodsDetailDtoList.add(cartGoodsDetailDto);
            //2.计算优惠价格
            originalTotalAmount += getProductsVo.getFinalPrice();
            totalDiscountAmount += cartGoodsDetailDto.getTotalDiscountAmount();
            currenttotalDiscountAmount += cartGoodsDetailDto.getTotalDiscountAmount();
            // 3.设置商品行优惠明细
            ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
            activityDiscountsDto.setActivityCode(sendActivity1.getActivityCode());
            activityDiscountsDto.setActivityName(sendActivity1.getActivityName());
            activityDiscountsDto.setActivityType(ActivityTypeEnum.TYPE_81.getCode());
            activityDiscountsDto.setDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount());
            List<ActivityDiscountsDto> activityDiscountsDtoList = new ArrayList<>();
            activityDiscountsDtoList.add(activityDiscountsDto);
            cartGoodsDetailDto.setActivityDiscountsDtos(activityDiscountsDtoList);
        }
        shoppingCartGoodsDto.setOriginalTotalAmount(originalTotalAmount);
        //添加优惠活动
        if (currenttotalDiscountAmount > 0) {
            ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
            activityDiscountsDto.setActivityCode(sendActivity1.getActivityCode());
            activityDiscountsDto.setActivityName(sendActivity1.getActivityName());
            activityDiscountsDto.setActivityType(ActivityTypeEnum.TYPE_81.getCode());
            activityDiscountsDto.setDiscountAmount(0 - currenttotalDiscountAmount.intValue());
            activityDiscountsDtos.add(activityDiscountsDto);
        }
    }
}
