
package com.tmerclub.cloud.feign;

import com.tmerclub.cloud.api.feign.MarketingFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.order.vo.CouponOrderVO;
import com.tmerclub.cloud.common.order.vo.ShopCartItemDiscountVO;
import com.tmerclub.cloud.common.order.vo.ShopCartItemVO;
import com.tmerclub.cloud.common.order.vo.ShopCartVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.coupon.service.CouponService;
import com.tmerclub.cloud.coupon.util.ChooseCouponHelper;
import com.tmerclub.cloud.discount.manager.DiscountConfirmOrderManager;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author tmerclub
 */
@DubboService
public class MarketingFeignController implements MarketingFeignClient {

    public static final Logger log = LoggerFactory.getLogger(MarketingFeignController.class);

    @Autowired
    private CouponService couponService;
    @Autowired
    private DiscountConfirmOrderManager discountConfirmOrderManager;


    @Override
    public List<ShopCartVO> calculateMarketingAndMakeUpShopCart(List<ShopCartVO> shopCarts, List<Long> couponIds, Integer userChangeCoupon) {
        // 计算优惠券和套餐活动
        shopCarts = discountConfirmOrderManager.calculateDiscountAndMakeUpShopCartAndAmount(shopCarts);
        // 选择商家优惠券
        chooseShopCoupon(shopCarts, couponIds, userChangeCoupon);
        return shopCarts;
    }

    @Override
    public ServerResponseEntity checkComboActivity(List<ShopCartItemDiscountVO> shopCartItemDiscountVOList) {
        return discountConfirmOrderManager.checkComboActivity(shopCartItemDiscountVOList);
    }


    /**
     * 选择商家优惠券
     * @param shopCarts 购物车信息
     * @param couponIds 优惠券id数组
     * @param userChangeCoupon 用户是否改变了优惠券的选择，如果用户改变了优惠券的选择，则完全根据传入参数进行优惠券的选择
     */
    private void chooseShopCoupon(List<ShopCartVO> shopCarts, List<Long> couponIds, Integer userChangeCoupon) {
        // 优惠券
        Long userId = AuthUserContext.get().getUserId();

        for (ShopCartVO shopCart : shopCarts) {
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();
            List<ShopCartItemVO> shopCartItems = new ArrayList<>(Constant.INITIAL_CAPACITY);
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                shopCartItems.addAll(shopCartItemDiscount.getShopCartItems());
            }
            // 因为经过满减，实际金额的顺序已经变了
            shopCartItems = shopCartItems.stream().sorted(Comparator.comparingDouble(ShopCartItemVO::getActualTotal)).collect(Collectors.toList());

            // 获取用户有效的优惠券
            List<CouponOrderVO> shopCoupons = couponService.getCouponListByUserIdAndShopId(userId, shopCart.getShopId());

            // 用户选中的所有优惠券

            ChooseCouponHelper chooseCouponHelper = new ChooseCouponHelper(shopCartItems, shopCoupons, couponIds, userChangeCoupon).invoke();

            if (chooseCouponHelper.getChooseCoupon() != null) {
                log.info("用户选择的优惠券：{}", chooseCouponHelper.getChooseCoupon());
                long couponReduce = chooseCouponHelper.getCouponReduce();
                // 最后组装订单信息
                shopCart.setCouponReduce(couponReduce);
                shopCart.setActualTotal(shopCart.getActualTotal() - shopCart.getCouponReduce());
                shopCart.setShopReduce(shopCart.getShopReduce() + shopCart.getCouponReduce());
            }

            shopCart.setCoupons(shopCoupons);
        }
    }

}
