package com.crm.ucard.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.PayConstant;
import com.crm.rely.backend.core.dto.wasabi.*;
import com.crm.rely.backend.core.entity.ucard.UcardPayCallbackEntity;
import com.crm.rely.backend.core.enums.*;
import com.crm.rely.backend.core.pojo.table.ucard.*;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.util.BeanUtilPlus;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.GetRandom;
import com.crm.ucard.config.WasabiConfig;
import com.crm.ucard.dao.repository.*;
import com.crm.ucard.service.*;
import com.crm.ucard.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;


@Slf4j
@Service
public class UcardNotifyServiceImpl implements UcardNotifyService {

    @Autowired
    private CardApplyRepository cardApplyRepository;
    @Autowired
    private UcardCardRepository cardRepository;
    @Autowired
    private CardActivateRepository cardActivateRepository;
    @Autowired
    private CardRechargeOrderRepository rechargeOrderRepository;
    @Autowired
    private CardMerchantUserRepository merchantUserRepository;
    @Autowired
    private CardOperateRepository cardOperateRepository;
    @Autowired
    private CardTransacOrderRepository cardTransacOrderRepository;
    @Autowired
    private MqSendService mqSendService;
    @Autowired
    private UcardWalletRepository ucardWalletRepository;
    @Autowired
    private UcardWalletRecordRepository ucardWalletRecordRepository;
    @Autowired
    private CardPasswordResetRepository passwordResetRepository;
    @Autowired
    private CardGlobalOrderDataAvailableRepository globalOrderDataAvailableRepository;
    @Autowired
    private CardGlobalOrderDataRepository globalOrderDataRepository;
    @Autowired
    private CardGlobalOrderRepository globalOrderRepository;
    @Autowired
    private UcardGlobalReceiverInfoRepository globalReceiverInfoRepository;
    @Autowired
    private CardWithdrawRepository withdrawRepository;
    @Autowired
    private Card3dsTransactionRepository card3dsTransactionRepository;
    @Autowired
    private WasabiDocumentApiService wasabiDocumentApiService;
    @Autowired
    private UcardEmailService ucardEmailService;
    @Autowired
    private GlobalService globalService;
    @Autowired
    private UcardNumberService ucardNumberService;
    @Autowired
    private UcardCardService wasabiCardCardService;


    /**
     * 回调通知处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cardTransactionNotify(WasabiTransactionDto dto) throws Exception {
        Date now = new Date();
        switch (dto.getType()) {
            case "create"://开卡；
                CardApplyTable applyTable = cardApplyRepository.getByMerchantOrderNo(dto.getMerchantOrderNo());
                if (null == applyTable) {
                    throw new ServiceException("卡片不存在");
                }
                if (!applyTable.getStatus().equals(dto.getStatus())) {
                    BeanUtils.copyProperties(dto, applyTable);
                    cardApplyRepository.save(applyTable);
                    UcardCardTable cardTable = cardRepository.findByCardNo(dto.getCardNo());
                    if (cardTable != null) {
                        return;
                    }
                    if (Constants.SUCCESS.equals(dto.getStatus())) {
                        ucardNumberService.saveCardNumberStatus(applyTable.getCardNumber(), 3);
                        cardTable = new UcardCardTable();
                        BeanUtils.copyProperties(applyTable, cardTable);
                        cardTable.setId(null);
                        cardTable.setStatus(CardStatusTypeEnum.UN_ACTIVATE.getCode());
                        cardTable.setType(dto.getType());
                        cardTable.setSubType(dto.getSubType());
                        cardTable.setTransactionTime(dto.getTransactionTime());
                        cardTable.setFreezeStatus(Constants.SUCCESS);
                        cardTable.setFreezeType("1");
                        cardTable.setAddTime(now);
                        cardTable.setLogisticsStatus("1");
                        cardRepository.save(cardTable);
                        mqSendService.send(Constants.CARD_LOGISTICS_STATUS_UPDATE, JSONObject.toJSONString(cardTable)
                                , 24 * 60 * 60 * 1000);
                        ucardEmailService.sendOpenCardSuccessEmail(cardTable);
                    }
                    if (Constants.FAIL.equals(applyTable.getStatus())) {
                        ucardNumberService.saveCardNumberStatus(applyTable.getCardNumber(), 1);
                        applyTable.setTradeType(2);
                        wasabiCardCardService.failure(applyTable);
                    }
                }
                break;
            case "deposit"://充值；
                CardRechargeOrderTable table = rechargeOrderRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
                if (table == null) {
                    log.error("充值订单不存在-notifyParam : {}", JSON.toJSONString(dto));
                    throw new ServiceException("充值订单不存在");
                }
                if (Constants.SUCCESS.equals(table.getStatus()) || Constants.FAIL.equals(table.getStatus())) {
                    return;
                }
                UcardCardTable cardTable = cardRepository.findByCardNo(dto.getCardNo());
                if (!table.getStatus().equals(dto.getStatus())) {
                    BeanUtils.copyProperties(dto, table);
                    table.setTransactionTime(DateUtil.formatTimestamp(dto.getTransactionTime()));
                    table.setModifyTime(now);
                    table.setCurrency("USD");
                    table.setReceivedCurrency("USD");
                    rechargeOrderRepository.save(table);
                    CardMerchantUserTable userTable = merchantUserRepository.getByUniqueId(table.getUniqueId());
                    if ("1".equals(table.getRechargeType())) {
                        // 充值默认金额
                        if (Constants.SUCCESS.equals(dto.getStatus())) {
                            if (cardTable != null && !Constants.SUCCESS.equals(cardTable.getStatus())) {
                                cardTable.setStatus(Constants.SUCCESS);
                                cardTable.setType(dto.getType());
                                cardRepository.save(cardTable);
                                // 激活成功发送邮件通知
                                ucardEmailService.sendActivateCardSuccessEmail(cardTable);
                            }
                        }
                    } else if ("2".equals(table.getRechargeType())) {
                        // 速汇退款
                        CardGlobalOrderTable orderTable =
                                globalOrderRepository.findByRefundMerchantOrderNo(dto.getMerchantOrderNo());
                        // 处理速汇退款订单
                        if (orderTable != null) {
                            if (Constants.SUCCESS.equals(dto.getStatus())) {
                                orderTable.setDeductionAccountStatus(GlobalOrderDeductionStatusEnum.REFUND_SUCCESS.getStatus());
                            } else if (Constants.FAIL.equals(dto.getStatus())) {
                                orderTable.setDeductionAccountStatus(GlobalOrderDeductionStatusEnum.REFUND_FAIL.getStatus());
                            }
                            globalOrderRepository.save(orderTable);
                        }
                    } else if ("3".equals(table.getRechargeType())) {
                        // 充值
                        UcardWalletRecordTable recordTable =
                                ucardWalletRecordRepository.findFirstByOrderNo(dto.getMerchantOrderNo());
                        if (Constants.SUCCESS.equals(dto.getStatus())) {
                            if (cardTable != null && !Constants.SUCCESS.equals(cardTable.getStatus())) {
                                cardTable.setStatus(Constants.SUCCESS);
                                cardTable.setType(dto.getType());
                                cardRepository.save(cardTable);
                            }
                            recordTable.setStatus(2);
                            // 充值成功给客户发邮件
                            ucardEmailService.sendCardRechargeSuccessEmail(userTable, table);
                        } else if (Constants.FAIL.equals(dto.getStatus())) {
                            UcardWalletTable walletTable = ucardWalletRepository.findFirstByCId(userTable.getCId());
                            recordTable.setStatus(3);
                            BigDecimal balance = null == walletTable.getBalance() ? new BigDecimal(0) :
                                    walletTable.getBalance();
                            walletTable.setBalance(balance.add(table.getAmount()).add(table.getFee()));
                            ucardWalletRepository.save(walletTable);
                            // 新增退款订单信息记录
                            UcardWalletRecordTable walletRecordTable = new UcardWalletRecordTable();
                            walletRecordTable.setWalletId(walletTable.getId());
                            walletRecordTable.setCId(walletTable.getCId());
                            walletRecordTable.setUniqueId(walletTable.getUniqueId());
                            walletRecordTable.setAmount(table.getAmount());
                            walletRecordTable.setFee(table.getFee());
                            walletRecordTable.setSerial(GetRandom.getOrderNo(PayConstant.UCARD_HEAD));
                            walletRecordTable.setStatus(2);
                            walletRecordTable.setType(CardWalletRecordTypeEnum.REFUND.getCode());
                            walletRecordTable.setAddTime(now);
                            ucardWalletRecordRepository.save(walletRecordTable);
                        }
                        recordTable.setModifyTime(now);
                        ucardWalletRecordRepository.save(recordTable);
                    }
                }
                break;
            case "cancel"://销卡；
                UcardCardTable cancelCard = cardRepository.findByCardNo(dto.getCardNo());
                if (cancelCard == null) {
                    throw new ServiceException("卡不存在");
                }
                if (!cancelCard.getCancelStatus().equals(dto.getStatus())) {
                    cancelCard.setCancelStatus(dto.getStatus());
                    cancelCard.setSubType(dto.getSubType());
                    cancelCard.setType(dto.getType());
                    cancelCard.setRemark(dto.getRemark());
                    cancelCard.setTransactionTime(dto.getTransactionTime());
                    cancelCard.setModifyTime(now);
                    cardRepository.save(cancelCard);
                    CardApplyTable apply = cardApplyRepository.getByCardNo(dto.getCardNo());
                    apply.setStatus("cancel");
                    apply.setType(dto.getType());
                    apply.setSubType(dto.getSubType());
                    apply.setRemark(dto.getRemark());
                    apply.setModifyTime(now);
                    cardApplyRepository.save(apply);
                }
                break;
            case "Freeze"://冻结；
                UcardCardTable card = cardRepository.findByCardNo(dto.getCardNo());
                if (card == null) {
                    throw new ServiceException("卡不存在");
                }
                if ("2".equals(card.getFreezeType()) && Constants.SUCCESS.equals(card.getFreezeStatus())) {
                    throw new ServiceException("卡已冻结");
                }

                if (!card.getFreezeStatus().equals(dto.getStatus())) {
                    if (Constants.FAIL.equals(dto.getStatus())) {
                        card.setFreezeType("1");
                        card.setFreezeStatus(Constants.SUCCESS);
                    } else {
                        card.setFreezeType("2");
                        card.setFreezeStatus(dto.getStatus());
                    }
                    card.setType(dto.getType());
                    card.setRemark(dto.getRemark());
                    card.setTransactionTime(dto.getTransactionTime());
                    card.setModifyTime(now);
                    cardRepository.save(card);
                    CardOperateTable operateTable =
                            cardOperateRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
                    if (operateTable != null) {
                        operateTable.setStatus(dto.getStatus());
                        cardOperateRepository.save(operateTable);
                    }
                }
                break;
            case "UnFreeze"://解冻；
                cardTable = cardRepository.findByCardNo(dto.getCardNo());
                if (cardTable == null) {
                    throw new ServiceException("卡不存在");
                }
                if ("1".equals(cardTable.getFreezeType()) && Constants.SUCCESS.equals(cardTable.getFreezeStatus())) {
                    throw new ServiceException("卡已冻结");
                }

                if (!cardTable.getFreezeStatus().equals(dto.getStatus())) {
                    if (Constants.FAIL.equals(dto.getStatus())) {
                        cardTable.setFreezeType("2");
                        cardTable.setFreezeStatus(Constants.SUCCESS);
                    } else {
                        cardTable.setFreezeType("1");
                        cardTable.setFreezeStatus(dto.getStatus());
                    }
                    cardTable.setType(dto.getType());
                    cardTable.setRemark(dto.getRemark());
                    cardTable.setTransactionTime(dto.getTransactionTime());
                    cardTable.setModifyTime(now);
                    cardRepository.save(cardTable);
                    CardOperateTable operateTable =
                            cardOperateRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
                    if (operateTable != null) {
                        operateTable.setStatus(dto.getStatus());
                        cardOperateRepository.save(operateTable);
                    }
                }
                break;
            case "withdraw"://扣款；
                CardWithdrawTable withdrawTable = withdrawRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
                if (withdrawTable == null) {
                    throw new ServiceException("交易不存在");
                }
                if (!withdrawTable.getStatus().equals(dto.getStatus())) {
                    BigDecimal amount = withdrawTable.getAmount();
                    String type = withdrawTable.getType();
                    BeanUtils.copyProperties(dto, withdrawTable);
                    withdrawTable.setModifyTime(now);
                    withdrawTable.setAmount(amount);
                    withdrawTable.setType(type);
                    withdrawRepository.save(withdrawTable);
                    CardOperateTable cardOperateTable =
                            cardOperateRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
                    if (cardOperateTable != null) {
                        cardOperateTable.setStatus(dto.getStatus());
                        cardOperateTable.setModifyTime(now);
                        cardOperateRepository.save(cardOperateTable);
                    }
                    if ("1".equals(withdrawTable.getType())) {
                        CardGlobalOrderTable globalOrderTable =
                                globalOrderRepository.findByDeductionMerchantOrderNo(dto.getMerchantOrderNo());
                        if (globalOrderTable != null) {
                            globalOrderTable.setDeductionAccountStatus(GlobalOrderDeductionTypeEnum.matchCode(dto.getStatus()));
                            globalOrderTable.setModifyTime(now);
                            globalOrderRepository.save(globalOrderTable);
                            if ("2".equals(globalOrderTable.getDeductionAccountStatus())) {
                                CardMerchantUserTable userTable =
                                        merchantUserRepository.getByUniqueId(globalOrderTable.getUniqueId());
                                // 将收款人信息保存到数据库
                                CardGlobalReceiverInfoTable receiverInfoTable =
                                        globalReceiverInfoRepository.findByUniqueIdAndPayoutCurrencyAndTransferTypeAndPayoutMethodAndReceiverBankAccountNumber(
                                                globalOrderTable.getUniqueId(), globalOrderTable.getPayoutCurrency(),
                                                globalOrderTable.getTransferType(), globalOrderTable.getPayoutMethod(),
                                                globalOrderTable.getReceiverBankAccountNumber());
                                if (receiverInfoTable == null) {
                                    receiverInfoTable = new CardGlobalReceiverInfoTable();
                                    BeanUtilPlus.copyPropertiesIgnoreNull(globalOrderTable, receiverInfoTable);
                                    receiverInfoTable.setId(null);
                                    receiverInfoTable.setAddTime(now);
                                } else {
                                    Long id = receiverInfoTable.getId();
                                    BeanUtilPlus.copyPropertiesIgnoreNull(globalOrderTable, receiverInfoTable);
                                    receiverInfoTable.setId(id);
                                    receiverInfoTable.setModifyTime(now);
                                }
                                globalReceiverInfoRepository.save(receiverInfoTable);
                                // 发邮件给审核人员
                                ucardEmailService.sendGlobalOrderReviewEmail(userTable, globalOrderTable);
                            }
                        }
                    } else if ("2".equals(withdrawTable.getType())) {
                        UcardPayCallbackEntity callbackEntity = new UcardPayCallbackEntity();
                        callbackEntity.setOrderNo(withdrawTable.getDepositOrderNo());
                        callbackEntity.setInternalOrderNo(withdrawTable.getInternalOrderNo());
                        callbackEntity.setAmount(withdrawTable.getAmount());
                        callbackEntity.setCallBackUrl(withdrawTable.getCallbackUrl());
                        if (Constants.SUCCESS.equals(dto.getStatus())) {
                            callbackEntity.setStatus(2);
                            callbackEntity.setApproveDesc("");
                        } else if (Constants.FAIL.equals(dto.getStatus())) {
                            callbackEntity.setStatus(3);
                            callbackEntity.setApproveDesc("103");
                        }
                        mqSendService.send(Constants.UCARD_DEPOSIT_CALLBACK, callbackEntity);
                    }
                }
                break;
            case "update_pin"://更新PIN
                UcardCardTable ucardCardTable = cardRepository.findByCardNo(dto.getCardNo());
                if (ucardCardTable == null) {
                    throw new ServiceException("卡不存在");
                }
                CardPasswordResetTable cardPasswordResetTable =
                        passwordResetRepository.findFirstByMerchantOrderNo(dto.getMerchantOrderNo());
                if (cardPasswordResetTable == null) {
                    throw new ServiceException("卡密码修改记录不存在");
                }
                if (!cardPasswordResetTable.getStatus().equals(dto.getStatus())) {
                    cardPasswordResetTable.setStatus(dto.getStatus());
                    cardPasswordResetTable.setModifyTime(now);
                    passwordResetRepository.save(cardPasswordResetTable);
                    CardOperateTable operateTable =
                            cardOperateRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
                    if (operateTable != null) {
                        operateTable.setStatus(dto.getStatus());
                        operateTable.setModifyTime(now);
                        cardOperateRepository.save(operateTable);
                    }
                    if (Constants.SUCCESS.equals(dto.getStatus())) {
                        ucardCardTable.setPin(cardPasswordResetTable.getPassword());
                        ucardCardTable.setType(dto.getType());
                        ucardCardTable.setModifyTime(now);
                        cardRepository.save(ucardCardTable);
                        // 修改密码成功给客户发邮件
                        CardMerchantUserTable cardMerchantUserTable =
                                merchantUserRepository.getByUniqueId(ucardCardTable.getUniqueId());
                        ucardEmailService.sendCardUpdatePasswordSuccessEmail(cardMerchantUserTable, ucardCardTable.getCardNumber());
                    }
                }
                break;
            case "blocked"://锁卡
                cardTable = cardRepository.findByCardNo(dto.getCardNo());
                if (cardTable == null) {
                    throw new ServiceException("卡不存在");
                }
                if (Constants.SUCCESS.equals(dto.getStatus())) {
                    cardTable.setBlocked(true);
                    cardTable.setType(dto.getType());
                    cardTable.setModifyTime(now);
                    cardRepository.save(cardTable);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 卡授权交易通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cardAuthTransactionNotify(WasabiAuthTransactionDto dto) throws ServiceException {
        // 查询数据库是否存在该条数据记录 存在则更新 不存在则新增
        CardTransacOrderTable table = cardTransacOrderRepository.findByCardNoAndTradeNo(dto.getCardNo(),
                dto.getTradeNo());
        if (table == null) {
            table = new CardTransacOrderTable();
            table.setAddTime(new Date());
        } else {
            table.setModifyTime(new Date());
        }
        BeanUtils.copyProperties(dto, table);
        cardTransacOrderRepository.save(table);
    }

    /**
     * 卡授权交易冲正通知
     */
    @Override
    public void cardFeePatchNotify(WasabiFeePatchNotifyDto dto) throws ServiceException {

    }

    /**
     * 卡3ds通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void card3dsNotify(WasabiThird3dsTransactionDto dto) throws Exception {
        WasabiConfig config = wasabiDocumentApiService.getWasabiConfig();
        UcardCardTable cardTable = cardRepository.findByCardNo(dto.getCardNo());
        if (cardTable == null) {
            throw new ServiceException("卡不存在");
        }
        CardMerchantUserTable userTable = merchantUserRepository.findByUniqueId(cardTable.getUniqueId());
        String values = RsaUtils.decryptPrivateKey(dto.getValues(), config.getPrivateKey());
        if (StringUtils.isEmpty(values)) {
            log.error("卡3ds通知-解密参数为空,{}", JSON.toJSONString(dto));
            throw new ServiceException("卡3ds通知-解密参数为空");
        }
        Card3dsTransactionTable table = new Card3dsTransactionTable();
        BeanUtils.copyProperties(dto, table);
        table.setValue(values);
        table.setAddTime(new Date());
        table.setTransactionTime(DateUtil.formatTimestamp(dto.getTransactionTime()));
        table.setExpirationTime(DateUtil.formatTimestamp(dto.getExpirationTime()));
        card3dsTransactionRepository.save(table);
        switch (dto.getType()) {
            case "activation_code":
                // 发邮件给用户
//                sendUserActivationCodeEmail(userTable, cardTable.getCardNumber(), values);
                break;
            case "third_3ds_otp":
                // 发邮件给用户
                ucardEmailService.sendUser3dsEmail(userTable, cardTable.getCardNumber(), values, dto);
                break;
            case "auth_url":
                // 发邮件给用户
                ucardEmailService.sendUserAuthUrlEmail(userTable, cardTable.getCardNumber(), values, dto);
                break;
            default:
                break;
        }
    }

    /**
     * 持卡人通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cardHolderNotify(WasabiHolderQueryDto dto) throws ServiceException {
        try {
            CardApplyTable applyTable =
                    cardApplyRepository.findFirstByHolderMerchantOrderNoOrderByAddTimeDesc(dto.getMerchantOrderNo());
            if (null == applyTable) {
                throw new ServiceException("持卡人不存在");
            }
            if (!applyTable.getHolderStatus().equals(dto.getStatus())) {
                applyTable.setHolderId(dto.getHolderId());
                applyTable.setHolderStatus(dto.getStatus());
                applyTable.setHolderDescription(dto.getDescription());
                cardApplyRepository.save(applyTable);
                mqSendService.send(Constants.WASABICARD_CARD_APPLY_PROGRESS, JSON.toJSONString(applyTable),
                        3 * 60 * 1000);
            }

        } catch (Exception e) {
            log.error("持卡人通知回调失败", e);
            throw new ServiceException("持卡人通知回调失败");
        }
    }

    /**
     * 实体卡事件通知(激活)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void physicalCardNotify(WasabiPhysicalCardNotifyDto dto) throws ServiceException {
        try {
            if (!Constants.SUCCESS.equals(dto.getStatus())) {
                return;
            }
            UcardCardTable table = cardRepository.findByCardNo(dto.getCardNo());
            if (table == null) {
                throw new ServiceException("卡片不存在");
            }
            if (Constants.SUCCESS.equals(table.getStatus())) {
                throw new ServiceException("卡片已激活");
            }

            CardActivateTable cardActivateTable =
                    cardActivateRepository.findByMerchantOrderNo(dto.getMerchantOrderNo());
            if (!cardActivateTable.getStatus().equals(Constants.SUCCESS)) {
                cardActivateTable.setStatus(dto.getStatus());
                cardActivateTable.setRemark(dto.getRemark());
                cardActivateTable.setDescription(dto.getDescription());
                cardActivateTable.setModifyTime(new Date());
                cardActivateRepository.save(cardActivateTable);
                mqSendService.send(Constants.WASABICARD_CARD_INFO_REFRESH, JSONObject.toJSONString(table),
                        60 * 1000);
            }
        } catch (Exception e) {
            log.error("卡片激活结果通知回调失败", e);
            throw new ServiceException("卡片激活结果通知回调失败");
        }
    }

    /**
     * 速汇交易通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void expressRemittanceTransactionNotify(WasabiTransactionTransferDto dto) throws ServiceException {
        try {
            CardGlobalOrderTable table = globalOrderRepository.findByOrderNo(dto.getOrderNo());
            if (table == null) {
                throw new ServiceException("订单不存在: {}", dto.getOrderNo());
            }
            CardMerchantUserTable userTable = merchantUserRepository.getByUniqueId(table.getUniqueId());
            // 订单状态为成功 直接返回
            if (table.getStatus().equals(Constants.SUCCESS)) {
                return;
            }
            AtomicBoolean needSupplement = new AtomicBoolean(false);

            // 如果存在需要补充的资料保存到数据库中
            if (CollectionUtils.isNotEmpty(dto.getRfiInfos())) {
                for (WasabiRfiInfosDto rfiInfosDto : dto.getRfiInfos()) {
                    if ((dto.getStatus().equals(GlobalOrderStatusEnum.PROCESSING.getStatus())
                            || dto.getStatus().equals(GlobalOrderStatusEnum.PARTNER_PROCESSING.getStatus())) && ("pending_check".equals(rfiInfosDto.getStatus()) || "rejected".equals(rfiInfosDto.getStatus()))){
                        needSupplement.set(true);
                    }
                    CardGlobalOrderDataTable orderDataTable =
                            globalOrderDataRepository.findByOrderNoAndRfiId(rfiInfosDto.getOrderNo(),
                                    rfiInfosDto.getRfiId());
                    if (orderDataTable == null) {
                        orderDataTable = new CardGlobalOrderDataTable();
                    }
                    BeanUtils.copyProperties(rfiInfosDto, orderDataTable);
                    WasabiRfiFieldInfoDto rfiFieldInfo = rfiInfosDto.getRfiFieldInfo();
                    if (rfiFieldInfo != null) {
                        BeanUtils.copyProperties(rfiFieldInfo, orderDataTable);
                        orderDataTable.setAddTime(new Date());
                        List<WasabiMethodDto> selectValues = rfiFieldInfo.getSelectValues();
                        if (CollectionUtils.isNotEmpty(selectValues)) {
                            globalOrderDataAvailableRepository.deleteAllByOrderNoAndRfiId(rfiInfosDto.getOrderNo(),
                                    rfiInfosDto.getRfiId());
                            for (WasabiMethodDto selectValue : selectValues) {
                                CardGlobalOrderDataAvailableTable availableTable =
                                        new CardGlobalOrderDataAvailableTable();
                                availableTable.setOrderNo(rfiInfosDto.getOrderNo());
                                availableTable.setRfiId(rfiInfosDto.getRfiId());
                                availableTable.setValueId(selectValue.getValueId());
                                availableTable.setValue(selectValue.getValue());
                                availableTable.setAddTime(new Date());
                                globalOrderDataAvailableRepository.save(availableTable);
                            }
                        }
                    }
                    globalOrderDataRepository.save(orderDataTable);
                }
            } else {
                if (dto.getStatus().equals(Constants.SUCCESS)) {
                    List<CardGlobalOrderDataTable> dataTables = globalOrderDataRepository.findAllByOrderNo(dto.getOrderNo());
                    if (CollectionUtils.isNotEmpty(dataTables)){
                        for (CardGlobalOrderDataTable dataTable : dataTables){
                            dataTable.setStatus(GlobalComplianceStatusEnum.APPROVED.getStatus());
                            globalOrderDataRepository.save(dataTable);
                        }
                    }
                }
            }
            if (!table.getStatus().equals(dto.getStatus())) {
                table.setStatus(dto.getStatus());
                table.setFee(dto.getFee());
                table.setComplianceStatus(dto.getComplianceStatus());
                table.setNeedSupplement(needSupplement.get());
                table.setModifyTime(new Date());
                globalOrderRepository.save(table);
            }

            if (needSupplement.get()) {
                // 补充资料邮件
                ucardEmailService.sendGlobalOrderSupplementaryDataEmail(userTable, table);
            }

            if (dto.getStatus().equals(Constants.SUCCESS)) {
                // 发送邮件通知用户
                ucardEmailService.sendGlobalOrderTransactionSuccessEmail(userTable, table);
            } else if (dto.getStatus().equals(Constants.FAIL)) {
                // 订单失败发送邮件通知用户
                ucardEmailService.sendGlobalOrderTransactionFailEmail(userTable, table);
                // 退费
                globalService.refundTransacOrder(table);
            }
        } catch (Exception e) {
            log.error("速汇交易通知回调失败", e);
            throw new ServiceException("速汇交易通知回调失败");
        }
    }
}
