package cn.freemud.service;

import cn.freemud.adapter.ActivityAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ShoppingCartConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.activity.ActivityQueryResponseDto;
import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountRequestDto;
import cn.freemud.entities.dto.calculate.CalculationDiscountResult;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.GoodsTypeEnum;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import javafx.util.Pair;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title:
 * @Package cn.freemud.service
 * @Description:
 * @author: ping.wu
 * @date: 2018/5/18 19:49
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
public interface ShoppingCartNewService {

    /**
     * 从微信卡券向购物车中添加商品
     */
    BaseResponse addGoodsByCard(AddGoodsByWeixinCardRequestVo request);

    /**
     * 添加商品
     *
     * @param addShoppingCartGoodsRequestVo
     * @return
     */
    BaseResponse addGoods(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo);

    /**
     * 更新商品数量
     *
     * @param updateShoppingCartGoodsQtyRequestVo
     * @return
     */
    BaseResponse updateGoodsQty(UpdateShoppingCartGoodsQtyRequestVo updateShoppingCartGoodsQtyRequestVo);

    /**
     * 获取购物车商品信息和可用，不可用优惠券列表
     *
     * @param shoppingCartInfoRequestVo
     * @return
     */
    BaseResponse getGoodsList(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo);

    /**
     * svc卡支付调用接口
     * @param shoppingCartInfoRequestVo
     * @return
     */
    BaseResponse getGoodsListCheck(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo);

    /**
     * 清空购物车
     *
     * @param request
     * @return
     */
    BaseResponse clear(ShoppingCartClearRequestVo request);

    /**
     * 查询购物车信息 包括参与的活动详情,包括所有的
     */
    BaseResponse<ShoppingCartGoodsDto> getShoppingCartGoods(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo,
                                                            CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity);


    CalculationDiscountResult getActivityCalculationDiscountResponse(String partnerId,
                                                                     String storeId,
                                                                     String userId,
                                                                     String appId,
                                                                     Integer orderType,
                                                                     boolean isMember,
                                                                     List<CartGoods> cartGoodsList,
                                                                     List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons,
                                                                     List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList, String menuType, Long distributionFee, Integer bizType, Integer accountFlag);


    List<CartGoods> updateCartGoodsLegal(CartGoods cartGoods, String userId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo, List<CartGoods> oldAllCartGoodsList);

    default BaseResponse<GetMemberInfoResponseVo> getMemberInfo(GetMemberInfoRequestDto request){
        return null;
    };

//    /**
//     * 商品券校验券是否有效
//     *
//     * @param partnerId
//     * @param storeId
//     * @param couponCode
//     * @param productIds
//     * @return
//     */
//    default Pair<String, Integer> validCoupon(String partnerId
//            , String storeId
//            , String couponCode
//            , List<Long> productIds
//            , String menuType
//            , CouponProductDto couponProductDto) {
//        String spuId2;
//        CheckSpqInfoRequestDto checkSpqInfoRequestDto = new CheckSpqInfoRequestDto(partnerId, storeId, couponCode, menuType);
//        CouponService couponService = SDKCommonBaseContextWare.getBean(CouponService.class);
//        CheckSpqInfoResponseDto checkSpqInfoResponseDto = couponService.checkSpqInfo(checkSpqInfoRequestDto,null);
//        if (checkSpqInfoResponseDto == null) {
//            throw new ServiceException(ResponseResult.SHOPPING_CART_COUPON_NOT_EXIST);
//        }
//        if (couponProductDto != null) {
//            couponProductDto.setType(checkSpqInfoResponseDto.getCouponType());
//        }
//        productIds.add(Long.parseLong(checkSpqInfoResponseDto.getSkuId()));
//        spuId2 = checkSpqInfoResponseDto.getSkuId();
//        return new Pair(spuId2, checkSpqInfoResponseDto.getTodayAvailableTimes());
//    }

    /**
     * 换购券　买M赠N券
     *
     * @param partnerId
     * @param storeId
     * @param couponCode
     * @param productIds
     * @param menuType
     * @param goodsId
     * @return
     */
    default Pair<String, Integer> validCoupon(String partnerId
            , String storeId
            , String couponCode
            , List<Long> productIds
            , String menuType
            , String goodsId
            , CouponProductDto couponProductDto) {
        String spuId2;
        CheckSpqInfoRequestDto checkSpqInfoRequestDto = new CheckSpqInfoRequestDto(partnerId, storeId, couponCode, menuType,null);
        CouponService couponService = SDKCommonBaseContextWare.getBean(CouponService.class);
        CheckSpqInfoResponseDto checkSpqInfoResponseDto = couponService.checkSpqInfo(checkSpqInfoRequestDto, goodsId);
        if (checkSpqInfoResponseDto == null) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_COUPON_MIX_NOT_EXIST);
        }
        productIds.add(Long.parseLong(checkSpqInfoResponseDto.getSkuId()));
        couponProductDto.setType(checkSpqInfoResponseDto.getCouponType());
        spuId2 = checkSpqInfoResponseDto.getSkuId();
        return new Pair(spuId2, checkSpqInfoResponseDto.getTodayAvailableTimes());
    }

    /**
     * 添加商品券商品
     *
     * @param addShoppingCartGoodsRequestVo
     * @param cartGoods
     * @param userId
     * @param shoppingCartGoodsResponseVo
     * @param spuId
     * @param spuId2
     * @param allCartGoodsList
     * @param productBeanListSpuClass
     */
    default void addProductGoods(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo
            , CartGoods cartGoods, String spuId2, String userId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, String spuId
            , List<CartGoods> allCartGoodsList, List<ProductBeanDTO> productBeanListSpuClass) {
        // 商品券商品list
        List<CartGoods> tmpCartGoods = allCartGoodsList.parallelStream().filter(k -> k.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX)).collect(Collectors.toList());
        // 当已有商品券时，不得添加(暂时的限制)
        if (CollectionUtils.isNotEmpty(tmpCartGoods)) {
            setToastMsgIfNotExist(shoppingCartGoodsResponseVo, ShoppingCartConstant.ONE_TRADE_CAN_ONLY_USE_ONE_GOODS_COUPON);
            cartGoods.setCartGoodsUid(null);
        } else {
            cartGoods.setCartGoodsUid(spuId);
            // 设置商品类型为商品券
            cartGoods.setGoodsType(GoodsTypeEnum.COUPON_GOODS.getGoodsType());
            // 商品券Id
            String spqId = spuId.substring(CommonsConstant.COUPON_PREFIX.length());
//            cartGoods.setSpuId(spqId);
            cartGoods.setSkuId(spuId2);
            cartGoods.setOriginalPrice(0L);
            cartGoods.setOriginalAmount(0L);
            cartGoods.setAmount(0L);
            cartGoods.setPackPrice(productBeanListSpuClass.get(0).getPackPrice());
            cartGoods.setPic(productBeanListSpuClass.get(0).getPicture());

            List<String> goodsIds = allCartGoodsList.parallelStream().map(CartGoods::getGoodsId).collect(Collectors.toList());
            boolean hasSpecialGoods = hasSpecialGoods(addShoppingCartGoodsRequestVo.getPartnerId(), addShoppingCartGoodsRequestVo.getShopId(), userId, addShoppingCartGoodsRequestVo.getAppId(), goodsIds, addShoppingCartGoodsRequestVo.getOrderType());
            // 如果购物车先加入促销活动的商品，再加入商品券时，toast提示“该商品券与其他活动不同享，购物车中已优惠的商品将恢复原价”
            if (hasSpecialGoods) {
                setToastMsgIfNotExist(shoppingCartGoodsResponseVo, ShoppingCartConstant.HAS_OTHER_ACTIVITY_WHEN_ADD_GOODS_COUPON);
            }
            //校验合法性,更新缓存中购物车信息
            updateCartGoodsLegal(cartGoods, userId, shoppingCartGoodsResponseVo, addShoppingCartGoodsRequestVo, allCartGoodsList);
        }
    }

    /**
     * 当ToastMsg为空时才赋值
     *
     * @param shoppingCartGoodsResponseVo
     * @param message
     */
    default void setToastMsgIfNotExist(ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, String message) {
        if (StringUtils.isEmpty(shoppingCartGoodsResponseVo.getToastMsg())) {
            shoppingCartGoodsResponseVo.setToastMsg(message);
        }
    }

    /**
     * check商品中是否有特价商品
     *
     * @param partnerId
     * @param storeId
     * @param userId
     * @param appId
     * @param goodsIds
     * @return
     */
    default boolean hasSpecialGoods(String partnerId, String storeId, String userId, String appId, List<String> goodsIds, Integer orderType) {
        boolean hasSpecialGoods = false;
        for (String goodsId : goodsIds) {
            if (isSpecialGoods(partnerId, storeId, userId, appId, goodsId, orderType)) {
                hasSpecialGoods = true;
                break;
            }
        }
        return hasSpecialGoods;
    }

    /**
     * 判断一个商品是不是特价商品
     *
     * @param partnerId
     * @param storeId
     * @param userId
     * @param appId
     * @param goodsId
     * @return
     */
    default boolean isSpecialGoods(String partnerId, String storeId, String userId, String appId, String goodsId, Integer orderType) {
        boolean isSpecialGoods = false;
        ActivityAdapter activityAdapter = SDKCommonBaseContextWare.getBean(ActivityAdapter.class);
        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, userId, appId, orderType);
        ActivityService activityService = SDKCommonBaseContextWare.getBean(ActivityService.class);
        ActivityQueryResponseDto activityQueryResponseDto = activityService.queryActivitys(activityQueryDto, ActivityTypeEnum.TYPE_2, null);

        if (activityQueryResponseDto == null || activityQueryResponseDto.getResult() == null) {
            return isSpecialGoods;
        }

        List<ActivityResponseDto> activityResponseDtoList = activityQueryResponseDto.getResult();
        for (int i = 0, len = activityResponseDtoList.size(); i < len; i++) {
            List<GoodsBeanDto> goodsBeanDtos = activityResponseDtoList.get(i).getGoods();
            if (CollectionUtils.isEmpty(goodsBeanDtos)) {
                continue;
            }
            boolean match = goodsBeanDtos.stream().anyMatch(k -> k.getGoodsId().equals(goodsId));
            if (match) {
                isSpecialGoods = true;
                break;
            }
        }
        return isSpecialGoods;

    }

    /**
     * 添加非商品券商品
     *
     * @param addShoppingCartGoodsRequestVo
     * @param cartGoods
     * @param goodsId
     * @param userId
     * @param shoppingCartGoodsResponseVo
     * @param allCartGoodsList
     */
    default void addNotProductGoods(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo, CartGoods cartGoods
            , String goodsId, String userId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, List<CartGoods> allCartGoodsList) {

        // 校验合法性,更新缓存中购物车信息
        updateCartGoodsLegal(cartGoods, userId, shoppingCartGoodsResponseVo, addShoppingCartGoodsRequestVo, allCartGoodsList);

        // 如果购物车中有商品券，则当前添加的商品是特价商品时，需要提示“已选商品券，与其他优惠商品不同享，商品将恢复原价”
        boolean haveCouponProduct = allCartGoodsList.parallelStream().anyMatch(k -> (StringUtils.isNotBlank(k.getCouponCode()) || k.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX)));
        if (haveCouponProduct && isSpecialGoods(addShoppingCartGoodsRequestVo.getPartnerId(), addShoppingCartGoodsRequestVo.getShopId(), userId, addShoppingCartGoodsRequestVo.getAppId(), goodsId, addShoppingCartGoodsRequestVo.getOrderType())) {
            // 如果购物车先加入商品券，再加入促销商品，toast提示“已选商品券，与其他优惠商品不同享，商品将恢复原价”
            setToastMsgIfNotExist(shoppingCartGoodsResponseVo, ShoppingCartConstant.HAS_GOODS_COUPON_WHEN_ADD_SPECIAL_GOODS);
        }
    }

    /**
     * 结算页获取加价购活动商品列表
     * @param request
     * @return
     */
    default BaseResponse<PremiumExchangeResponseVo> premiumExchange(PremiumExchangeRequestVo request){
        return null;
    };
}
