
package com.tmerclub.cloud.order.controller.app;


import com.tmerclub.cloud.api.delivery.dto.CalculateAndGetDeliverInfoDTO;
import com.tmerclub.cloud.api.order.manager.ConfirmOrderManager;
import com.tmerclub.cloud.api.product.manager.ShopCartAdapter;
import com.tmerclub.cloud.api.product.manager.ShopCartItemAdapter;
import com.tmerclub.cloud.api.user.feign.UserLevelAndScoreOrderFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.constant.DeliveryType;
import com.tmerclub.cloud.common.order.constant.OrderType;
import com.tmerclub.cloud.common.order.dto.DvyTypeDTO;
import com.tmerclub.cloud.common.order.dto.OrderDTO;
import com.tmerclub.cloud.common.order.util.OrderLangUtil;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.product.constant.SpuMold;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.delivery.manager.DeliveryManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 积分商城接口
 *
 * @author YXF
 * @date 2021-08-24
 */
@RestController
@RequestMapping("/score_order")
@Tag(name = "积分商品订单接口")
public class ScoreOrderController {

    private final Logger LOGGER = LoggerFactory.getLogger(ScoreOrderController.class);
    @Autowired
    private ShopCartAdapter shopCartAdapter;
    @Autowired
    private ConfirmOrderManager confirmOrderManager;
    @Autowired
    private ShopCartItemAdapter shopCartItemAdapter;
    @Autowired
    private DeliveryManager deliveryManager;
    @DubboReference
    private UserLevelAndScoreOrderFeignClient userLevelAndScoreOrderFeignClient;

    /**
     * 积分商品购买
     */
    @PostMapping("/confirm")
    @Operation(summary = "购买，生成订单信息", description = "传入下单所需要的参数进行下单")
    public ServerResponseEntity<ShopCartOrderMergerVO> confirm(@Valid @RequestBody OrderDTO orderParam) {
        if (Objects.isNull(orderParam.getShopCartItem())) {
            LOGGER.error("shopCartItem不能为空");
            throw new LuckException("shopCartItem不能为空");
        }
        Long userId = AuthUserContext.get().getUserId();
        // 将要返回给前端的完整的订单信息
        ShopCartOrderMergerVO shopCartOrderMerger = new ShopCartOrderMergerVO();
        // 积分商品只有快递发货
        List<DvyTypeDTO> dvyTypeDTOList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        dvyTypeDTOList.add(new DvyTypeDTO(0L, DeliveryType.DELIVERY.value()));
        shopCartOrderMerger.setDvyTypes(dvyTypeDTOList);
        shopCartOrderMerger.setOrderType(OrderType.SCORE);
        shopCartOrderMerger.setSpuMold(SpuMold.REAL.value());

        List<ShopCartItemVO> shopCartItemsDb = shopCartItemAdapter.conversionShopCartItem(orderParam.getShopCartItem(), null, userId, orderParam.getDvyTypes());
        // 获取用户地址信息
        UserDeliveryInfoVO userDeliveryInfoVO = confirmOrderManager.getUserDeliveryInfoVO(shopCartItemsDb, userId, orderParam);
        // 筛选过滤掉不同配送的商品
        List<ShopCartItemVO> shopCartItems = confirmOrderManager.filterShopItemsByType(shopCartOrderMerger, userDeliveryInfoVO, shopCartItemsDb);

        OrderLangUtil.shopCartItemList(shopCartItemsDb);

        // 购物车
        List<ShopCartVO> shopCarts = shopCartAdapter.conversionShopCart(shopCartItems);

        // 积分商品没有优惠活动信息，不需要异步
        ServerResponseEntity<UserDeliveryInfoVO> userDeliveryInfoResponseEntity = deliveryManager.calculateAndGetDeliverInfo(new CalculateAndGetDeliverInfoDTO(shopCartItems, userDeliveryInfoVO));

        // 处理完优惠活动，插入订单项库存区域id
        confirmOrderManager.handleShopCartStockPoint(userDeliveryInfoVO, shopCarts, shopCartItemsDb, shopCartOrderMerger.getMold());

        // 当算完一遍店铺的各种满减活动时，重算一遍订单金额
        confirmOrderManager.recalculateAmountWhenFinishingCalculateShop(shopCartOrderMerger, shopCarts, userDeliveryInfoResponseEntity.getData());
        long orderShopReduce = shopCartOrderMerger.getOrderReduce();

        // ===============================================开始平台优惠的计算==================================================

        // 会员等级优惠
        ServerResponseEntity<ShopCartOrderMergerVO> calculateLevelDiscountResponseEntity = userLevelAndScoreOrderFeignClient.calculateLevelAndScoreDiscount(shopCartOrderMerger);
        if (!calculateLevelDiscountResponseEntity.isSuccess()) {
            LOGGER.error("会员等级优惠计算失败，原因：{}", calculateLevelDiscountResponseEntity.getMsg());
            return ServerResponseEntity.transform(calculateLevelDiscountResponseEntity);
        }
        shopCartOrderMerger = calculateLevelDiscountResponseEntity.getData();

        // 重新插入spu、sku
        Map<Long, ShopCartItemVO> shopCartItemMap = shopCartItemsDb.stream().collect(Collectors.toMap(ShopCartItemVO::getSkuId, s -> s));
        for (ShopCartOrderVO shopCartOrder : shopCartOrderMerger.getShopCartOrders()) {
            shopCartOrder.setShopName(Constant.PLATFORM_SHOP_NAME);
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    ShopCartItemVO shopCartItemVO = shopCartItemMap.get(shopCartItem.getSkuId());
                    shopCartItem.setSkuLangList(shopCartItemVO.getSkuLangList());
                    shopCartItem.setSpuLangList(shopCartItemVO.getSpuLangList());
                }
            }
        }
        shopCartOrderMerger.setOrderShopReduce(orderShopReduce);
        // 缓存计算新
        confirmOrderManager.cacheCalculatedInfo(userId, shopCartOrderMerger);

        // 无法配送的商品添加商品详细和店铺详细
        shopCartAdapter.setFilterShopItemsLong(shopCartOrderMerger);
        return ServerResponseEntity.success(shopCartOrderMerger);
    }
}
