
package com.tmerclub.cloud.api.product.manager;

import com.google.common.collect.Lists;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.feign.OrderShopDetailFeignClient;
import com.tmerclub.cloud.common.order.util.OrderLangUtil;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车适配器
 * @author tmerclub
 * @date 2020/12/07
 */
@Component
public class ShopCartAdapter {

    @DubboReference
    private OrderShopDetailFeignClient orderShopDetailFeignClient;
    private static final Logger logger = LoggerFactory.getLogger(ShopCartAdapter.class);

    /**
     * 将参数转换成组装好的购物项
     * @param shopCartItems 订单参数
     * @return 组装好的购物项
     */
    public List<ShopCartVO> conversionShopCart(List<ShopCartItemVO> shopCartItems) {
        // 根据店铺ID划分item
        Map<Long, List<ShopCartItemVO>> shopCartMap = shopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemVO::getShopId));

        // 返回一个店铺的所有信息
        List<ShopCartVO> shopCarts = Lists.newArrayList();
        for (Long shopId : shopCartMap.keySet()) {
            // 构建每个店铺的购物车信息
            ShopCartVO shopCart = buildShopCart(shopId, shopCartMap.get(shopId));
            // 店铺信息
            ServerResponseEntity<ShopInfoInOrderVO> shopNameResponse = orderShopDetailFeignClient.getShopInfoInOrderByShopId(shopId);
            if (!shopNameResponse.isSuccess()) {
                logger.error("获取店铺信息失败，shopId:{}", shopId);
                throw new LuckException(shopNameResponse.getMsg());
            }
            ShopInfoInOrderVO shopInfo = shopNameResponse.getData();
            shopCart.setShopName(shopInfo.getShopName());
            shopCart.setShopType(shopInfo.getType());
            shopCarts.add(shopCart);
        }

        return shopCarts;
    }


    private ShopCartVO buildShopCart(Long shopId, List<ShopCartItemVO> shopCartItems) {

        ShopCartVO shopCart = new ShopCartVO();
        shopCart.setShopReduce(0L);
        shopCart.setDiscountReduce(0L);
        shopCart.setShopId(shopId);
        long total = 0L;
        long actualTotal = 0L;
        long reduce = 0L;
        int totalCount = 0;
        long scoreTotal = 0L;

        for (ShopCartItemVO shopCartItem : shopCartItems) {
            total += shopCartItem.getTotalAmount();
            actualTotal += shopCartItem.getActualTotal();
            reduce += shopCartItem.getShareReduce() != null ? shopCartItem.getShareReduce() : 0;
            totalCount += shopCartItem.getCount();
            scoreTotal += shopCartItem.getScorePrice();
        }

        ShopCartItemDiscountVO shopCartItemDiscountVO = new ShopCartItemDiscountVO();
        shopCartItemDiscountVO.setShopCartItems(shopCartItems);
        // 用于后续组装组合商品
        Set<Long> comboSkuIds = shopCartItems.stream().map(ShopCartItemVO::getMainComboSkuId).filter(mainComboSkuId -> Objects.nonNull(mainComboSkuId)).collect(Collectors.toSet());
        shopCartItemDiscountVO.setComboMainSkuIds(comboSkuIds);
        shopCart.setShopCartItemDiscounts(Collections.singletonList(shopCartItemDiscountVO));
        shopCart.setTotal(total);
        shopCart.setTotalCount(totalCount);
        shopCart.setActualTotal(actualTotal);
        shopCart.setDiscountReduce(0L);
        shopCart.setShopReduce(reduce);
        shopCart.setScoreTotal(scoreTotal);
        return shopCart;
    }

    /**
     * 不可配送的商品添加店铺名称
     * @param shopCartOrderMerger 订单信息
     */
    public void setFilterShopItemsLong(ShopCartOrderMergerVO shopCartOrderMerger) {
        List<ShopCartItemVO> filterShopItemList = shopCartOrderMerger.getFilterShopItems();
        // 购物车项添加店铺名称
        OrderLangUtil.shopCartItemList(filterShopItemList);
        for (ShopCartItemVO shopCartItemVO : filterShopItemList) {
            if (Objects.equals(shopCartItemVO.getShopId(), 0L)) {
                logger.info("店铺名称 平台是官方店");
                shopCartItemVO.setShopName("官方店");
                continue;
            }
            ServerResponseEntity<ShopInfoInOrderVO> shopNameResponse = orderShopDetailFeignClient.getShopInfoInOrderByShopId(shopCartItemVO.getShopId());
            if (!shopNameResponse.isSuccess()) {
                logger.error("店铺名称获取失败");
                throw new LuckException(shopNameResponse.getMsg());
            }
            ShopInfoInOrderVO shopInfo = shopNameResponse.getData();
            shopCartItemVO.setShopName(shopInfo.getShopName());
        }
    }
}
