
package com.tmerclub.cloud.multishop.listener;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.bo.PayNotifyBO;
import com.tmerclub.cloud.common.order.vo.OrderSimpleAmountInfoBO;
import com.tmerclub.cloud.common.product.constant.PreSaleType;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.common.vo.ShopSubstituteSalesVO;
import com.tmerclub.cloud.multishop.service.ShopSubstituteSalesService;
import com.tmerclub.cloud.multishop.service.ShopWalletService;
import com.tmerclub.cloud.multishop.vo.ShopWalletVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @author tmerclub
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ORDER_NOTIFY_SERVICE_TOPIC, consumerGroup = RocketMqConstant.ORDER_NOTIFY_SHOP_GROUP)
public class OrderNotifyShopConsumer implements RocketMQListener<PayNotifyBO> {

    private static final Logger LOG = LoggerFactory.getLogger(OrderNotifyShopConsumer.class);

    @Autowired
    private ShopWalletService shopWalletService;

    @Autowired
    private ShopSubstituteSalesService shopSubstituteSalesService;

    @DubboReference
    private OrderFeignClient orderFeignClient;


    /**
     * 订单支付成功 分账
     */
    @Override
    public void onMessage(PayNotifyBO message) {
        // 定金预售订单付定金时不用全部分账
        boolean isPreSale = Objects.nonNull(message.getPreSaleType()) && Objects.equals(message.getPreSaleType(), PreSaleType.DEPOSIT.value())
                && Objects.equals(message.getOrderStatus(), OrderStatus.UNPAY.value());
        if (isPreSale) {
            return;
        }
        LOG.info("订单支付成功，分账... message:{} ", Json.toJsonString(message));

        ServerResponseEntity<List<OrderSimpleAmountInfoBO>> ordersShopWalletInfoResponse = orderFeignClient.getOrdersSimpleAmountInfo(message.getOrderIds());
        if (!ordersShopWalletInfoResponse.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        List<OrderSimpleAmountInfoBO> orderShopWalletInfos = ordersShopWalletInfoResponse.getData();
        List<Long> shopIds = orderShopWalletInfos.stream().map(OrderSimpleAmountInfoBO::getShopId).collect(Collectors.toList());
        List<Long> defaultShopIds = orderShopWalletInfos.stream().filter(o -> Objects.equals(o.getPaySysType(), PaySysType.DEFAULT.value())).map(OrderSimpleAmountInfoBO::getShopId).collect(Collectors.toList());
        List<Long> allinpayShopIds = orderShopWalletInfos.stream().filter(o -> Objects.equals(o.getPaySysType(), PaySysType.ALLINPAY.value())).map(OrderSimpleAmountInfoBO::getShopId).collect(Collectors.toList());
        // 获取店铺已结算金额map
        Map<String, Long> settledAmountMap = new HashMap<>(Constant.INITIAL_CAPACITY);
        if (CollUtil.isNotEmpty(allinpayShopIds)) {
            List<ShopWalletVO> allinpayList = shopWalletService.listByShopIds(allinpayShopIds, PaySysType.ALLINPAY.value());
            for (ShopWalletVO shopWalletVO : allinpayList) {
                settledAmountMap.put(shopWalletVO.getShopId() + ":" + PaySysType.ALLINPAY.value(), shopWalletVO.getSettledAmount());
            }
        }
        if (CollUtil.isNotEmpty(defaultShopIds)) {
            List<ShopWalletVO> shopWalletList = shopWalletService.listByShopIds(defaultShopIds, PaySysType.DEFAULT.value());
            for (ShopWalletVO shopWalletVO : shopWalletList) {
                settledAmountMap.put(shopWalletVO.getShopId() + ":" + PaySysType.DEFAULT.value(), shopWalletVO.getSettledAmount());
            }
        }
        // 根据shopIds获取商家的代销配置
        List<ShopSubstituteSalesVO> shopSubstituteSalesList = shopSubstituteSalesService.listByShopIds(shopIds);
        Map<Long, Integer> salesMap = shopSubstituteSalesList.stream().collect(Collectors.toMap(ShopSubstituteSalesVO::getShopId, ShopSubstituteSalesVO::getOrderShape));
        // 筛选掉需要采购和采购完成的
        orderShopWalletInfos = orderShopWalletInfos.stream().filter(orderSimpleAmountInfoBO -> Objects.equals(orderSimpleAmountInfoBO.getWaitPurchase(), 0)).collect(Collectors.toList());
        shopWalletService.addAmountByOrder(orderShopWalletInfos, message, settledAmountMap, salesMap);
    }
}
