package cn.freemud.service.impl;

import cn.freemud.entities.dto.ActivityCalculationDiscountResponseDto;
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 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.*;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.cn
 * 买赠活动
 * 例如：买烧饼送手提袋
 *
 * @version V1.0
 * @Title: BuyAndGiftsPromotionService
 * @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 BuyAndGiftsPromotionService implements IPromotionService {
    @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 (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getSendGoods())) {
            return;
        }
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> sendActivities = calculationDiscountResult.getSendGoods().stream().filter(goods -> ActivityTypeEnum.TYPE_62.getCode().equals(goods.getActivityType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(sendActivities)) {
            return;
        }
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> sendGoodsList = new ArrayList<>();
        sendActivities.forEach(sendActivity -> sendGoodsList.addAll(sendActivity.getSendGoods()));
        List<ProductBeanDTO> productBeanDTOS = buildActivityProduct(activityQueryDto, sendGoodsList,shoppingCartInfoRequestVo==null?null:shoppingCartInfoRequestVo.getMenuType());
        if (CollectionUtils.isEmpty(productBeanDTOS)) {
            return;
        }

        Long totalGiftAmount = 0L;
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity : sendActivities) {
            for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods sendGoods : sendActivity.getSendGoods()) {
                Optional<ProductBeanDTO> firstProduct = productBeanDTOS.stream().filter(productBean -> ObjectUtils.equals(productBean.getPid(), sendGoods.getGoodsId())).findFirst();
                if (!firstProduct.isPresent()) {
                    continue;
                }
                ProductBeanDTO product = firstProduct.get();
                CartGoods cartGoods = new CartGoods();
                cartGoods.setGoodsId(sendGoods.getGoodsId());
                cartGoods.setGoodsType(1);
                cartGoods.setSpuId(sendGoods.getGoodsId());
                cartGoods.setSkuId(sendGoods.getGoodsId());
                cartGoods.setOriginalPrice(product.getFinalPrice());
                cartGoods.setPackPrice(product.getPackPrice());
                cartGoods.setOriginalAmount(product.getFinalPrice() * sendGoods.getSendNumber());
                cartGoods.setAmount(0L);
                cartGoods.setName(product.getName());
                cartGoods.setSpuName(product.getName());
                cartGoods.setCategoryName(product.getName());
                cartGoods.setPic(product.getPicture());
                cartGoods.setSkuName(product.getName());
                cartGoods.setActivityType(ActivityTypeEnum.TYPE_62.getCode());
                cartGoods.setStockLimit(ObjectUtils.equals(1, product.getStockLimit()));
                cartGoods.setCustomerCode(product.getCustomerCode());
                cartGoods.setUnit(product.getUnit());
                cartGoods.setWeight(product.getWeight());
                cartGoods.setQty(sendGoods.getSendNumber());
                cartGoods.setClassificationId(product.getCategory());
                cartGoods.setClassificationName(product.getCategoryName());
                // nodeId标识activeCode,用于计算均摊时每个商品在每个活动上均摊金额
                cartGoods.setNodeId(sendActivity.getActivityCode());
                this.setGiftExtra(cartGoods,product,cartGoodsList);
                cartGoodsList.add(cartGoods);
                totalGiftAmount += product.getFinalPrice() * sendGoods.getSendNumber();
            }
        }


        shoppingCartGoodsResponseVo.setOriginalTotalAmount(shoppingCartGoodsResponseVo.getOriginalTotalAmount() + totalGiftAmount);
        Long totalDiscountAmount = Objects.isNull(shoppingCartGoodsResponseVo.getTotalDiscountAmount()) ? 0L : shoppingCartGoodsResponseVo.getTotalDiscountAmount();
        shoppingCartGoodsResponseVo.setTotalDiscountAmount(totalDiscountAmount + totalGiftAmount);

    }

    @Override
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getSendGoods())) {
            return;
        }
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> sendActivities = calculationDiscountResult.getSendGoods().stream().filter(goods -> ActivityTypeEnum.TYPE_62.getCode().equals(goods.getActivityType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(sendActivities)) {
            return;
        }

        List<ShoppingCartGoodsDto.CartGoodsDetailDto> sendGoodsList = shoppingCartGoodsDto.getProducts().stream().filter(product -> ActivityTypeEnum.TYPE_62.getCode().equals(product.getActivityType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(sendGoodsList)) {
            return;
        }
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos() == null ? new ArrayList<>() : shoppingCartGoodsDto.getActivityDiscountsDtos();
        //设置商品行活动均摊
        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto : sendGoodsList) {
            Optional<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity> first = sendActivities.stream().filter(sendActivity -> ObjectUtils.equals(sendActivity.getActivityCode(), cartGoodsDetailDto.getNodeId())).findFirst();
            if (!first.isPresent()) {
                continue;
            }
            ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity = first.get();
            ActivityDiscountsDto ProductActivityDiscountsDto = new ActivityDiscountsDto();
            ProductActivityDiscountsDto.setActivityCode(sendActivity.getActivityCode());
            ProductActivityDiscountsDto.setActivityName(sendActivity.getActivityName());
            ProductActivityDiscountsDto.setActivityType(sendActivity.getActivityType());
            ProductActivityDiscountsDto.setDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount());
            cartGoodsDetailDto.setActivityDiscountsDtos(Arrays.asList(ProductActivityDiscountsDto));
        }
        //设置活动级别的均摊
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity : sendActivities) {
            //设置优惠活动
            Integer totalDiscountAmount = sendGoodsList.stream().filter(sendGoods -> ObjectUtils.equals(sendActivity.getActivityCode(), sendGoods.getNodeId())).mapToInt(sendGoods -> sendGoods.getTotalDiscountAmount()).sum();
            ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
            activityDiscountsDto.setActivityCode(sendActivity.getActivityCode());
            activityDiscountsDto.setActivityName(sendActivity.getActivityName());
            activityDiscountsDto.setActivityType(sendActivity.getActivityType());
            activityDiscountsDto.setDiscountAmount(0 - totalDiscountAmount);
            activityDiscountsDtos.add(activityDiscountsDto);
        }
    }

    /**
     * @param activityQueryDto
     * @param sendGoodsList
     * @return
     */
    private List<ProductBeanDTO> buildActivityProduct(ActivityQueryDto activityQueryDto, List<ActivityCalculationDiscountResponseDto
            .CalculationDiscountResult.SendActivity.SendGoods> sendGoodsList,String menuType) {
        //获取
        List<String> goodsIds = sendGoodsList.stream().map(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods::getGoodsId).collect(Collectors.toList());
        List<ProductBeanDTO> productBeanList = assortmentSdkService.getProductsInfoSdk(activityQueryDto.getPartnerId()
                , activityQueryDto.getStoreId(), goodsIds, menuType ,shoppingCartBaseService);
        if (CollectionUtils.isEmpty(productBeanList)) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_GIFTS_PRODUCT_NOT_EXIST);
        }
        return productBeanList;
    }


    private void setGiftExtra(CartGoods cartGoods,ProductBeanDTO product,List<CartGoods> cartGoodsList) {
        long count = cartGoodsList.stream().filter(c -> c.getSpuId().equals(cartGoods.getSpuId())).count();
        //购物车内存在同类
        if (count>0) {
            CartGoods find = cartGoodsList.stream().filter(c -> c.getSpuId().equals(cartGoods.getSpuId())).findFirst().get();
            cartGoods.setExtra(find.getExtra());
            cartGoods.setSpuName(find.getSpuName());
            cartGoods.setSkuName(find.getSkuName());
            cartGoods.setSubName(find.getSubName());
        }
        //不存在
        else {
            if (product.getProductAttributeGroupList().size()==0) {
                return;
            }
            List<CartGoods.CartGoodsExtra> extra = new ArrayList<>();
            ArrayList<String> name = new ArrayList<>();
            List<ProductBeanDTO.ProductAttributeGroupListBean> productAttributeGroupList = product.getProductAttributeGroupList();
            for (ProductBeanDTO.ProductAttributeGroupListBean productAttributeGroupListBean : productAttributeGroupList) {
                ProductBeanDTO.ProductAttributeGroupListBean.AttributeValueBean bean = productAttributeGroupListBean.getAttributeValues().stream().findFirst().get();

                CartGoods.CartGoodsExtra goodsExtra = new CartGoods.CartGoodsExtra();
                goodsExtra.setAttributeId(bean.getAttributeId());
                goodsExtra.setAttributeName(bean.getAttributeValue());
                name.add(bean.getAttributeValue());
                extra.add(goodsExtra);
            }
            cartGoods.setExtra(extra);
            cartGoods.setSubName(StringUtils.join(name, "/"));
        }
    }
}
