
package com.tmerclub.cloud.discount.feign;

import com.tmerclub.cloud.api.discount.constant.DiscountRule;
import com.tmerclub.cloud.api.discount.feign.DiscountFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.product.vo.SpuDiscountAppVO;
import com.tmerclub.cloud.common.product.vo.search.SpuDiscountItemAppVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Arith;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.common.util.BooleanUtil;
import com.tmerclub.cloud.common.util.PriceUtil;
import com.tmerclub.cloud.discount.manager.DiscountConfirmOrderManager;
import com.tmerclub.cloud.discount.service.DiscountService;
import com.tmerclub.cloud.discount.vo.DiscountVO;
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.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author tmerclub
 */
@DubboService
public class DiscountFeignController implements DiscountFeignClient {

    @Autowired
    private DiscountService discountService;
    @Autowired
    private DiscountConfirmOrderManager discountConfirmOrderManager;

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


    @Override
    public ServerResponseEntity<ShopCartWithAmountVO> calculateDiscountAndMakeUpShopCartAndAmount(ShopCartWithAmountVO shopCartWithAmountVO) {
        List<ShopCartVO> shopCarts = shopCartWithAmountVO.getShopCarts();

        shopCarts = discountConfirmOrderManager.calculateDiscountAndMakeUpShopCartAndAmount(shopCarts);


        long total = 0L;
        int count = 0;
        long reduce = 0L;
        long totalTransfee = 0L;
        long totalFreeTransfee = 0L;
        ShopCartWithAmountVO shopCartWithAmount = new ShopCartWithAmountVO();
        for (ShopCartVO shopCart : shopCarts) {
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();

            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                ChooseDiscountItemVO chooseDiscountItemVO = shopCartItemDiscount.getChooseDiscountItem();
                if (Objects.nonNull(chooseDiscountItemVO)) {
                    Long needPiece = getNeedPiece(chooseDiscountItemVO);

                    reduce = getReduce(reduce, chooseDiscountItemVO, needPiece);
                }

                for (ShopCartItemVO shopCartItem : shopCartItems) {
                    if (!BooleanUtil.isTrue(shopCartItem.getIsChecked())) {
                        continue;
                    }
                    count += shopCartItem.getCount();
                    total += shopCartItem.getTotalAmount();
                    if (Objects.nonNull(shopCartItem.getComboAmount())) {
                        //如果是套餐商品需要减去套餐优惠金额
                        reduce += shopCartItem.getComboAmount();
                    }
                    // 前端页面套餐商品小计显示（套餐商品计算套餐价）
                    if (Objects.nonNull(shopCartItem.getComboId()) && shopCartItem.getComboId() > 0) {
                        log.info("套餐商品重新计算总金额");
                        double totalAmount = Arith.mul(shopCartItem.getSkuPriceFee(), shopCartItem.getCount());
                        shopCartItem.setTotalAmount((long) totalAmount);
                    }
                }
            }

            recalculate(shopCartWithAmountVO, shopCart);
            totalFreeTransfee += shopCart.getFreeTransfee();
            totalTransfee += shopCart.getTransfee();
        }

        shopCartWithAmount.setCount(count);
        shopCartWithAmount.setTotalMoney(total);
        shopCartWithAmount.setSubtractMoney(reduce);
        shopCartWithAmount.setFinalMoney(total + totalTransfee - reduce);
        shopCartWithAmount.setFreeTransfee(totalFreeTransfee);
        shopCartWithAmount.setFreightAmount(totalTransfee);
        shopCartWithAmount.setShopCarts(shopCarts);


        return ServerResponseEntity.success(shopCartWithAmount);
    }

    @Override
    public ServerResponseEntity<List<SpuDiscountAppVO>> spuDiscountList(Long shopId, Long spuId) {
        List<DiscountVO> discountList = discountService.spuDiscountList(shopId, spuId);
        List<SpuDiscountAppVO> spuDiscountList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (DiscountVO discountVO : discountList) {
            SpuDiscountAppVO spuDiscount = new SpuDiscountAppVO();
            spuDiscount.setDiscountId(discountVO.getDiscountId());
            spuDiscount.setDiscountName(discountVO.getDiscountName());
            spuDiscount.setDiscountRule(discountVO.getDiscountRule());
            spuDiscount.setDiscountType(discountVO.getDiscountType());
            spuDiscount.setMaxReduceAmount(discountVO.getMaxReduceAmount());
            spuDiscount.setDiscountItemList(BeanUtil.mapAsList(discountVO.getDiscountItemList(), SpuDiscountItemAppVO.class));
            spuDiscountList.add(spuDiscount);
        }
        return ServerResponseEntity.success(spuDiscountList);
    }

    @Override
    public ServerResponseEntity<Void> handleSpuOffline(List<Long> spuIds, List<Long> shopIds) {
        discountService.handleSpuOffline(spuIds, shopIds);
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<Void> handleShopOffline(List<Long> shopIds) {
        discountService.handleShopOffline(shopIds);
        return ServerResponseEntity.success();
    }

    private static void recalculate(ShopCartWithAmountVO shopCartWithAmountVO, ShopCartVO shopCart) {
        Map<Long, ShopTransFeeVO> shopIdWithShopTransFee = null;
        if (Objects.nonNull(shopCartWithAmountVO.getUserDeliveryInfo())) {
            shopIdWithShopTransFee = shopCartWithAmountVO.getUserDeliveryInfo().getShopIdWithShopTransFee();
        }
        // 要计算运费
        if (shopIdWithShopTransFee != null && shopIdWithShopTransFee.containsKey(shopCart.getShopId())) {
            ShopTransFeeVO shopTransFeeVO = shopIdWithShopTransFee.get(shopCart.getShopId());

            // 店铺的实付 = 购物车实付 + 运费
            shopCart.setActualTotal(shopCart.getActualTotal() + shopTransFeeVO.getTransfee());
            // 店铺免运费金额
            shopCart.setFreeTransfee(shopTransFeeVO.getFreeTransfee());
            //店铺优惠金额 = 优惠金额  + 减免运费
            shopCart.setShopReduce(shopCart.getShopReduce() + shopTransFeeVO.getFreeTransfee());

            // 运费
            shopCart.setTransfee(shopTransFeeVO.getTransfee());
        } else {
            shopCart.setFreeTransfee(0L);
            shopCart.setTransfee(0L);
        }
    }

    private static long getReduce(long reduce, ChooseDiscountItemVO chooseDiscountItemVO, Long needPiece) {
        // 如果满足优惠活动
        if (Objects.equals(DiscountRule.M2M.value(), chooseDiscountItemVO.getDiscountRule()) && chooseDiscountItemVO.getNeedAmount() <= chooseDiscountItemVO.getProdsPrice()) {
            //满钱减钱
            reduce += chooseDiscountItemVO.getReduceAmount();
        } else if (Objects.equals(DiscountRule.P2D.value(), chooseDiscountItemVO.getDiscountRule()) && needPiece <= chooseDiscountItemVO.getCount()) {
            //满件打折
            reduce += chooseDiscountItemVO.getReduceAmount();
        }
        return reduce;
    }

    private static Long getNeedPiece(ChooseDiscountItemVO chooseDiscountItemVO) {
        Long needPiece = chooseDiscountItemVO.getNeedAmount();
        // 当规则为满件打折时 9.5折就是95、9.5元就是950，此时数据库存的是件数*100，还需除以100进行判断
        if (Objects.equals(DiscountRule.P2D.value(), chooseDiscountItemVO.getDiscountRule())) {
            needPiece = PriceUtil.toDecimalPrice(needPiece).longValue();
        }
        return needPiece;
    }


}
