
package com.tmerclub.cloud.multishop.feign;

import com.alibaba.fastjson2.JSON;
import com.tmerclub.cloud.api.multishop.feign.WalletLogOperationFeignClient;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.bo.EsOrderBO;
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.vo.ShopSubstituteSalesVO;
import com.tmerclub.cloud.multishop.service.ShopSubstituteSalesService;
import com.tmerclub.cloud.multishop.service.ShopWalletService;
import com.tmerclub.cloud.multishop.service.WalletLogOperationService;
import com.tmerclub.cloud.multishop.vo.ShopWalletVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

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

/**
 * @author chiley
 * @date 2022/6/30 16:55
 */
@DubboService
public class WalletLogOperationFeignController implements WalletLogOperationFeignClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(WalletLogOperationFeignController.class);

    @Autowired
    private MongoTemplate mongoTemplate;
    @DubboReference
    private OrderFeignClient orderFeignClient;
    @Autowired
    private WalletLogOperationService walletLogOperationService;
    @Autowired
    private ShopWalletService shopWalletService;
    @Autowired
    private ShopSubstituteSalesService shopSubstituteSalesService;

    @Override
    public void addSupplierLog(String st) {
        List<EsOrderBO> orderBOList = JSON.parseArray(st, EsOrderBO.class);
        Set<Long> shopIds = orderBOList.stream().map(EsOrderBO::getShopId).collect(Collectors.toSet());
        // 根据shopIds获取商家的代销配置
        List<ShopSubstituteSalesVO> shopSubstituteSalesList = shopSubstituteSalesService.listByShopIds(new ArrayList<>(shopIds));
        Map<Long, Integer> salesMap = shopSubstituteSalesList.stream().collect(Collectors.toMap(ShopSubstituteSalesVO::getShopId, ShopSubstituteSalesVO::getOrderShape));

        for (EsOrderBO esOrderBO : orderBOList) {
            try {
                PayNotifyBO message = new PayNotifyBO();
                message.setOrderIds(Collections.singletonList(esOrderBO.getOrderId()));
                // 添加未结算记录
                // 采购订单不分账
                if (Objects.equals(message.getIsPurchaseOrder(), Boolean.TRUE)) {
                    continue;
                }
                // 定金预售订单付定金时不用全部分账
                boolean isPreSale = Objects.nonNull(message.getPreSaleType()) && Objects.equals(message.getPreSaleType(), PreSaleType.DEPOSIT.value())
                        && Objects.equals(message.getOrderStatus(), OrderStatus.UNPAY.value());
                if (isPreSale) {
                    continue;
                }

                ServerResponseEntity<List<OrderSimpleAmountInfoBO>> ordersShopWalletInfoResponse = orderFeignClient.getOrdersSimpleAmountInfo(message.getOrderIds());
                if (!ordersShopWalletInfoResponse.isSuccess()) {
                    throw new LuckException(ResponseEnum.EXCEPTION);
                }
                List<OrderSimpleAmountInfoBO> orderShopWalletInfos = ordersShopWalletInfoResponse.getData();
                // 获取店铺已结算金额map
                List<ShopWalletVO> shopWalletList = shopWalletService.listByShopIds(new ArrayList<>(shopIds), esOrderBO.getPaySysType());
                Map<Long, Long> settledAmountMap = shopWalletList.stream().collect(Collectors.toMap(ShopWalletVO::getShopId, ShopWalletVO::getSettledAmount));
                // 筛选掉需要采购和采购完成的
                orderShopWalletInfos = orderShopWalletInfos.stream().filter(orderSimpleAmountInfoBO -> Objects.equals(orderSimpleAmountInfoBO.getWaitPurchase(), 0)).collect(Collectors.toList());
                message.setAgreePurchase(1);
                walletLogOperationService.addAmountByOrder(orderShopWalletInfos, message, settledAmountMap, salesMap);


                // ============================================已结算记录============================================

                if (Objects.equals(esOrderBO.getIsSettled(), 1)) {
                    walletLogOperationService.addAmountBySettledOrder(esOrderBO.getOrderId());
                }
            } catch (Exception e) {
                LOGGER.error("异常", e);
            }

        }
    }

}
