package com.yami.shop.distribution.multishop.listener;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.event.OrderRefundSuccessEvent;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.distribution.comment.Enums.DistributionUserIncomeStateEnum;
import com.yami.shop.distribution.comment.dao.DistributionUserIncomeMapper;
import com.yami.shop.distribution.comment.dao.DistributionUserWalletMapper;
import com.yami.shop.distribution.comment.model.DistributionUserIncome;
import com.yami.shop.distribution.comment.model.DistributionUserWallet;
import com.yami.shop.distribution.comment.model.DistributionUserWalletBill;
import com.yami.shop.distribution.comment.service.DistributionUserWalletBillService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

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

/**
 * 退款订单监听
 */
@Component("orderRefundListener")
@AllArgsConstructor
public class OrderRefundListener {

    private final DistributionUserIncomeMapper distributionUserIncomeMapper;

    private final DistributionUserWalletMapper distributionUserWalletMapper;

    private final DistributionUserWalletBillService distributionUserWalletBillService;


    @EventListener(OrderRefundSuccessEvent.class)
    public void orderRefundSuccessEvent(OrderRefundSuccessEvent event) {
        OrderRefundDto orderRefundDto = event.getOrderRefundDto();

        if (CollectionUtils.isEmpty(orderRefundDto.getOrderItems())) {
            return;
        }
        // 查看是否有分销订单
        List<OrderItem> distributionOrderItemList = orderRefundDto.getOrderItems().stream().filter(orderItem -> StrUtil.isNotEmpty(orderItem.getDistributionCardNo())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(distributionOrderItemList)) {
            return;
        }
        // 处理分销订单
        List<DistributionUserIncome> updateBatchDistributionUserIncomeList = new ArrayList<>();
        List<DistributionUserWalletBill> saveBatchDistributionWalletBillList = new ArrayList<>();
        // 更新订单收入信息
        for (OrderItem orderItem : distributionOrderItemList) {
            // 减少分销员的待结算金额，添加已失效金额
            List<DistributionUserIncome> distributionUserIncomeList = distributionUserIncomeMapper.selectList(new LambdaQueryWrapper<DistributionUserIncome>().eq(DistributionUserIncome::getOrderItemId, orderItem.getOrderItemId()));
            for (DistributionUserIncome distributionUserIncome : distributionUserIncomeList) {
                DistributionUserWallet distributionUserWallet = distributionUserWalletMapper.selectById(distributionUserIncome.getWalletId());
                if (distributionUserWallet == null) {
                    throw new GlobalException("未找到分销员信息");
                }

                // 添加分销钱包日志
                distributionUserWallet.setUnsettledAmount(Arith.sub(distributionUserWallet.getUnsettledAmount(), distributionUserIncome.getIncomeAmount()));
                distributionUserWallet.setInvalidAmount(Arith.add(distributionUserWallet.getInvalidAmount(), distributionUserIncome.getIncomeAmount()));
                distributionUserWalletMapper.updateById(distributionUserWallet);

                // 更新收入状态
                updateBatchDistributionUserIncomeList.add(distributionUserIncome);

                // 添加钱包变动日志
                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "分销订单退款失效奖励", -distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0.0, 0));
            }
        }

        // 批量更新分销收入状态
        if (CollectionUtils.isNotEmpty(updateBatchDistributionUserIncomeList)) {
            if (distributionUserIncomeMapper.updateBatchState(updateBatchDistributionUserIncomeList, DistributionUserIncomeStateEnum.INVALID.getValue()) <= 0) {
                throw new GlobalException("批量更新分销收入状态失败");
            }
        }

        // 批量添加钱包变动日志
        if (CollectionUtils.isNotEmpty(saveBatchDistributionWalletBillList)) {
            distributionUserWalletBillService.saveBatch(saveBatchDistributionWalletBillList);
        }
    }
}
