package com.m2pool.lease.mq;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.lease.annotation.LedgerLog;
import com.m2pool.lease.annotation.LedgerLogParam;
import com.m2pool.lease.constant.RabbitmqConstant;
import com.m2pool.lease.entity.*;
import com.m2pool.lease.exception.PayRechargeException;
import com.m2pool.lease.mapper.*;
import com.m2pool.lease.mq.message.*;
import com.m2pool.lease.service.LeaseOrderItemService;
import com.m2pool.lease.utils.UuidGeneratorUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class MessageReceiver {

    @Resource
    private LeasePayWithdrawMessageMapper leasePayWithdrawMessageMapper;
    @Resource
    private LeasePayRechargeMessageMapper leasePayRechargeMessageMapper;
    @Resource
    private LeaseUserWalletDataMapper leaseUserWalletDataMapper;
    @Resource
    private LeasePayRecordMessageMapper leasePayRecordMessageMapper;
    @Resource
    private LeaseAutoAddressMapper leaseAutoAddressMapper;
    @Resource
    private LeaseOrderItemMapper leaseOrderItemMapper;
    @Resource
    private LeaseOrderItemService leaseOrderItemService;
    @Resource
    private LeaseShopConfigMapper leaseShopConfigMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;
    ///**
    // * 订单超时 消费者
    // */
    //@RabbitListener(queues = RabbitmqConstant.DEAD_LETTER_QUEUE_NAME)
    //@Transactional(rollbackFor = Exception.class)
    //public void orderOvertimeMessage(@Payload List<RabbitmqOrderMessage> message /**,Message amqpMessage */) {
    //    List<LeasePaymentRecord> leasePaymentRecords = leasePaymentRecordMapper.checkPaymentRecordStatus(message);
    //    List<LeasePaymentRecord> collect = leasePaymentRecords.stream()
    //            .filter(record -> record.getStatus() == 6)
    //            .peek(record-> record.setStatus(5))
    //            .collect(Collectors.toList());
    //    System.out.println("订单超时消费者"+collect);
    //    if (!collect.isEmpty()){
    //        //1. 修改支付订单状态为 6支付中 状态改为 5 订单已超时
    //        boolean b = leasePaymentRecordService.updateBatchById(collect);
    //        //2. 修改普通订单状态 6支付中 状态改为 5 订单已超时(普通订单和支付订单是同时创建的，所以用的同一个消息)
    //        Long orderId = collect.get(0).getOrderId();
    //        int i = leaseOrderInfoMapper.updateById(LeaseOrderInfo.builder().id(orderId).status(5).build());
    //        //3.修改该订单下状态为售出中的机器为可售出状态
    //        List<Long> orderStatusIsPayInData = leaseOrderItemMapper.getMachineByOrderStatusIsPayInData(leasePaymentRecords);
    //        //这里只更新机器售出状态为2 售出中的机器
    //        int update = leaseProductMachineMapper.update(LeaseProductMachine.builder().saleState(0).build(),
    //                new LambdaQueryWrapper<LeaseProductMachine>()
    //                        .eq(LeaseProductMachine::getSaleState, 2).in(LeaseProductMachine::getId, orderStatusIsPayInData));
    //
    //    }
    //    //try {
    //    //    // 手动确认消息
    //    //    channel.basicAck(amqpMessage.getMessageProperties().getDeliveryTag(), false);
    //    //} catch (Exception e) {
    //    //    try {
    //    //        // 拒绝消息，不重新入队
    //    //        channel.basicReject(amqpMessage.getMessageProperties().getDeliveryTag(), false);
    //    //    } catch (IOException ioException) {}
    //    //}
    //}


    /**
     * 支付 消费者
     * @param payAutoReturnMessage
     */
    @RabbitListener(queues = RabbitmqConstant.PAY_AUTO_RETURN_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    @Transactional(rollbackFor = Exception.class)
    public void listenerPayBalanceStatusQueueMessage(@Payload RabbitmqPayAutoReturnMessage payAutoReturnMessage) {
        System.out.println("支付消费者"+JSONUtil.toJsonPrettyStr(payAutoReturnMessage));
        //查找到数据库对应的支付记录 现在已经每日记录和总记录拆分开了，实际查出来的只会有一条记录
        List<LeasePayRecordMessage> leasePayRecordMessagesList = leasePayRecordMessageMapper.selectList(new LambdaQueryWrapper<LeasePayRecordMessage>()
                .eq(LeasePayRecordMessage::getQueueId, payAutoReturnMessage.getQueue_id()));
        if (leasePayRecordMessagesList.isEmpty()){
            return ;
        }
        //买家钱包
        LeasePayRecordMessage payRecordMessage = leasePayRecordMessagesList.get(0);

        LeaseUserWalletData buyer = leaseUserWalletDataMapper.selectOne(new LambdaQueryWrapper<LeaseUserWalletData>()
                .eq(LeaseUserWalletData::getFromAddress,payRecordMessage.getFromAddress())
                .eq(LeaseUserWalletData::getFromChain, payRecordMessage.getFromChain())
                .eq(LeaseUserWalletData::getFromSymbol, payRecordMessage.getFromSymbol())
                .eq(LeaseUserWalletData::getDel, false)
        );
        //获取初始余额和冻结余额
        BigDecimal initBalance = buyer.getBalance();
        BigDecimal initBlockBalance = buyer.getBlockedBalance();
        BigDecimal balance = buyer.getBalance().subtract(payAutoReturnMessage.getAmount());

        //支付成功修改order_item表实际支付金额
        for (LeasePayRecordMessage leasePayRecordMessage : leasePayRecordMessagesList) {
            BigDecimal blockBalance = buyer.getBlockedBalance().subtract(leasePayRecordMessage.getBlockAmount());
            leasePayRecordMessage.setUpdateTime(LocalDateTime.now());
            leasePayRecordMessage.setBlockHeight(payAutoReturnMessage.getBlock_height());
            leasePayRecordMessage.setRealAmount(payAutoReturnMessage.getAmount());
            //当天已存在支付的信息
            leasePayRecordMessage.setStatus(payAutoReturnMessage.getStatus());
            leasePayRecordMessage.setTxHash(payAutoReturnMessage.getTx_hash());
            List<LeaseOrderItem> needUpdateOrderItem = leaseOrderItemMapper.getNeedUpdateOrderItem(Long.valueOf(leasePayRecordMessage.getOrderId()));
            if(payAutoReturnMessage.getStatus() == 1){
                //支付成功 买家 钱包总余额 + 冻结余额 减少  卖家 钱包总余额增加
                buyer.setBalance(balance);
                buyer.setBlockedBalance(blockBalance);
                needUpdateOrderItem = needUpdateOrderItem.stream().peek(item ->{
                    item.setAlreadyPayRealAmount(item.getAlreadyPayRealAmount().add(item.getSettlePayRealAmount()));
                    item.setSettlePayRealAmount(BigDecimal.ZERO);
                }).collect(Collectors.toList());
            }
            if (payAutoReturnMessage.getStatus() == 0){
                buyer.setBlockedBalance(blockBalance);
                needUpdateOrderItem = needUpdateOrderItem.stream().peek(item ->{
                    item.setSettlePayRealAmount(BigDecimal.ZERO);
                }).collect(Collectors.toList());
            }
            //修改支付记录状态
            int i = leasePayRecordMessageMapper.updateById(leasePayRecordMessage);
            //支付成功修改order_item表实际支付金额
            boolean b = leaseOrderItemService.updateBatchById(needUpdateOrderItem);
            if (i < 1 || !b){
                throw new PayRechargeException("支付失败,该支付记录已修改,消息重试！！！");
            }
        }
        //使用乐观锁防止余额少减少
        int update = leaseUserWalletDataMapper.update(buyer, new LambdaQueryWrapper<LeaseUserWalletData>()
                .eq(LeaseUserWalletData::getId, buyer.getId())
                .eq(LeaseUserWalletData::getBalance, initBalance)
                .eq(LeaseUserWalletData::getBlockedBalance, initBlockBalance)
        );
        if (update < 1){
            throw new PayRechargeException("支付失败,余额金额错误,消息重试！！！");
        }
    }

    //@RabbitListener(queues = RabbitmqConstant.PAY_AUTO_RETURN_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    //@Transactional(rollbackFor = Exception.class)
    //public void listenerPayBalanceStatusQueueMessage(@Payload RabbitmqPayAutoReturnMessage payAutoReturnMessage) {
    //    System.out.println("支付消费者"+JSONUtil.toJsonPrettyStr(payAutoReturnMessage));
    //    //查找到数据库对应的支付记录
    //    List<LeasePayRecordMessage> leasePayRecordMessages = leasePayRecordMessageMapper.selectList(new LambdaQueryWrapper<LeasePayRecordMessage>()
    //            .eq(LeasePayRecordMessage::getQueueId, payAutoReturnMessage.getQueue_id()));
    //    Map<String, List<LeasePayRecordMessage>> recordMap = leasePayRecordMessages.stream()
    //            .collect(Collectors.groupingBy(item -> item.getToAddress() + "-" + item.getToChain()));
    //    //买家钱包
    //    Map<String,RabbitmqPayAutoReturnInfoMessage> transactions = payAutoReturnMessage.getTransactions();
    //    LeasePayRecordMessage leasePayRecordMessage1 = leasePayRecordMessages.get(0);
    //    LeaseUserWalletData buyer = leaseUserWalletDataMapper.selectOne(new LambdaQueryWrapper<LeaseUserWalletData>()
    //            .eq(LeaseUserWalletData::getFromAddress,leasePayRecordMessage1.getFromAddress())
    //            .eq(LeaseUserWalletData::getFromChain, leasePayRecordMessage1.getFromChain())
    //            .eq(LeaseUserWalletData::getFromSymbol, leasePayRecordMessage1.getFromSymbol())
    //            .eq(LeaseUserWalletData::getDel, false)
    //    );
    //    //获取初始余额和冻结余额
    //    BigDecimal initBalance = buyer.getBalance();
    //    BigDecimal initBlockBalance = buyer.getBlockedBalance();
    //    //支付成功修改order_item表实际支付金额
    //    transactions.forEach((key,transaction) -> {
    //        String key1 = transaction.getTo_address() + "-" + payAutoReturnMessage.getChain();
    //        List<LeasePayRecordMessage> leasePayRecordMessageList = recordMap.get(key1);
    //        if (leasePayRecordMessageList != null){
    //            for (LeasePayRecordMessage leasePayRecordMessage : leasePayRecordMessageList) {
    //                BigDecimal balance = buyer.getBalance().subtract(transaction.getAmount());
    //                BigDecimal blockBalance = buyer.getBlockedBalance().subtract(leasePayRecordMessage.getBlockAmount())
    //                        .subtract(leasePayRecordMessage.getNeedAmount());
    //
    //                leasePayRecordMessage.setUpdateTime(LocalDateTime.now());
    //                leasePayRecordMessage.setBlockHeight(transaction.getBlock_height());
    //                leasePayRecordMessage.setRealAmount(transaction.getAmount());
    //                //当天已存在支付的信息
    //                leasePayRecordMessage.setStatus(transaction.getStatus());
    //                leasePayRecordMessage.setTxHash(transaction.getTx_hash());
    //                List<LeaseOrderItem> needUpdateOrderItem = leaseOrderItemMapper.getNeedUpdateOrderItem(Long.valueOf(leasePayRecordMessage.getOrderId()));
    //                if(transaction.getStatus() == 1){
    //                    //支付成功 买家 钱包总余额 + 冻结余额 减少  卖家 钱包总余额增加
    //                    buyer.setBalance(balance);
    //                    buyer.setBlockedBalance(blockBalance);
    //                    needUpdateOrderItem = needUpdateOrderItem.stream().peek(item ->{
    //                        item.setAlreadyPayRealAmount(item.getAlreadyPayRealAmount().add(item.getSettlePayRealAmount()));
    //                        item.setSettlePayRealAmount(BigDecimal.ZERO);
    //                    }).collect(Collectors.toList());
    //                }
    //                if (transaction.getStatus() == 0){
    //                    buyer.setBlockedBalance(blockBalance);
    //                    needUpdateOrderItem = needUpdateOrderItem.stream().peek(item ->{
    //                        item.setSettlePayRealAmount(BigDecimal.ZERO);
    //                    }).collect(Collectors.toList());
    //                }
    //                //修改支付记录状态
    //                System.out.println("支付成功1"+JSONUtil.toJsonPrettyStr(leasePayRecordMessage));
    //                int i = leasePayRecordMessageMapper.updateById(leasePayRecordMessage);
    //                //支付成功修改order_item表实际支付金额
    //                System.out.println("支付成功2"+JSONUtil.toJsonPrettyStr(needUpdateOrderItem));
    //                boolean b = leaseOrderItemService.updateBatchById(needUpdateOrderItem);
    //
    //                System.out.println("支付成功修改order_item表实际支付金额"+ b +"----"+ i);
    //                if (i < 1 || !b){
    //                    throw new PayRechargeException("支付失败,该支付记录已修改,消息重试！！！");
    //                }
    //            }
    //
    //        }
    //
    //    });
    //    //使用乐观锁防止余额少减少
    //    int update = leaseUserWalletDataMapper.update(buyer, new LambdaQueryWrapper<LeaseUserWalletData>()
    //            .eq(LeaseUserWalletData::getId, buyer.getId())
    //            .eq(LeaseUserWalletData::getBalance, initBalance)
    //            .eq(LeaseUserWalletData::getBlockedBalance, initBlockBalance)
    //    );
    //    if (update < 1){
    //        throw new PayRechargeException("支付失败,余额金额错误,消息重试！！！");
    //    }
    //}



    /**
     * 余额充值 消费者 （正常流程一笔充值会有两个消息 2 充值中 1充值成功）
     * @param payRechargeReturnMessage
     */
    @LedgerLog(value = "余额充值")
    @RabbitListener(queues = RabbitmqConstant.PAY_RECHARGE_RETURN_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    @Transactional(rollbackFor = Exception.class)
    public void listenerPayRechargeStatusQueueMessage(@Payload RabbitmqPayRechargeReturnMessage payRechargeReturnMessage) {
        System.out.println("充值消费者---"+JSONUtil.toJsonPrettyStr(payRechargeReturnMessage));
        //获取到需要操作的钱包
        List<LeaseUserWalletData> leaseUserWalletDataList = leaseUserWalletDataMapper.selectList(new LambdaQueryWrapper<LeaseUserWalletData>()
                .eq(LeaseUserWalletData::getFromAddress, payRechargeReturnMessage.getAddress())
                .eq(LeaseUserWalletData::getDel, false)
        );
        if (leaseUserWalletDataList.isEmpty()){
            return;
        }
        LeaseUserWalletData leaseUserWalletData = null;
        for (LeaseUserWalletData item : leaseUserWalletDataList) {
            if (item.getFromSymbol().equals(payRechargeReturnMessage.getSymbol())){
                leaseUserWalletData = item;
                break;
            }
        }
        //需要新增该币种的钱包
        if (leaseUserWalletData == null){
            LeaseUserWalletData leaseUserWalletData1 = leaseUserWalletDataList.get(0);
            leaseUserWalletData = LeaseUserWalletData.builder()
                    .queueId(payRechargeReturnMessage.getQueue_id())
                    .userId(leaseUserWalletData1.getUserId())
                    .fromAddress(payRechargeReturnMessage.getAddress())
                    .fromChain(payRechargeReturnMessage.getChain())
                    .fromSymbol(payRechargeReturnMessage.getSymbol())
                    .balance(BigDecimal.ZERO)
                    .blockedBalance(BigDecimal.ZERO)
                    .qrcode(leaseUserWalletData1.getQrcode())
                    .build();
            leaseUserWalletDataMapper.insert(leaseUserWalletData);
        }
        LeasePayRechargeMessage leasePayRechargeMessage = leasePayRechargeMessageMapper.selectOne(new LambdaQueryWrapper<LeasePayRechargeMessage>()
                .eq(LeasePayRechargeMessage::getTxHash, payRechargeReturnMessage.getTx_hash()));
        BigDecimal balance = leaseUserWalletData.getBalance();
        //处理支付中消息
        if(payRechargeReturnMessage.getStatus() == 2 || leasePayRechargeMessage == null){
            if (leasePayRechargeMessage != null){
                return;
            }

            LeasePayRechargeMessage build = LeasePayRechargeMessage.builder()
                    .queueId(payRechargeReturnMessage.getQueue_id())
                    .chain(payRechargeReturnMessage.getChain())
                    .blockHeight(payRechargeReturnMessage.getBlock_height())
                    .fromAddress(payRechargeReturnMessage.getFromAddress())
                    .symbol(payRechargeReturnMessage.getSymbol())
                    .amount(payRechargeReturnMessage.getAmount())
                    .address(payRechargeReturnMessage.getAddress())
                    .txHash(payRechargeReturnMessage.getTx_hash())
                    .status(payRechargeReturnMessage.getStatus())
                    .build();
            leasePayRechargeMessageMapper.saveOrUpdateByIndex(build);
        }else {
            //已存在已完成充值的消息
            if (leasePayRechargeMessage.getStatus() == 1){
                return;
            }
            leasePayRechargeMessage.setStatus(payRechargeReturnMessage.getStatus());
            leasePayRechargeMessage.setUpdateTime(LocalDateTime.now());
            leasePayRechargeMessageMapper.updateById(leasePayRechargeMessage);
        }
        //处理支付成功消息
        if (payRechargeReturnMessage.getStatus() == 1){
            leaseUserWalletData.setBalance(balance.add(payRechargeReturnMessage.getAmount()));
            //使用乐观锁防止余额少加
            int update = leaseUserWalletDataMapper.update(leaseUserWalletData, new LambdaQueryWrapper<LeaseUserWalletData>()
                    .eq(LeaseUserWalletData::getId, leaseUserWalletData.getId())
                    .eq(LeaseUserWalletData::getBalance, balance)
            );
            if (update < 1){
                throw new PayRechargeException("余额充值失败,余额已被修改");
            }
        }
    }


    /**
     * 余额提现 消费者
     * @param payWithdrawReturnMessage
     */
    @LedgerLog(value = "余额提现结果")
    @RabbitListener(queues = RabbitmqConstant.PAY_WITHDRAW_RETURN_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    @Transactional(rollbackFor = Exception.class)
    public void listenerPayWithdrawStatusQueueMessage(@Payload RabbitmqPayWithdrawReturnMessage payWithdrawReturnMessage) {
        System.out.println("提现消费者----"+ JSONUtil.toJsonPrettyStr(payWithdrawReturnMessage));
        List<LeasePayWithdrawMessage> leasePayWithdrawMessageList = leasePayWithdrawMessageMapper.selectList(new LambdaQueryWrapper<LeasePayWithdrawMessage>()
                .eq(LeasePayWithdrawMessage::getQueueId, payWithdrawReturnMessage.getQueue_id()));
        if (leasePayWithdrawMessageList.isEmpty()){
            return ;
        }
        LeasePayWithdrawMessage leasePayWithdrawMessage = handlerBuyerWithdraw(payWithdrawReturnMessage, leasePayWithdrawMessageList);
        if (leasePayWithdrawMessage != null){
            LeaseShopConfig leaseShopConfig = leaseShopConfigMapper.selectOne(new LambdaQueryWrapper<LeaseShopConfig>()
                    .eq(LeaseShopConfig::getPayAddress, leasePayWithdrawMessage.getFromAddress())
                    .eq(LeaseShopConfig::getChain, leasePayWithdrawMessage.getFromChain())
                    .eq(LeaseShopConfig::getPayCoin, leasePayWithdrawMessage.getFromSymbol())
                    .eq(LeaseShopConfig::getDel, false));
            if (leaseShopConfig != null){
                //要修改的钱包状态为1 且提现的状态为1 则不处理
                if (leasePayWithdrawMessage.getStatus() == 1 && payWithdrawReturnMessage.getStatus() == 1){
                    return;
                }
                if (payWithdrawReturnMessage.getStatus() == 1){
                    leaseShopConfig.setBalance(leaseShopConfig.getBalance()
                            .add(leasePayWithdrawMessage.getAmount())
                            .add(leasePayWithdrawMessage.getServiceCharge()));
                    leaseShopConfigMapper.updateById(leaseShopConfig);
                }
                leasePayWithdrawMessageMapper.updateById(LeasePayWithdrawMessage.builder()
                        .id(leasePayWithdrawMessage.getId())
                        .status(payWithdrawReturnMessage.getStatus())
                        .txHash(payWithdrawReturnMessage.getTx_hash())
                        .blockHeight(payWithdrawReturnMessage.getBlock_height())
                        .build());
                //TODO 修改leaseShopConfig 金额（暂时不修改，提现申请的时候就修改了）
            }
        }

    }

    /**
     * 处理买家提现消息
     * @param payWithdrawReturnMessage
     * @param leasePayWithdrawMessageList
     * @return
     */
    public LeasePayWithdrawMessage handlerBuyerWithdraw(RabbitmqPayWithdrawReturnMessage payWithdrawReturnMessage,List<LeasePayWithdrawMessage> leasePayWithdrawMessageList){
        LeasePayWithdrawMessage leasePayWithdrawMessage  = leasePayWithdrawMessageList.get(0);
        //获取对应的提现钱包
        LeaseUserWalletData  leaseUserWalletData = leaseUserWalletDataMapper.selectOne(new LambdaQueryWrapper<LeaseUserWalletData>()
                .eq(LeaseUserWalletData::getFromAddress, leasePayWithdrawMessage.getFromAddress())
                .eq(LeaseUserWalletData::getFromChain, leasePayWithdrawMessage.getFromChain())
                .eq(LeaseUserWalletData::getFromSymbol, leasePayWithdrawMessage.getFromSymbol())
                .eq(LeaseUserWalletData::getDel,false));
        //如果不存在，则说明本次提现申请的是卖方钱包提现
        if (leaseUserWalletData == null){
            return leasePayWithdrawMessage;
        }
        BigDecimal balance = leaseUserWalletData.getBalance()
                .subtract(payWithdrawReturnMessage.getAmount())
                .subtract(leasePayWithdrawMessage.getServiceCharge());
        BigDecimal blockBalance = leaseUserWalletData.getBlockedBalance()
                .subtract(payWithdrawReturnMessage.getAmount())
                .subtract(leasePayWithdrawMessage.getServiceCharge());

        if (leasePayWithdrawMessageList.size() == 1){
            //这种情况下说明不是同一笔交易了,但是它又提现了，但是数据库里面没有该提现记录 需要去新增这笔记录并只减去钱包余额
            if (StringUtils.isNotEmpty(leasePayWithdrawMessage.getTxHash()) && leasePayWithdrawMessage.getStatus() == 1  && !leasePayWithdrawMessage.getTxHash().equals(payWithdrawReturnMessage.getTx_hash())){
                leasePayWithdrawMessageMapper.insert(LeasePayWithdrawMessage.builder()
                        .toChain(leasePayWithdrawMessage.getToChain())
                        .toSymbol(leasePayWithdrawMessage.getToSymbol())
                        .fromChain(leasePayWithdrawMessage.getFromChain())
                        .fromSymbol(leasePayWithdrawMessage.getFromSymbol())
                        .fromAddress(leasePayWithdrawMessage.getFromAddress())
                        .serviceCharge(leasePayWithdrawMessage.getServiceCharge())
                        .toAddress(leasePayWithdrawMessage.getToAddress())
                        .status(payWithdrawReturnMessage.getStatus())
                        .amount(payWithdrawReturnMessage.getAmount().add(payWithdrawReturnMessage.getFee()))
                        .queueId(payWithdrawReturnMessage.getQueue_id())
                        .txHash(payWithdrawReturnMessage.getTx_hash())
                        .build());
                blockBalance = leaseUserWalletData.getBlockedBalance();
            }else{
                //要修改的钱包状态为1 且提现的状态为1 则不处理
                if (leasePayWithdrawMessage.getStatus() == 1 && payWithdrawReturnMessage.getStatus() == 1){
                    return null;
                }
                leasePayWithdrawMessageMapper.updateById(LeasePayWithdrawMessage.builder()
                        .id(leasePayWithdrawMessage.getId())
                        .amount(payWithdrawReturnMessage.getAmount().add(payWithdrawReturnMessage.getFee()))
                        .status(payWithdrawReturnMessage.getStatus())
                        .blockHeight(payWithdrawReturnMessage.getBlock_height())
                        .txHash(payWithdrawReturnMessage.getTx_hash())
                        .build());
            }
            updateWalletInfo(payWithdrawReturnMessage.getStatus(), leaseUserWalletData, balance, blockBalance);
        }else if(leasePayWithdrawMessageList.size() >= 2){
            //极少情况 连续三次以上发送相同queueid 的消息
            LeasePayWithdrawMessage with = null;
            for (LeasePayWithdrawMessage withdraw : leasePayWithdrawMessageList) {
                if (withdraw.getTxHash().equals(payWithdrawReturnMessage.getTx_hash()) ){
                    with = withdraw;
                }
            }
            if(with == null){
                leasePayWithdrawMessageMapper.insert(LeasePayWithdrawMessage.builder()
                        .queueId(payWithdrawReturnMessage.getQueue_id())
                        .txHash(payWithdrawReturnMessage.getTx_hash())
                        .toChain(leasePayWithdrawMessage.getToChain())
                        .toSymbol(leasePayWithdrawMessage.getToSymbol())
                        .fromChain(leasePayWithdrawMessage.getFromChain())
                        .fromSymbol(leasePayWithdrawMessage.getFromSymbol())
                        .fromAddress(leasePayWithdrawMessage.getFromAddress())
                        .serviceCharge(payWithdrawReturnMessage.getFee())
                        .toAddress(leasePayWithdrawMessage.getToAddress())
                        .amount(payWithdrawReturnMessage.getAmount().add(payWithdrawReturnMessage.getFee()))
                        .build());
                blockBalance =leaseUserWalletData.getBlockedBalance();
                updateWalletInfo(payWithdrawReturnMessage.getStatus(), leaseUserWalletData, balance, blockBalance);
            }else{
                leasePayWithdrawMessageMapper.updateById(LeasePayWithdrawMessage.builder()
                        .id(with.getId())
                        .amount(payWithdrawReturnMessage.getAmount().add(payWithdrawReturnMessage.getFee()))
                        .status(payWithdrawReturnMessage.getStatus())
                        .txHash(payWithdrawReturnMessage.getTx_hash())
                        .build());
                if (with.getStatus() != 1 && payWithdrawReturnMessage.getStatus() == 1){
                    updateWalletInfo(payWithdrawReturnMessage.getStatus(), leaseUserWalletData, balance, blockBalance);
                }
            }
        }

        return null;
    }


    /**
     * 更新钱包余额信息
     * @param status
     * @param leaseUserWalletData
     * @param balance
     * @param blockBalance
     */
    public void updateWalletInfo(Integer status,LeaseUserWalletData  leaseUserWalletData,BigDecimal balance,BigDecimal blockBalance){
        BigDecimal initBalance = leaseUserWalletData.getBalance();
        BigDecimal initBlockBalance = leaseUserWalletData.getBlockedBalance();
        //余额 和 冻结余额 减去提现金额 + 手续费  状态为3不做任何操作
        if (status == 1){
            leaseUserWalletData.setBalance(balance);
            leaseUserWalletData.setBlockedBalance(blockBalance);
        }else if (status == 0 ){
            //余额提现失败 冻结金额 需要减去提现手续费和提现金额
            leaseUserWalletData.setBlockedBalance(blockBalance);
        }
        leaseUserWalletData.setUpdateTime(LocalDateTime.now());
        //使用乐观锁防止余额少加
        int update = leaseUserWalletDataMapper.update(leaseUserWalletData, new LambdaQueryWrapper<LeaseUserWalletData>()
                .eq(LeaseUserWalletData::getId, leaseUserWalletData.getId())
                .eq(LeaseUserWalletData::getBalance, initBalance)
                .eq(LeaseUserWalletData::getBlockedBalance, initBlockBalance)
        );
        if (update < 1){
            System.out.println("余额提现/支付失败");
            throw new PayRechargeException("余额提现失败,余额已被修改");
        }
        System.out.println("余额提现/支付成功");
    }

    @RabbitListener(queues = RabbitmqConstant.DELETE_WALLET_RETURN_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    @Transactional(rollbackFor = Exception.class)
    public void listenerDeleteWalletQueue(@Payload RabbitmqDeleteWalletReturnMessage rabbitmqDeleteWalletReturnMessage) {
        System.out.println("钱包监听删除----删除钱包地址"+rabbitmqDeleteWalletReturnMessage.getAddress());
        LeaseAutoAddress build;
        if (rabbitmqDeleteWalletReturnMessage.getStatus() == 1){
            //设置钱包使用状态为2 已过期
            build = LeaseAutoAddress.builder().status(2).build();
        }else{
            //设置钱包使用状态为3 删除监听失败
            build = LeaseAutoAddress.builder().status(3).build();
        }
        int i = leaseAutoAddressMapper.update(build, new LambdaUpdateWrapper<LeaseAutoAddress>()
                .eq(LeaseAutoAddress::getAddress, rabbitmqDeleteWalletReturnMessage.getAddress())
                .eq(LeaseAutoAddress::getFromChain, rabbitmqDeleteWalletReturnMessage.getChain())
                .eq(LeaseAutoAddress::getFromSymbol, rabbitmqDeleteWalletReturnMessage.getSymbol())
        );
        int update = leaseUserWalletDataMapper.update(LeaseUserWalletData.builder().del(true).build(), new LambdaUpdateWrapper<LeaseUserWalletData>()
                .eq(LeaseUserWalletData::getFromAddress, rabbitmqDeleteWalletReturnMessage.getAddress())
                .eq(LeaseUserWalletData::getFromChain, rabbitmqDeleteWalletReturnMessage.getChain())
                .eq(LeaseUserWalletData::getFromSymbol, rabbitmqDeleteWalletReturnMessage.getSymbol())
        );
        if (i > 0 && update > 0 ){
            System.out.println("钱包监听删除成功:"+rabbitmqDeleteWalletReturnMessage.getAddress());
        }
    }

    ////测试 开发环境 支付回调测试
    //@RabbitListener(queues = RabbitmqConstant.PAY_AUTO_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    //@Transactional(rollbackFor = Exception.class)
    //public void listenerPayBalanceStatusQueueMessage(@Payload RabbitmqPayAutoMessage payAutoReturnMessage) {
    //    //消费消息
    //    System.out.println("自动支付功能queueId"+payAutoReturnMessage.getQueue_id());
    //
    //    RabbitmqPayAutoReturnMessage rabbitmqPayAutoReturnMessage = RabbitmqPayAutoReturnMessage.builder()
    //            .queue_id(payAutoReturnMessage.getQueue_id())
    //            .from_address(payAutoReturnMessage.getFrom_address())
    //            .to_address(payAutoReturnMessage.getTo_address())
    //            .chain(payAutoReturnMessage.getChain())
    //            .symbol(payAutoReturnMessage.getSymbol())
    //            .fee(payAutoReturnMessage.getFee())
    //            .amount(payAutoReturnMessage.getAmount())
    //            .status(1)
    //            .tx_hash(UuidGeneratorUtil.generateUuidWithoutHyphen())
    //            .block_height(1000L)
    //            .order_id(payAutoReturnMessage.getOrder_id())
    //            .build();
    //
    //    rabbitTemplate.convertAndSend(RabbitmqConstant.PAY_AUTO_RETURN_QUEUE,rabbitmqPayAutoReturnMessage);
    //}
    //
    //测试 开发环境 充值测试
    //@RabbitListener(queues = RabbitmqConstant.PAY_RECHARGE_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    //@Transactional(rollbackFor = Exception.class)
    //public void listenerPayRechargeQueueMessage(@Payload RabbitmqPayRechargeMessage payAutoReturnMessage) {
    //    String s = UuidGeneratorUtil.generateUuidWithoutHyphen();
    //    ////发送充值消息
    //    //RabbitmqPayRechargeReturnMessage rabbitmqPayRechargeReturnMessage = RabbitmqPayRechargeReturnMessage.builder()
    //    //        .queue_id(payAutoReturnMessage.getQueue_id())
    //    //        .status(2)
    //    //        .amount(BigDecimal.valueOf(20))
    //    //        .chain(payAutoReturnMessage.getChain())
    //    //        .symbol(payAutoReturnMessage.getSymbol())
    //    //        .address(payAutoReturnMessage.getAddress())
    //    //        .tx_hash(s)
    //    //        .build();
    //    //rabbitTemplate.convertAndSend(RabbitmqConstant.PAY_RECHARGE_RETURN_QUEUE,rabbitmqPayRechargeReturnMessage);
    //
    //
    //    //发送充值消息
    //    RabbitmqPayRechargeReturnMessage rabbitmqPayRechargeReturnMessage1 = RabbitmqPayRechargeReturnMessage.builder()
    //            .queue_id(payAutoReturnMessage.getQueue_id())
    //            .status(1)
    //            .amount(BigDecimal.valueOf(20))
    //            .chain(payAutoReturnMessage.getChain())
    //            .symbol(payAutoReturnMessage.getSymbol())
    //            .address(payAutoReturnMessage.getAddress())
    //            .tx_hash(s)
    //            .build();
    //    rabbitTemplate.convertAndSend(RabbitmqConstant.PAY_RECHARGE_RETURN_QUEUE,rabbitmqPayRechargeReturnMessage1);
    //}


    //提现
    //@RabbitListener(queues = RabbitmqConstant.PAY_WITHDRAW_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    //@Transactional(rollbackFor = Exception.class)
    //public void listenerWithdrawQueueMessage(@Payload RabbitmqPayWithdrawMessage payAutoReturnMessage) {
    //    //发送充值消息
    //    RabbitmqPayWithdrawReturnMessage rabbitmqPayRechargeReturnMessage = RabbitmqPayWithdrawReturnMessage.builder()
    //            .queue_id(payAutoReturnMessage.getQueue_id())
    //            .status(1)
    //            .amount(payAutoReturnMessage.getAmount())
    //            .chain(payAutoReturnMessage.getChain())
    //            .symbol(payAutoReturnMessage.getSymbol())
    //            .from_address(payAutoReturnMessage.getFrom_address())
    //            .tx_hash(UuidGeneratorUtil.generateUuidWithoutHyphen())
    //            .fee(payAutoReturnMessage.getFee())
    //            .build();
    //    rabbitTemplate.convertAndSend(RabbitmqConstant.PAY_WITHDRAW_RETURN_QUEUE,rabbitmqPayRechargeReturnMessage);
    //}


    ////测试 开发环境 删除钱包测试
    //@RabbitListener(queues = RabbitmqConstant.DELETE_WALLET_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    //@Transactional(rollbackFor = Exception.class)
    //public void listenerDeleteWalletQueueMessage(@Payload RabbitmqDeleteWalletMessage payAutoReturnMessage) {
    //    //发送充值消息
    //    RabbitmqDeleteWalletReturnMessage rabbitmqDeleteWalletReturnMessage = RabbitmqDeleteWalletReturnMessage.builder()
    //            .queue_id(payAutoReturnMessage.getQueue_id())
    //            .status(1)
    //            .chain(payAutoReturnMessage.getChain())
    //            .symbol(payAutoReturnMessage.getSymbol())
    //            .address(payAutoReturnMessage.getAddress())
    //            .build();
    //    rabbitTemplate.convertAndSend(RabbitmqConstant.DELETE_WALLET_RETURN_QUEUE,rabbitmqDeleteWalletReturnMessage);
    //}
    //




}
