package cn.freemud.service.impl.calculate.promotion;

import cn.freemud.constant.ShoppingCartConstant;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.calculate.CalculationSharingDiscountResponseDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.CalculationGoodsType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.ItemService;
import cn.freemud.service.impl.AssortmentSdkService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
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.function.Function;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: cn.freemud.service.impl.calculate.promotion AdditionSharingService
 * @Description: 加价购商品
 * @author: pengfei.liu
 * @date: 2020/11/26
 * @Copyright: www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class BuyOneGiveOneSendService {

    @Autowired
    private AssortmentSdkService assortmentSdkService;
    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;

    public void giftResponse(CalculationSharingDiscountResponseDto.CalculationDiscountResult discountResult
            , List<CartGoods> cartGoodsList
            , ShoppingCartInfoRequestVo shoppingCartInfoRequestVo
            , ActivityQueryDto activityQueryDto
            , ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {

        if(discountResult == null){
            return;
        }

        //  过略出来买一赠一寄杯活动，没有直接返回
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount> discounts = discountResult.getDiscounts();
        if(null == discounts || discounts.isEmpty()){
            return;
        }
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount> buyOneGiveOneSendDiscounts = discounts
                .stream()
                .filter(discount -> ObjectUtils.equals(discount.getType(),ActivityTypeEnum.TYPE_63.getCode()))
                .collect(Collectors.toList());
        if(null == buyOneGiveOneSendDiscounts || buyOneGiveOneSendDiscounts.isEmpty()){
            return;
        }

        if (discountResult == null || CollectionUtils.isEmpty(discountResult.getGoods())) {
            return;
        }
/*        String menuType = shoppingCartInfoRequestVo == null ? null : shoppingCartInfoRequestVo.getMenuType();
        // 构建赠品detail
        List<ProductBeanDTO> beanDTOList = this.drawGiftInfo(discountResult, activityQueryDto, menuType);
        this.setCartGoods(discountResult, cartGoodsList, beanDTOList);*/

        // 设置用户可以选择的寄送商品券码
        this.buildSendGoods(discountResult,shoppingCartGoodsResponseVo,shoppingCartInfoRequestVo);
    }

    /**
     * 构建用户可以商品券信息
     *
     * @param discountResult
     * @return
     */
    private void buildSendGoods(CalculationSharingDiscountResponseDto.CalculationDiscountResult discountResult,ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo,ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {

        // 赠送、换购商品信息集合
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity> sendGoods = discountResult.getSendGoods();
        if(sendGoods == null || sendGoods.isEmpty()){
            return;
        }

        // 抽取买一赠一寄件活动送的商品
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity> buyOneGiveOneSendGoods = sendGoods
                .stream()
                .filter(sendGood -> ObjectUtils.equals(sendGood.getActivityType(),ActivityTypeEnum.TYPE_63.getCode()))
                .collect(Collectors.toList());

        if(null == buyOneGiveOneSendGoods || buyOneGiveOneSendGoods.isEmpty()){
            return;
        }

        List<ShoppingCartGoodsResponseVo.chooseGood> chooseGoods = shoppingCartGoodsResponseVo.getChooseGoods() == null ? new ArrayList<>() : shoppingCartGoodsResponseVo.getChooseGoods();
        buyOneGiveOneSendGoods.forEach(sendActivity ->{

            // 这个是真正的送的券
            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> innerSendGoods = sendActivity.getSendGoods();
            if(innerSendGoods == null || innerSendGoods.isEmpty()){
                return;
            }

            innerSendGoods.forEach(innerSendGood -> {
                ShoppingCartGoodsResponseVo.chooseGood  chooseGood = new ShoppingCartGoodsResponseVo.chooseGood();
                chooseGood.setActiveCode(sendActivity.getActivityCode());
                chooseGood.setActiveType(sendActivity.getActivityType());
                chooseGood.setGoodsId(innerSendGood.getGoodsId());
                chooseGood.setQty(innerSendGood.getSendNumber());
                chooseGood.setCouponQty(1);
                chooseGood.setCartGoodsUid(innerSendGood.getOriginalGoodsUid());
                chooseGood.setCouponCode(innerSendGood.getSendCouponCode());
                chooseGood.setCouponName(innerSendGood.getSendCouponName());
                chooseGood.setSendCoupon(innerSendGood.getSendCoupon());
                chooseGood.setGoodsName(innerSendGood.getGoodsName());
                chooseGoods.add(chooseGood);
            });
        });

        shoppingCartGoodsResponseVo.setChooseGoods(chooseGoods);

        /*
        List<ShoppingCartGoodsResponseVo.chooseGood> chooseGoods = shoppingCartGoodsResponseVo.getChooseGoods() == null ? new ArrayList<>() : shoppingCartGoodsResponseVo.getChooseGoods();


        // 赠送、换购商品信息集合
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity> sendGoods = discountResult.getSendGoods();
        if(sendGoods == null || sendGoods.isEmpty()){
            ApiLog.info("买一赠一寄件活动,未查到赠送、换购商品信息集合,shoppingCartInfoRequestVo,discountResult", shoppingCartInfoRequestVo,discountResult);
            return;
        }

        Map<String,CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> activeSendGoodMap = new HashMap<>();

        for(CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity sendGood : sendGoods){
            if(!ObjectUtils.equals(sendGood.getActivityType(),ActivityTypeEnum.TYPE_63.getCode())){
                break;
            }

            String activeCode = sendGood.getActivityCode();
            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> innerSendGoods = sendGood.getSendGoods();
            if(innerSendGoods == null || innerSendGoods.isEmpty()){
                break;
            }
            for(CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods innerSendGood : innerSendGoods){
                String goodsId = innerSendGood.getGoodsId();
                activeSendGoodMap.put(activeCode + "-" + goodsId,innerSendGood);
            }

        }

        // 商品优惠信息
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods> goods = discountResult.getGoods();

        if(goods == null || goods.isEmpty()){
            ApiLog.info("买一赠一寄件活动,未查到商品优惠信息,shoppingCartInfoRequestVo,discountResult", shoppingCartInfoRequestVo,discountResult);
            return;
        }

        goods.forEach(g -> {

            // 获取商品参加的优惠活动
            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> discounts = g.getDiscounts();
            if(discounts == null || discounts.isEmpty()){
                ApiLog.info("买一赠一寄件活动,优惠商品未查找到优惠集合,shoppingCartInfoRequestVo,discountResult", shoppingCartInfoRequestVo,discountResult);
                return;
            }

            // 获取商品参加的买一赠一寄件优惠活动
            List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> buyOneGiveOneSendDiscount = discounts.stream()
                    .filter(discount -> ObjectUtils.equals(discount.getType(),ActivityTypeEnum.TYPE_63.getCode()))
                    .collect(Collectors.toList());

            if(buyOneGiveOneSendDiscount == null || buyOneGiveOneSendDiscount.isEmpty()){
                ApiLog.info("买一赠一寄件活动,优惠商品未参加买一赠一寄件活动,shoppingCartInfoRequestVo,discountResult", shoppingCartInfoRequestVo,discountResult);
                return;
            }

            buyOneGiveOneSendDiscount.forEach(d -> {
                String activeCode = d.getActivityCode();
                String goodsId = g.getGoodsId();
                CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods innerSendGood = activeSendGoodMap.get(activeCode + "-" + goodsId);

                ShoppingCartGoodsResponseVo.chooseGood  chooseGood = new ShoppingCartGoodsResponseVo.chooseGood();
                chooseGood.setCartGoodsUid(g.getCartGoodsUid());
                chooseGood.setActiveCode(activeCode);
                chooseGood.setActiveType(ActivityTypeEnum.TYPE_63.getCode());
                chooseGood.setGoodsId(goodsId);
                chooseGood.setQty(innerSendGood.getSendNumber());
                chooseGood.setCouponQty(1);
                chooseGood.setCouponCode(innerSendGood.getSendCouponCode());
                chooseGood.setCouponName(innerSendGood.getSendCouponName());
                chooseGood.setSendCoupon(innerSendGood.getSendCoupon());
                chooseGood.setGoodsName(innerSendGood.getGoodsName());
                chooseGoods.add(chooseGood);
            });
        });

        shoppingCartGoodsResponseVo.setChooseGoods(chooseGoods);*/

    }

    public void validator(CalculationSharingDiscountResponseDto.CalculationDiscountResult discountResult
            , List<CartGoods> cartGoodsList
            , ShoppingCartInfoRequestVo shoppingCartInfoRequestVo
            , ActivityQueryDto activityQueryDto
            , ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {

        // 用户选择的商品、数量不在促销返回的优惠信息中，返回错误
        if(shoppingCartInfoRequestVo == null ){
            throw new ServiceException(ResponseResult.SHOPPING_CART_REQUEST_NOT_EMPTY);
        }

        // 用户选择的商品信息
        List<ShoppingCartInfoRequestVo.ChooseGood> chooseGoods = shoppingCartInfoRequestVo.getChooseGoods();

        // 用户没有选择商品，不做校验
        if(chooseGoods == null ||  chooseGoods.isEmpty()){
            return;
        }

        if(discountResult == null){
            throw new ServiceException(ResponseResult.SHOPPING_CART_BUY_ONE_SEND_GOODS_NOT_EMPTY);
        }

        // 促销返回的赠送信息
        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity> sendGoods = discountResult.getSendGoods();
        if(sendGoods == null || sendGoods.isEmpty()){
            throw new ServiceException(ResponseResult.SHOPPING_CART_BUY_ONE_SEND_GOODS_NOT_EMPTY);
        }

        List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity> sendActivityList = sendGoods
                .stream()
                .filter(sendActivity -> ObjectUtils.equals(sendActivity.getActivityType(),ActivityTypeEnum.TYPE_63.getCode()))
                .collect(Collectors.toList());

        // 校验用户选择的商品、优惠券是否在促销返回的买一赠一寄件活动中
        // 没有返回错误

        for(ShoppingCartInfoRequestVo.ChooseGood chooseGood : chooseGoods){
            boolean flag = true;
            if(sendActivityList == null || sendActivityList.isEmpty()){
                throw new ServiceException(ResponseResult.SHOPPING_CART_BUY_ONE_SEND_GOODS_NOT_EMPTY);
            }

            for(CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity : sendActivityList){
                List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> innerSendGoods = sendActivity.getSendGoods();
                if(innerSendGoods == null || innerSendGoods.isEmpty()){
                    break;
                }

                for(CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods innerSendGood : innerSendGoods){
                    if(ObjectUtils.equals(chooseGood.getGoodsId(),innerSendGood.getGoodsId())){
                        if(ObjectUtils.equals(chooseGood.getCouponCode(),innerSendGood.getSendCouponCode())){
                            flag = false;
                        }
                    }
                }
            }

            if(flag){
                throw new ServiceException(ResponseResult.SHOPPING_CART_BUY_ONE_SEND_GOODS_ERR);
            }
        }



    }


}