
package com.tmerclub.cloud.order.listener;

import com.tmerclub.cloud.api.multishop.bo.OrderChangeShopWalletAmountBO;
import com.tmerclub.cloud.api.order.constant.PurchaseOrderWaitStatus;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.order.bo.PayRefundBO;
import com.tmerclub.cloud.common.order.vo.OrderItemVO;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.constant.DistributedIdKey;
import com.tmerclub.cloud.order.constant.RefundInterventionType;
import com.tmerclub.cloud.order.constant.RefundType;
import com.tmerclub.cloud.order.model.Order;
import com.tmerclub.cloud.order.service.OrderItemService;
import com.tmerclub.cloud.order.service.OrderService;
import com.tmerclub.cloud.order.vo.OrderRefundVO;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author tmerclub
 * @date 2021/1/7
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ORDER_REFUND_TOPIC, consumerGroup = RocketMqConstant.ORDER_REFUND_TOPIC)
public class OrderRefundConsumer implements RocketMQListener<OrderRefundVO> {

    @Autowired
    private RocketMQTemplate orderRefundPaymentTemplate;
    @Autowired
    private RocketMQTemplate orderRefundShopTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private SegmentManager segmentManager;

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

    @Override
    public void onMessage(OrderRefundVO orderRefundVo) {
        LOG.info("订单退款{}", orderRefundVo);

        PayRefundBO payRefundBO = new PayRefundBO();
        payRefundBO.setRefundId(orderRefundVo.getRefundId());
        payRefundBO.setRefundAmount(orderRefundVo.getRefundAmount());
        payRefundBO.setAllinpayRefundPurchaseAmount(orderRefundVo.getAllinpayRefundPurchaseAmount());
        payRefundBO.setOrderId(orderRefundVo.getOrderId());
        payRefundBO.setPayId(orderRefundVo.getPayId());
        payRefundBO.setPayIds(orderRefundVo.getPayIds());
        payRefundBO.setShopId(orderRefundVo.getShopId());
        SendStatus sendPaymentStatus = null;
        // 未成团退款的订单已经处理过了，不需要再处理
        if (!Objects.equals(orderRefundVo.getUnSuccessGroupOrder(), 1)) {
            // 发送退款服务进行退款的通知
            sendPaymentStatus = orderRefundPaymentTemplate.syncSend(RocketMqConstant.ORDER_REFUND_PAYMENT_TOPIC, new GenericMessage<>(payRefundBO)).getSendStatus();
        }
        // 如果是待采购的订单，商家平台供应商不用退钱
        if (Objects.equals(orderRefundVo.getWaitPurchase(), 1)) {
            return;
        }
        // 锁定商家钱包结算金额
        OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = getOrderChangeShopWalletAmountBO(orderRefundVo);

        // 生成钱包id
        int num = 1;
        if (!Objects.equals(orderChangeShopWalletAmountBO.getSupplierHandleStatus(), -1)) {
            LOG.info("非商家自行处理{}", orderChangeShopWalletAmountBO.getSupplierHandleStatus());
            num++;
        }
        boolean checkPlatformRefundType = Objects.isNull(orderChangeShopWalletAmountBO.getInterventionRefundType()) || !Objects.equals(orderChangeShopWalletAmountBO.getInterventionRefundType(),2);
        if (!checkPlatformRefundType) {
            LOG.info("退款平台介入且同意为商家供应商承担{}", orderChangeShopWalletAmountBO);
            num++;
        }
        // 店铺记录id
        if (Objects.equals(orderChangeShopWalletAmountBO.getWaitPurchase(), PurchaseOrderWaitStatus.PURCHASED.value())) {
            LOG.info("采购完成{}", orderChangeShopWalletAmountBO.getWaitPurchase());
            num++;
        }
        if (Objects.nonNull(orderChangeShopWalletAmountBO.getSupplierId()) && !Objects.equals(orderChangeShopWalletAmountBO.getSupplierId(), 0L)) {
            LOG.info("供应商id不为空{}", orderChangeShopWalletAmountBO.getSupplierId());
            num++;
        }
        // 生成店铺钱包日志id列表
        List<Long> ids = segmentManager.listSegmentId(DistributedIdKey.tmerclub_SHOP_WALLET_LOG, num);
        // 平台介入同意退款商家承担的时候,设置一下只能自行处理
        if(Objects.equals(orderRefundVo.getInterventionRefundType(), RefundInterventionType.SHOP.value())){
            orderChangeShopWalletAmountBO.setSupplierHandleStatus(-1);
        }
        orderChangeShopWalletAmountBO.setInterventionRefundType(orderRefundVo.getInterventionRefundType());
        orderChangeShopWalletAmountBO.setWalletLogIds(ids);
        // 减少商家待结算金额
        SendStatus sendShopStatus = orderRefundShopTemplate.syncSend(RocketMqConstant.ORDER_REFUND_SHOP_TOPIC, new GenericMessage<>(orderChangeShopWalletAmountBO)).getSendStatus();

        if (Objects.nonNull(sendPaymentStatus) && !Objects.equals(sendPaymentStatus, SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }

        if (!Objects.equals(sendShopStatus, SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
    }


    /**
     * 获取订单待结算金额
     */
    private OrderChangeShopWalletAmountBO getOrderChangeShopWalletAmountBO(OrderRefundVO orderRefundVO) {

        // 同意退款，判断商家是否还有金额进行退款
        Order order = orderService.getByOrderId(orderRefundVO.getOrderId());
        if (order == null) {
            throw new LuckException("未找到该订单信息");
        }

        // 实付金额
        Long actualTotal;
        Long platformCommission;
        Double rate = 0.0;
        Long distributionAmount;
        long shopAllowanceAmount;
        if (Objects.equals(orderRefundVO.getRefundType(), RefundType.ALL.value())) {
            actualTotal = order.getActualTotal();
            platformCommission = order.getPlatformCommission();
            distributionAmount = order.getDistributionAmount();
            shopAllowanceAmount = order.getReduceAmount() - order.getPlatformAmount();
        } else {
            OrderItemVO item = orderItemService.getByOrderItemId(orderRefundVO.getOrderItemId());
            actualTotal = item.getActualTotal();
            // 平台佣金
            platformCommission = item.getPlatformCommission();
            rate = item.getRate();
            shopAllowanceAmount = item.getShareReduce() - item.getPlatformShareReduce();
            distributionAmount = item.getDistributionAmount() + item.getDistributionParentAmount();
        }


        OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = new OrderChangeShopWalletAmountBO();
        orderChangeShopWalletAmountBO.setOrderStatus(order.getStatus());
        orderChangeShopWalletAmountBO.setActualTotal(actualTotal);
        orderChangeShopWalletAmountBO.setRefundAmount(orderRefundVO.getRefundAmount());
        orderChangeShopWalletAmountBO.setPlatformAllowanceAmount(orderRefundVO.getPlatformRefundAmount());
        orderChangeShopWalletAmountBO.setShopAllowanceAmount(shopAllowanceAmount);
        orderChangeShopWalletAmountBO.setOrderId(order.getOrderId());
        orderChangeShopWalletAmountBO.setRefundId(orderRefundVO.getRefundId());
        orderChangeShopWalletAmountBO.setShopId(orderRefundVO.getShopId());
        orderChangeShopWalletAmountBO.setOrderItemId(orderRefundVO.getOrderItemId());
        orderChangeShopWalletAmountBO.setPlatformCommission(platformCommission);
        orderChangeShopWalletAmountBO.setChangePlatformCommission(orderRefundVO.getPlatformRefundCommission());
        orderChangeShopWalletAmountBO.setRate(rate);
        orderChangeShopWalletAmountBO.setDistributionAmount(distributionAmount);
        orderChangeShopWalletAmountBO.setFreightAmount(orderRefundVO.getFreightAmount());
        orderChangeShopWalletAmountBO.setWaitPurchase(order.getWaitPurchase());
        orderChangeShopWalletAmountBO.setPlatformFreeFreightAmount(order.getPlatformFreeFreightAmount());
        // 供应商相关
        orderChangeShopWalletAmountBO.setSupplierFreightAmount(orderRefundVO.getSupplierFreightAmount());
        orderChangeShopWalletAmountBO.setSupplierHandleStatus(orderRefundVO.getSupplierHandleStatus());
        orderChangeShopWalletAmountBO.setSupplierId(order.getSupplierId());
        orderChangeShopWalletAmountBO.setChangePurchaseAmount(orderRefundVO.getPurchaseRefundAmount());
        orderChangeShopWalletAmountBO.setChangePurchasePlatformCommission(orderRefundVO.getPurPlatformRefundCommission());
        orderChangeShopWalletAmountBO.setLastOrder(orderRefundVO.isLastOrder());
        orderChangeShopWalletAmountBO.setPaySysType(order.getPaySysType());

        orderChangeShopWalletAmountBO.setInterventionRefundType(orderRefundVO.getInterventionRefundType());

        return orderChangeShopWalletAmountBO;
    }
}
