package com.crm.ucard.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseReportResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.ucard.*;
import com.crm.rely.backend.core.entity.ucard.*;
import com.crm.rely.backend.core.pojo.table.CustomInfoTable;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
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.DateUtil;
import com.crm.rely.backend.util.FileProcessUtil;
import com.crm.ucard.config.UcardConfig;
import com.crm.ucard.dao.mapper.*;
import com.crm.ucard.dao.repository.*;
import com.crm.ucard.service.SysConfigService;
import com.crm.ucard.service.SysUcardConfigService;
import com.crm.ucard.service.UcardService;
import com.crm.ucard.util.PayouCardUtil;
import com.crm.ucard.util.RateLimiterUtil;
import com.crm.ucard.util.UcardCommonUtil;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Ucard服务实现类
 */
@Slf4j
@Service
public class UcardServiceImpl implements UcardService {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysUcardConfigService sysUcardConfigService;
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private RateLimiterUtil rateLimiterUtil;
    @Autowired
    private CardApplyRepository cardApplyRepository;
    @Autowired
    private UcardCardRepository cardRepository;
    @Autowired
    private CardActivateRepository cardActivateRepository;
    @Autowired
    private CardRechargeOrderRepository rechargeOrderRepository;
    @Autowired
    private CardMerchantUserRepository merchantUsereRepository;
    @Autowired
    private CardKycAttachmentRepository kycAttachmentRepository;
    @Autowired
    private CardKycStatusRepository kycStatusRepository;
    @Autowired
    private CardOperateRepository CardOperateRepository;
    @Autowired
    private CardGlobalPaymentOrderRepository globalPaymentOrderRepository;
    @Autowired
    private CardGlobalPayerPayeeRepository globalPayerPayeeRepository;
    @Autowired
    private CardGlobalSubmitRepository globalSubmitRepository;
    @Autowired
    private CardTypeRepository cardTypeRepository;
    @Autowired
    private CardTransacOrderRepository cardTransacOrderRepository;
    @Autowired
    private CardTypeMapper cardTypeMapper;
    @Autowired
    private CardMerchantUserMapper cardMerchantUserMapper;
    @Autowired
    private CardKycStatusMapper cardKycStatusMapper;
    @Autowired
    private CardApplyMapper cardApplyMapper;
    @Autowired
    private UcardCardMapper cardMapper;
    @Autowired
    private CardRechargeOrderMapper rechargeOrderMapper;
    @Autowired
    private CardTransacOrderMapper cardTransacOrderMapper;
    @Autowired
    private CardGlobalPaymentOrderMapper globalPaymentOrderMapper;
    @Autowired
    private CardCountryMapper cardCountryMapper;
    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private MqSendService mqSendService;

    @Value("${web.upload-path:./upload}")
    private String UPLOAD;

    private String getMessage(String code)  throws ServiceException {
        return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
    }

    public UcardConfig getUcardConfig() throws ServiceException{
        SysConfigTable sysConfigTable = sysConfigService.getByCode(Constants.UCARD_CARD);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        UcardConfig ucardConfig = JSON.parseObject(sysConfigTable.getValue(), UcardConfig.class);
        return ucardConfig;
    }

    /**
     * 获取卡片类型列表
     * @return 卡片类型列表
     * @throws ServiceException 服务异常
     */
    @Override
    public ResultWithPagerDto<CardTypeDto> getCardTypePageList(CardTypePageEntity entity) throws ServiceException {
        try {
            // 获取总数
            Integer count = cardTypeMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<CardTypeDto> cardlist = cardTypeMapper.pageList(entity);
            SysUcardConfigTable sysUcardConfigTable = sysUcardConfigService.getByCode(Constants.WASABI_CARD_APPLY_AMOUNT);
            if (sysUcardConfigTable == null) {
                throw ServiceException.exception(Constants.SYSTEM_ERROR);
            }
            BigDecimal cardFee = new BigDecimal(sysUcardConfigTable.getValue());
            cardlist.forEach(cardTypeDto -> {
                if (cardTypeDto.getCardFee() == null) {
                    cardTypeDto.setCardFee(cardFee);
                }
            });
            return ResultWithPagerDto.success(pageDto, cardlist);
        } catch (Exception e) {
            log.error("获取卡片类型分页列表失败", e);
            throw new ServiceException("获取卡片类型分页列表失败");
        }
    }

    /**
     * 更新卡片类型列表
     * 频率限制：每秒10次
     * @return 卡片类型列表
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto getCardTypes() throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "getCardTypes";
        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 10.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            String paramStr = PayouCardUtil.initCommonRequest(null,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getCardTypesUrl(),
                    paramStr
            );

            if (!PayouCardUtil.verifySignature(ucardConfig, response)) {
                return BaseResultDto.error(Constants.SYSTEM_ERROR);
            }

            UcardBaseResponse<List<CardTypeDto>> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<List<CardTypeDto>>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            cardTypeRepository.deleteByCardCategory(Constants.CARD_CATEGORY_UCARD);
//            cardTypeCurrencyRepository.deleteByCardCategory(Constants.CARD_CATEGORY_UCARD);

            List<CardTypeDto> list = baseResponse.getData();
            List<CardTypeTable> tables = new ArrayList<>();
//            List<CardTypeCurrencyTable> currencyTables = new ArrayList<>();
            for (CardTypeDto cardTypeDto : list) {
                CardTypeTable table = new CardTypeTable();
                BeanUtils.copyProperties(cardTypeDto, table);
                table.setEnableStatus(3==cardTypeDto.getId()?1:0);
//                table.setCardTypeId(cardTypeDto.getId());
                table.setCardCategory(Constants.CARD_CATEGORY_UCARD);
                tables.add(table);

//                for (RechargeCurrencyInfo currency : cardTypeDto.getRechargeCurrencyInfoList()){
//                    CardTypeCurrencyTable currencyTable = new CardTypeCurrencyTable();
//                    BeanUtils.copyProperties(currency, currencyTable);
//                    currencyTable.setCardTypeId(table.getCardTypeId());
//                    currencyTable.setCardCategory(Constants.CARD_CATEGORY_UCARD);
//                    currencyTables.add(currencyTable);
//                }
            }

            cardTypeRepository.save(tables);
//            cardTypeCurrencyRepository.save(currencyTables);

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("更新卡片类型列表失败", e);
            throw new ServiceException("更新卡片类型列表失败");
        }
    }

    @Override
    public ResultWithPagerDto<MerchantUserDto> getMerchantUserPageList(MerchantUserPageEntity entity) throws ServiceException{
        try {
            // 获取总数
            Integer count = cardMerchantUserMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<MerchantUserDto> pagelist = cardMerchantUserMapper.pageList(entity);
            return ResultWithPagerDto.success(pageDto, pagelist);
        } catch (Exception e) {
            log.error("获取商户用户分页列表失败", e);
            throw new ServiceException("获取商户用户分页列表失败");
        }
    }

    /**
     * 商户账户查询
     * 频率限制：每秒5次
     *
     * @return 商户账户信息
     * @throws ServiceException 服务异常
     */
    @Override
    public BaseResultDto<List<MerchantAccountDto>> queryMerchantAccount() throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "queryMerchantAccount";

        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 5.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            String paramStr = PayouCardUtil.initCommonRequest(null,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getMerchantAccountUrl(),
                    paramStr
            );

            UcardBaseResponse<List<MerchantAccountDto>> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<List<MerchantAccountDto>>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("商户账户查询失败", e);
            throw new ServiceException("商户账户查询失败");
        }
    }

    /**
     * 商户用户注册
     * 频率限制：每秒2次
     *
     * @param entity 注册请求参数
     * @return 注册结果
     * @throws ServiceException 服务异常
     */
    @Override
    public BaseResultDto registerMerchantUser(MerchantUserEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "registerMerchantUser";

        CardMerchantUserTable ctable = merchantUsereRepository.findByCIdAndCardCategory(entity.getCId(),entity.getCardCategory());
        if (ctable != null) {
            return BaseResultDto.error("用户已注册");
        }
        CardMerchantUserTable etable = merchantUsereRepository.getByEmailAndCardCategory(entity.getEmail(),entity.getCardCategory());
        if (etable != null) {
            return BaseResultDto.error("邮箱已注册");
        }
        CardMerchantUserTable ptable = merchantUsereRepository.getByMobileAndCardCategory(entity.getMobile(),entity.getCardCategory());
        if (ptable != null) {
            return BaseResultDto.error("手机号已注册");
        }


        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 2.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            entity.setUniqueId(UUID.randomUUID().toString().replace("-",""));
            entity.setCId(null);
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getMerchantUserRegisterUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            CardMerchantUserTable table = new CardMerchantUserTable();
            BeanUtils.copyProperties(entity, table);
            table.setAddTime(new Date());
            table.setCardCategory(Constants.CARD_CATEGORY_UCARD);
            merchantUsereRepository.save(table);

            return BaseResultDto.success(Constants.SUCCESS,entity.getUniqueId());
        } catch (Exception e) {
            log.error("商户用户注册失败", e);
            throw new ServiceException("商户用户注册失败");
        }
    }

    /**
     * 商户用户信息更新
     * 频率限制：每秒2次
     * @param entity 更新请求参数
     * @return 更新结果
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto updateMerchantUser(MerchantUserEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "updateMerchantUser";

        CardMerchantUserTable etable = merchantUsereRepository.getByEmailAndCardCategory(entity.getEmail(),entity.getCardCategory());
        if (etable != null && !entity.getUniqueId().equals(etable.getUniqueId())) {
            return BaseResultDto.error("邮箱已存在");
        }
        CardMerchantUserTable ptable = merchantUsereRepository.getByMobileAndCardCategory(entity.getMobile(),entity.getCardCategory());
        if (ptable != null && !entity.getUniqueId().equals(ptable.getUniqueId())) {
            return BaseResultDto.error("手机号已存在");
        }

        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 2.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr, ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getMerchantUserUpdateUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(
                    response, new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardMerchantUserTable table = merchantUsereRepository.findByUniqueId(entity.getUniqueId());
            BeanUtils.copyProperties(entity, table);
            table.setModifyTime(new Date());
            merchantUsereRepository.save(table);

            return BaseResultDto.success(0);
        } catch (Exception e) {
            log.error("商户用户信息更新失败", e);
            throw new ServiceException("商户用户信息更新失败");
        }
    }

    /**
     * 获取kyc认证分页列表
     */
    @Override
    public ResultWithPagerDto<CardKycStatusDto> getKycPageList(CardKycStatusPageEntity entity) throws ServiceException {
        try {
            // 获取总数
            Integer count = cardKycStatusMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<CardKycStatusDto> dtos = cardKycStatusMapper.pageList(entity);

            return ResultWithPagerDto.success(pageDto, dtos);
        } catch (Exception e) {
            log.error("获取卡片类型分页列表失败", e);
            throw new ServiceException("获取卡片类型分页列表失败");
        }
    }

    /**
     * 商户用户KYC附件上传
     * 频率限制：每秒1次
     * @param entity 上传请求参数
     * @return 上传结果
     * @throws ServiceException 服务异常
     */
    @Override
    public BaseResultDto uploadKycAttachment(KycAttachmentUploadEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "uploadKycAttachment";

        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 1.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getKycAttachmentUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(
                    response,new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardKycAttachmentTable table = new CardKycAttachmentTable();
            BeanUtils.copyProperties(entity, table);
            table.setCode(baseResponse.getCode());
            table.setAddTime(new Date());
            kycAttachmentRepository.save(table);

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("商户用户KYC附件上传失败", e);
            throw new ServiceException("商户用户KYC附件上传失败");
        }
    }

    /**
     * 提交KYC认证
     * 频率限制：每秒2次
     * @param entity 认证请求参数
     * @return 认证结果
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto submitKyc(KycEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "submitKyc";
        CardKycStatusTable table = kycStatusRepository.findByUniqueIdAndCardTypeId(entity.getUniqueId(),entity.getCardTypeId());
        if(null != table && 1 == table.getStatus()){
            throw new ServiceException("卡片类型正在认证中");
        }
        if(null != table && 2 == table.getStatus()){
            throw new ServiceException("卡片类型已认证");
        }

        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 2.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getKycSubmitUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(
                    response,new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            if(null == table){
                table = new CardKycStatusTable();
                BeanUtils.copyProperties(entity, table);
                table.setAddTime(new Date());
            }
            table.setStatus(1);
            table.setModifyTime(new Date());
            kycStatusRepository.save(table);

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("提交KYC认证失败", e);
            throw new ServiceException("提交KYC认证失败");
        }
    }

    /**
     * 查询KYC认证状态
     * 频率限制：每秒5次
     *
     * @param entity 查询请求参数
     * @return 认证状态
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<KycStatusDto> queryKycStatus(KycEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "queryKycStatus";
        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 5.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getKycStatusUrl(),
                    paramStr
            );

            UcardBaseResponse<KycStatusDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<KycStatusDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            KycStatusDto dto = baseResponse.getData();
            CardKycStatusTable table = kycStatusRepository.findByUniqueIdAndCardTypeId(entity.getUniqueId(),entity.getCardTypeId());
            if (dto.getStatus() != table.getStatus()) {
                table.setStatus(dto.getStatus());
                table.setStatusDesc(dto.getStatusDesc());
                table.setModifyTime(new Date());
                kycStatusRepository.save(table);
            }

            return BaseResultDto.success(dto);
        } catch (ServiceException e) {
            log.error("查询KYC状态失败，错误信息：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("查询KYC状态异常", e);
            throw new ServiceException("查询KYC状态失败，请稍后重试");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto applyCard(CardApplyEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();

        UcardCardTable cardTable = cardRepository.findByUniqueIdAndCardTypeId(entity.getUniqueId(),entity.getCardTypeId());
        if(null != cardTable){
            throw new ServiceException("卡片已申请");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl()+ucardConfig.getCardApplyUrl(),
                    paramStr
            );

            UcardBaseResponse<CardApplyDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<CardApplyDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardApplyDto dto = baseResponse.getData();
            CardApplyTable table = new CardApplyTable();
            BeanUtils.copyProperties(entity, table);
            table.setOrderNo(dto.getOrderNo());
            table.setStatus("0");
            table.setAddTime(new Date());
            cardApplyRepository.save(table);

            mqSendService.send(Constants.UCARD_CARD_APPLY_PROGRESS,JSON.toJSONString(table),3*60*1000);
            mqSendService.send(Constants.UCARD_CARD_APPLY_PROGRESS,JSON.toJSONString(table),10*60*1000);
            mqSendService.send(Constants.UCARD_CARD_APPLY_PROGRESS,JSON.toJSONString(table),60*60*1000);
            mqSendService.send(Constants.UCARD_CARD_APPLY_PROGRESS,JSON.toJSONString(table),3*60*60*1000);
            mqSendService.send(Constants.UCARD_CARD_APPLY_PROGRESS,JSON.toJSONString(table),10*60*60*1000);
            mqSendService.send(Constants.UCARD_CARD_APPLY_PROGRESS,JSON.toJSONString(table),24*60*60*1000);

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("申请卡片失败", e);
            throw new ServiceException("ucard.error.applyCard", getMessage("ucard.error.applyCard"));
        }
    }

    @JmsListener(destination = Constants.UCARD_CARD_APPLY_PROGRESS)
    @Transactional(rollbackFor = Exception.class)
    public void callbackCardApplyProgress(String content) throws ServiceException{
        log.info(String.format("UCARD_CARD_APPLY_PROGRESS,content:%s", content));
        CardApplyTable applyTable = JSON.parseObject(content, CardApplyTable.class);
        if (null == applyTable) {
            log.error("UCARD_CARD_APPLY_PROGRESS,applyTable is null");
            return;
        }

        CardApplyTable table = cardApplyRepository.getByOrderNo(applyTable.getOrderNo());
        if(null == table){
            log.error("UCARD_CARD_APPLY_PROGRESS,table is null");
            return;
        }
        if("0".equals(table.getStatus())){
            CardApplyProgressEntity entity = new CardApplyProgressEntity();
            entity.setHolderMerchantOrderNo(table.getOrderNo());
            this.queryApplyProgress(entity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto queryApplyProgress(CardApplyProgressEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getCardStatusUrl(),
                    paramStr
            );

            UcardBaseResponse<CardApplyProgressDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<CardApplyProgressDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardApplyProgressDto dto = baseResponse.getData();
            CardApplyTable table = cardApplyRepository.findByOrderNo(entity.getHolderMerchantOrderNo());
            BeanUtils.copyProperties(dto, table);
            table.setModifyTime(new Date());
            cardApplyRepository.save(table);

            if("1".equals(dto.getStatus())){
                UcardCardTable cardTable = new UcardCardTable();
                BeanUtils.copyProperties(table, cardTable);
                cardTable.setId(null);

                CardTypeTable cardTypeTable = cardTypeRepository.findByCardTypeId(table.getCardTypeId());
                if("0".equals(cardTypeTable.getType()) || "2".equals(cardTypeTable.getType()) ){
                    cardTable.setStatus("1");
                }else{
                    cardTable.setStatus("-1");
                }

                cardTable.setFreezeStatus("1");
                table.setAddTime(new Date());
                cardRepository.save(cardTable);
            }

            return BaseResultDto.success(dto);
        } catch (Exception e) {
            log.error("查询开卡进度失败", e);
            throw new ServiceException("查询开卡进度失败");
        }
    }

    @Override
    public ResultWithPagerDto<CardApplyDto> getCardApplyPageList(CardApplyPageEntity entity) throws ServiceException {
        try {
            /**
             * 格式化时间
             */
            if (entity.getEndDate() != null) {
                entity.setEndDate(DateUtil.operationDay(entity.getEndDate(), 1));
            }
            // 获取总数
            Integer count = cardApplyMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<CardApplyDto> cardlist = cardApplyMapper.pageList(entity);

            return ResultWithPagerDto.success(pageDto, cardlist);
        } catch (Exception e) {
            log.error("获取卡片申请分页列表失败", e);
            throw new ServiceException("获取卡片申请分页列表失败");
        }
    }

    @Override
    public ResultWithPagerDto<UcardCardDto> getCardPageList(CardPageEntity entity) throws ServiceException {
        try {
            // 获取总数
            Integer count = cardMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<UcardCardDto> cardlist = cardMapper.pageList(entity);
            return ResultWithPagerDto.success(pageDto, cardlist);
        } catch (Exception e) {
            log.error("获取卡片分页列表失败", e);
            throw new ServiceException("获取卡片分页列表失败");
        }
    }

    /**
     * 银行卡激活
     * 频率限制：每秒2次
     *
     * @param entity 激活请求参数
     * @return 激活结果
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<CardActivateDto> activateCard(CardActivateEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            UcardCardTable table = cardRepository.findByCardNo(entity.getCardNo());
            if ("1".equals(table.getStatus())) {
                throw new ServiceException("该卡片已激活");
            }

            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getActivateCardUrl(),
                    paramStr
            );

            UcardBaseResponse<CardActivateDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<CardActivateDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }


            CardActivateTable activatTable = new CardActivateTable();
            BeanUtils.copyProperties(entity, activatTable);
            activatTable.setAddTime(new Date());
            cardActivateRepository.save(activatTable);

            table.setStatus(String.valueOf(baseResponse.getData().getStatus()));
//            table.setStatusStr(baseResponse.getData().getStatusStr());
//            table.setActivePhoto(entity.getActivePhoto());
            table.setModifyTime(new Date());
            cardRepository.save(table);

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("银行卡激活失败", e);
            throw new ServiceException("银行卡激活失败");
        }
    }

    /**
     * 银行卡充值预估到账金额查询
     * 频率限制：每秒5次
     * @param entity 查询请求参数
     * @return 预估到账金额
     * @throws ServiceException 服务异常
     */
    @Override
    public BaseResultDto<CardRechargeEstimateDto> queryRechargeEstimate(CardRechargeEstimateEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "queryRechargeEstimate";

        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 5.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            // 发送请求
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getRechargeEstimateUrl(),
                    paramStr
            );

            UcardBaseResponse<CardRechargeEstimateDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<CardRechargeEstimateDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (ServiceException e) {
            log.error("查询充值预估失败，错误信息：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("查询充值预估异常", e);
            throw new ServiceException("查询充值预估失败，请稍后重试");
        }
    }

    /**
     * 银行卡充值
     * 频率限制：每秒1次
     * @param entity 充值请求参数
     * @return 充值结果
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<CardRechargeDto> rechargeCard(CardRechargeEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "rechargeCard";

        CardMerchantUserTable userTable = merchantUsereRepository.findByUniqueId(entity.getUniqueId());
        CustomInfoTable customTable = customInfoRepository.findFirstByCId(userTable.getCId());
        BigDecimal balance = null == customTable.getBalance()?new BigDecimal(0):customTable.getBalance();
        if(balance.compareTo(entity.getAmount()) < 0){
            return BaseResultDto.error("余额不足！");
        }

        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 1.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }

            entity.setOrderNo(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + RandomStringUtils.randomNumeric(3));
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getRechargeUrl(),
                    paramStr
            );

            UcardBaseResponse<CardRechargeDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<CardRechargeDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }
            CardRechargeDto dto = baseResponse.getData();
            CardRechargeOrderTable table = new CardRechargeOrderTable();
            BeanUtils.copyProperties(entity, table);
            BeanUtils.copyProperties(dto, table);
            table.setAddTime(new Date());
            table.setStatus(String.valueOf(dto.getStatus()));
            table.setMerchantOrderNo(dto.getOrderNo());
            rechargeOrderRepository.save(table);

            customTable.setBalance(balance.subtract(entity.getAmount()));
            customInfoRepository.save(customTable);

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("银行卡充值失败", e);
            throw new ServiceException("银行卡充值失败");
        }
    }

    /**
     * 银行卡充值订单查询
     * 频率限制：每秒5次
     * @param entity 查询请求参数
     * @return 充值订单信息
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<CardRechargeOrderDto> queryRechargeOrder(CardRechargeOrderQueryEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "queryRechargeOrder";

        // 参数检查
        if (entity == null) {
            throw new ServiceException("查询参数不能为空");
        }
        if (Strings.isNullOrEmpty(entity.getMerchantOrderNo())) {
            throw new ServiceException("订单号不能为空");
        }

        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 5.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            // 发送请求
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getCardOrderUrl(),
                    paramStr
            );

            UcardBaseResponse<CardRechargeOrderDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<CardRechargeOrderDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardRechargeOrderDto dto = baseResponse.getData();
            CardRechargeOrderTable table = rechargeOrderRepository.findByMerchantOrderNo(entity.getMerchantOrderNo());
            if(!String.valueOf(dto.getStatus()).equals(table.getStatus())){
                table.setStatus(String.valueOf(dto.getStatus()));
                table.setReceivedCurrency(dto.getReceivedCurrency());
                table.setExchangeRate(dto.getExchangeRate());
                //table.setTime(dto.getTime());
                table.setModifyTime(new Date());
                rechargeOrderRepository.save(table);

                if("2".equals(dto.getStatus())){
                    CardMerchantUserTable userTable = merchantUsereRepository.findByUniqueId(table.getUniqueId());
                    CustomInfoTable customTable = customInfoRepository.findFirstByCId(userTable.getCId());
                    BigDecimal balance = null == customTable.getBalance()?new BigDecimal(0):customTable.getBalance();
                    customTable.setBalance(customTable.getBalance().add(table.getAmount()));
                    customInfoRepository.save(customTable);
                }

            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (ServiceException e) {
            log.error("查询充值订单失败，错误信息：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("查询充值订单异常", e);
            throw new ServiceException("查询充值订单失败，请稍后重试");
        }
    }

    /**
     * 银行卡充值记录查询
     * @param entity
     * @return
     * @throws ServiceException
     */
    @Override
    public BaseResultDto<CardRechargeOrderListDto> queryRechargeRecords(CardRechargeRecordQueryEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {

            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            // 发送请求
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getRechargeOrderUrl(),
                    paramStr
            );

            UcardBaseResponse<CardRechargeOrderListDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<CardRechargeOrderListDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (ServiceException e) {
            log.error("查询充值订单失败，错误信息：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("查询充值订单异常", e);
            throw new ServiceException("查询充值订单失败，请稍后重试");
        }
    }

    /**
     * 充值记录分页查询
     * @param entity
     * @return
     * @throws ServiceException
     */
    @Override
    public BaseReportResultDto<List<CardRechargeOrderDto>, CardRechargeOrderSumDto> queryRechargePageList(CardRechargePageEntity entity) throws ServiceException {
        try {
            /**
             * 格式化时间
             */
            if (entity.getEndDate() != null) {
                entity.setEndDate(DateUtil.operationDay(entity.getEndDate(), 1));
            }
            // 获取总数
            Integer count = rechargeOrderMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return new BaseReportResultDto(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, pageDto);
            }

            List<CardRechargeOrderDto> orderTables = rechargeOrderMapper.pageList(entity);
            CardRechargeOrderSumDto sumDto = rechargeOrderMapper.rechargeOrderSum(entity);
            CardRechargeOrderSumDto dto = CardRechargeOrderSumDto.getInstance();
            if (sumDto != null){
                BeanUtils.copyProperties(sumDto, dto);
            }
            return new BaseReportResultDto(orderTables,dto,pageDto);
        } catch (Exception e) {
            log.error("充值记录分页查询失败", e);
            throw new ServiceException("充值记录分页查询失败");
        }
    }

    @Override
    public BaseResultDto queryCardBalance(CardBalanceEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "queryCardBalance";

        // 参数检查
        if (entity == null) {
            throw new ServiceException("查询参数不能为空");
        }
        if (Strings.isNullOrEmpty(entity.getCardNo())) {
            throw new ServiceException("卡号不能为空");
        }

        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 5.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getBalanceUrl(),
                    paramStr
            );

            UcardBaseResponse<List<CardBalanceDto>> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<List<CardBalanceDto>>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("查询卡片余额失败", e);
            throw new ServiceException("查询卡片余额失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto resetPassword(CardOperateEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "resetPassword";

        // 参数检查
        if (entity == null) {
            throw new ServiceException("重置密码参数不能为空");
        }
        if (Strings.isNullOrEmpty(entity.getCardNo())) {
            throw new ServiceException("卡号不能为空");
        }

        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 1.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getPasswordResetUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardOperateTable table = new CardOperateTable();
            BeanUtils.copyProperties(entity, table);
            table.setOperateType(1);
            table.setAddTime(new Date());
            CardOperateRepository.save(table);

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("找回密码失败", e);
            throw new ServiceException("找回密码失败");
        }
    }

    @Override
    public ResultWithPagerDto<CardTransacOrderDto> getTransacOrderPageList(CardTransacOrderPageEntity entity) throws ServiceException  {
        try {
            // 获取总数
            Integer count = cardTransacOrderMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<CardTransacOrderDto> orderTables = cardTransacOrderMapper.pageList(entity);

            return ResultWithPagerDto.success(pageDto, orderTables);
        } catch (Exception e) {
            log.error("交易信息分页列表查询失败", e);
            throw new ServiceException("交易信息分页列表查询失败");
        }
    }

    @Override
    public BaseResultDto<CardTransacOrderListDto> queryTransactions(CardTransacQueryEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "queryTransactions";

        // 参数检查
        if (entity == null) {
            throw new ServiceException("查询参数不能为空");
        }
        if (Strings.isNullOrEmpty(entity.getCardNo())) {
            throw new ServiceException("卡号不能为空");
        }

        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 5.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getTransactionsUrl(),
                    paramStr
            );

            UcardBaseResponse<CardTransacOrderListDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<CardTransacOrderListDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("查询交易记录异常", e);
            throw new ServiceException("查询交易记录失败，请稍后重试");
        }
    }

    /**
     * 银行卡冻结
     * 频率限制：每秒1次
     * @param entity 冻结请求参数
     * @return 冻结结果
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<CardFreezeDto> freezeCard(CardOperateEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "freezeCard";

        // 参数检查
        if (entity == null) {
            throw new ServiceException("冻结参数不能为空");
        }
        if (Strings.isNullOrEmpty(entity.getCardNo())) {
            throw new ServiceException("卡号不能为空");
        }
        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 1.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        UcardCardTable cardTable = cardRepository.findByCardNo(entity.getCardNo());
        if (cardTable == null && "2".equals(cardTable.getFreezeStatus())) {
            throw new ServiceException("卡片已冻结");
        }

        try {
            // 构建请求参数
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getFreezeCardUrl(),
                    paramStr
            );

            UcardBaseResponse<CardFreezeDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<CardFreezeDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardOperateTable table = new CardOperateTable();
            BeanUtils.copyProperties(entity, table);
            table.setOperateType(2);
            table.setAddTime(new Date());
            CardOperateRepository.save(table);

            if (1 == baseResponse.getData().getStatus() && "1".equals(cardTable.getFreezeStatus())) {
                cardTable.setFreezeStatus("2");
                cardTable.setModifyTime(new Date());
                cardRepository.save(cardTable);
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (ServiceException e) {
            log.error("冻结卡片失败，错误信息：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("冻结卡片异常", e);
            throw new ServiceException("冻结卡片失败，请稍后重试");
        }
    }

    /**
     * 银行卡解冻
     * 频率限制：每秒1次
     *
     * @param entity 解冻请求参数
     * @return 解冻结果
     * @throws ServiceException 服务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<CardFreezeDto> unfreezeCard(CardOperateEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String methodName = "unfreezeCard";

        // 参数检查
        if (entity == null) {
            throw new ServiceException("解冻参数不能为空");
        }
        if (Strings.isNullOrEmpty(entity.getCardNo())) {
            throw new ServiceException("卡号不能为空");
        }
        // 频率限制检查
        if (!rateLimiterUtil.tryAcquire(methodName, 1.0)) {
            throw new ServiceException("请求过于频繁，请稍后再试");
        }

        UcardCardTable cardTable = cardRepository.findByCardNo(entity.getCardNo());
        if (cardTable != null && "1".equals(cardTable.getFreezeStatus())) {
            throw new ServiceException("卡片已解冻");
        }

        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getUnfreezeCardUrl(),
                    paramStr
            );

            UcardBaseResponse<CardFreezeDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<CardFreezeDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardOperateTable table = new CardOperateTable();
            BeanUtils.copyProperties(entity, table);
            table.setOperateType(3);
            table.setAddTime(new Date());
            CardOperateRepository.save(table);

            if (1 == baseResponse.getData().getStatus() && "2".equals(cardTable.getFreezeStatus())) {
                cardTable.setFreezeStatus("1");
                cardTable.setModifyTime(new Date());
                cardRepository.save(cardTable);
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (ServiceException e) {
            log.error("解冻银行卡失败，错误信息：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("解冻银行卡异常", e);
            throw new ServiceException("解冻银行卡失败，请稍后重试");
        }
    }

    /**
     * 查询速汇银行及相关配置
     * 频率限制：每秒5次
     * @return 速汇银行配置信息
     * @throws ServiceException 服务异常
     */
    @Override
    public BaseResultDto<List<GlobalTransferBankDto>> queryBankList() throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        String apiName = "queryBankList";

        try {
            if (!rateLimiterUtil.tryAcquire(apiName, 5.0)) {
                throw new ServiceException("请求过于频繁，请稍后重试");
            }
            String paramStr = PayouCardUtil.initCommonRequest(null,ucardConfig);
            String response = UcardCommonUtil.postJsons(ucardConfig.getApiUrl() + ucardConfig.getBankListUrl(),
                    paramStr
            );

            UcardBaseResponse baseResponse = JSON.parseObject(response, UcardBaseResponse.class);
            List<GlobalTransferBankDto> bankList = JSONArray.parseArray(baseResponse.getData().toString(), GlobalTransferBankDto.class);

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(bankList);
        } catch (Exception e) {
            log.error("查询速汇银行及相关配置失败", e);
            throw new ServiceException("查询速汇银行及相关配置失败");
        }
    }

    @Override
    public BaseResultDto<GlobalExchangeRateDto> queryExchangeRate(GlobalExchangeRateEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getExchangeRateUrl(),
                    paramStr
            );

            UcardBaseResponse<GlobalExchangeRateDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<GlobalExchangeRateDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("查询法币汇率失败", e);
            throw new ServiceException("查询法币汇率失败");
        }
    }

    @Override
    public BaseResultDto validateTransfer(GlobalPaymentEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            entity.setOriginOrderNo(UUID.randomUUID().toString().replace("-",""));
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getValidateTransferUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("代付校验失败", e);
            throw new ServiceException("代付校验失败");
        }
    }

    @Override
    public BaseResultDto validatePayer(GlobalPayerEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getValidatePayerUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("代付付款人校验失败", e);
            throw new ServiceException("代付付款人校验失败");
        }
    }

    @Override
    public BaseResultDto validatePayee(GlobalPayeeEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getValidatePayeeUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("代付收款人校验失败", e);
            throw new ServiceException("代付收款人校验失败");
        }
    }

    @Override
    public BaseResultDto<GlobalPaymentDto> transfer(GlobalPaymentEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {

            CardMerchantUserTable userTable = merchantUsereRepository.findByUniqueId(entity.getUniqueId());

            CustomInfoTable customTable = customInfoRepository.findFirstByCId(userTable.getCId());
            BigDecimal balance = null == customTable.getBalance()?new BigDecimal(0):customTable.getBalance();
            if(balance.compareTo(entity.getAmount()) < 0){
                return BaseResultDto.error("余额不足！");
            }

            entity.setOriginOrderNo(UUID.randomUUID().toString().replace("-",""));
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getTransferUrl(),
                    paramStr
            );

            UcardBaseResponse<GlobalPaymentDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<GlobalPaymentDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardGlobalPaymentOrderTable orderTable = new CardGlobalPaymentOrderTable();
            BeanUtils.copyProperties(entity, orderTable);
            orderTable.setOrderNo(baseResponse.getData().getOrderNo());
            orderTable.setStatus(baseResponse.getData().getStatus());
            orderTable.setAddTime(new Date());
            globalPaymentOrderRepository.save(orderTable);

            CardGlobalPayerPayeeTable table = new CardGlobalPayerPayeeTable();
            BeanUtils.copyProperties(entity.getPayer(), table);
            BeanUtils.copyProperties(entity.getPayee(), table);
            table.setOrderNo(baseResponse.getData().getOrderNo());
            globalPayerPayeeRepository.save(table);

            customTable.setBalance(balance.subtract(entity.getAmount()));
            customInfoRepository.save(customTable);

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("代付失败", e);
            throw new ServiceException("代付失败");
        }
    }

    @Override
    public BaseResultDto<GlobalPaymentOrderListDto> queryOrderList(GlobalTransferOrderEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getOrderListUrl(),
                    paramStr
            );

            UcardBaseResponse<GlobalPaymentOrderListDto> baseResponse = JSON.parseObject( response,
                    new TypeReference<UcardBaseResponse<GlobalPaymentOrderListDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("查询用户订单列表失败", e);
            throw new ServiceException("查询用户订单列表失败");
        }
    }

    /**
     * 用户订单分页查询
     * @param entity
     * @return
     * @throws ServiceException
     */
    @Override
    public ResultWithPagerDto<GlobalPaymentOrderDto> queryOrderPageList(GlobalPaymentPageEntity entity) throws ServiceException {
        try {
            // 获取总数
            Integer count = globalPaymentOrderMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }

            List<GlobalPaymentOrderDto> orderTables = globalPaymentOrderMapper.pageList(entity);

            return ResultWithPagerDto.success(pageDto, orderTables);
        } catch (Exception e) {
            log.error("用户订单分页查询失败", e);
            throw new ServiceException("用户订单分页查询失败");
        }
    }

    @Override
    public BaseResultDto submitDispute(GlobalSubmitDisputeEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getDisputeUrl(),
                    paramStr
            );

            UcardBaseResponse<UcardResultDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<UcardResultDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardGlobalSubmitTable table = new CardGlobalSubmitTable();
            table.setOrderNo(entity.getOrderNo());
            table.setTransferInfos(JSON.toJSONString(entity.getTransferInfos()));
            table.setTransferFiles(JSON.toJSONString(entity.getTransferFiles()));
            table.setAddTime(new Date());
            globalSubmitRepository.save(table);

            return BaseResultDto.success(baseResponse.getCode());
        } catch (Exception e) {
            log.error("提交调单信息或文件失败", e);
            throw new ServiceException("提交调单信息或文件失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<GlobalOrderInfoDto> queryOrderResult(GlobalOrderQueryEntity entity) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();
        try {
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getOrderResultUrl(),
                    paramStr
            );

            UcardBaseResponse<GlobalOrderInfoDto> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<GlobalOrderInfoDto>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                return BaseResultDto.error(baseResponse.getMessage());
            }

            CardGlobalPaymentOrderTable table = globalPaymentOrderRepository.findByOrderNo(entity.getOrderNo());
            if(table.getStatus().equals("B1") || !table.getStatus().equals(baseResponse.getData().getStatus())){
                BeanUtils.copyProperties(baseResponse.getData(), table);
                table.setModifyTime(new Date());
                globalPaymentOrderRepository.save(table);
            }

            return BaseResultDto.success(baseResponse.getData());
        } catch (Exception e) {
            log.error("查询订单结果失败", e);
            throw new ServiceException("查询订单结果失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadFile(MultipartFile file) throws ServiceException {
        UcardConfig ucardConfig = getUcardConfig();

        try {
            String middlePath = "/ucard";
            String path = FileProcessUtil.upload(file, middlePath);
            File upfile = FileProcessUtil.getFile(UPLOAD +path);

            String paramStr = PayouCardUtil.initCommonRequest(null,ucardConfig);
            Map<String,Object> paramMap = JSON.parseObject(paramStr,Map.class);
            String response = UcardCommonUtil.postFormData(ucardConfig.getApiUrl()+ucardConfig.getUplaodFileUrl(),
                    upfile,paramMap
            );

            UcardBaseResponse<String> baseResponse = JSON.parseObject(response,
                    new TypeReference<UcardBaseResponse<String>>() {
                    }
            );

            if (!baseResponse.getSuccess()) {
                throw new ServiceException(baseResponse.getMessage());
            }

//            CardFileTable cardFileTable = new CardFileTable();
//            cardFileTable.setPath(path);
//            cardFileTable.setUcardPath(baseResponse.getData());
//            cardFileTable.setAddTime(new Date());
//            cardFileRepository.save(cardFileTable);

            return baseResponse.getData();
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new ServiceException("上传文件失败");
        }
    }

    @Override
    public List<CardCountryDto> getCardCountryList(CardCountryEntity request) {
        List<CardCountryDto> list = cardCountryMapper.getCardCountryList(request);
        return list;
    }

    @Override
    public void queryOrderInfo() throws ServiceException {

        UcardConfig ucardConfig = getUcardConfig();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        try {
            CardTransacQueryEntity entity = new CardTransacQueryEntity();
            // 查询时间为前一天
            LocalDate yesterday = LocalDate.now().minusDays(1);
            LocalDateTime yesterdayStart = yesterday.atStartOfDay();
            LocalDateTime yesterdayEnd = yesterday.atTime(LocalTime.MAX);

            entity.setBeginDate(yesterdayStart.format(formatter));
            entity.setEndDate(yesterdayEnd.format(formatter));

            // 获取到银行卡信息
            List<UcardCardTable> cardlist = cardRepository.findAll();
            if (cardlist.isEmpty()){
                throw new ServiceException("没有该银行卡号");
            }

            // 批量查询本地已存在的交易记录
            List<String> allCardNos = cardlist.stream().map(UcardCardTable::getCardNo).collect(Collectors.toList());
            List<CardTransacOrderTable> localOrders = cardTransacOrderRepository.findByCardNoIn(allCardNos);
            Set<String> localOriginTransactionIds = localOrders.stream()
                    .map(CardTransacOrderTable::getOriginTradeNo)
                    .collect(Collectors.toSet());

            List<CardTransacOrderTable> tablesToSave = new ArrayList<>();
            for (UcardCardTable table : cardlist) {
                String cardNo = table.getCardNo();
                String uniqueId = table.getUniqueId();

                int page = 1;
                while (true){
                    entity.setCardNo(cardNo);
                    entity.setUniqueId(uniqueId);
                    entity.setPage((long) page);
                    entity.setPageSize(30L);

                    String entityStr = JSON.toJSONString(entity);
                    String paramStr = PayouCardUtil.initCommonRequest(entityStr, ucardConfig);
                    String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getTransactionsUrl(),
                            paramStr
                    );

                    UcardBaseResponse<CardTransacOrderListDto> baseResponse = JSON.parseObject(response,
                            new TypeReference<UcardBaseResponse<CardTransacOrderListDto>>() {
                            }
                    );

                    if (!baseResponse.getSuccess()) {
                        throw new ServiceException(baseResponse.getMessage());
                    }

                    //远程银行卡交易信息
                    List<CardTransacOrderDto> transacOrderDtos = baseResponse.getData().getRecords();

                    //比对数据
                    for (CardTransacOrderDto dto : transacOrderDtos) {
                        if (!localOriginTransactionIds.contains(dto.getOriginTradeNo())) {
                            CardTransacOrderTable saveTable = new CardTransacOrderTable();
                            BeanUtils.copyProperties(dto, saveTable);
                            tablesToSave.add(saveTable);
                        }
                    }

                    if (transacOrderDtos.size() < 30) {
                        break;
                    }
                    page++;
                }
            }

            if (!tablesToSave.isEmpty()) {
                cardTransacOrderRepository.save(tablesToSave);
                log.info("本次同步新增 {} 条交易记录", tablesToSave.size());
            }else {
                log.info("本次同步无新增交易记录");
            }

        } catch (Exception e) {
            log.error("银行卡交易信息数据定时同步异常", e);
            throw new ServiceException("银行卡交易信息数据定时同步失败，请稍后重试");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleGlobalTransferNotify(GlobalTransferNotifyDto notify,UcardConfig ucardConfig) throws ServiceException {
        try {
            // 查询订单
            CardGlobalPaymentOrderTable order = globalPaymentOrderRepository.findByOrderNo(notify.getOrderNo());
            if (order == null) {
                throw new ServiceException("订单不存在");
            }

            GlobalOrderQueryEntity entity = new GlobalOrderQueryEntity();
            entity.setOrderNo(notify.getOrderNo());
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getOrderResultUrl(),paramStr);

            UcardBaseResponse<GlobalOrderInfoDto> baseResponse = JSON.parseObject(response,new TypeReference<UcardBaseResponse<GlobalOrderInfoDto>>() {});
            if (!baseResponse.getSuccess()) {
                throw new ServiceException(baseResponse.getMessage());
            }
            if(!notify.getStatus().equals(baseResponse.getData().getStatus())){
                throw new ServiceException("系统错误");
            }

            if(!order.getStatus().equals(notify.getStatus())){
                BeanUtils.copyProperties(notify, order);
                order.setModifyTime(new Date());
                globalPaymentOrderRepository.save(order);
            }

        } catch (Exception e) {
            log.error("处理支付结果回调失败", e);
            throw new ServiceException("处理充支付结果回调失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleGlobalTransferSubmitNotify(GlobalTransferSubmitNotifyDto notify,UcardConfig ucardConfig) throws ServiceException {
        try {
            // 查询订单
            CardGlobalPaymentOrderTable order = globalPaymentOrderRepository.findByOrderNo(notify.getOrderNo());
            if (order == null) {
                throw new ServiceException("订单不存在");
            }

            GlobalOrderQueryEntity entity = new GlobalOrderQueryEntity();
            entity.setOrderNo(notify.getOrderNo());
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getOrderResultUrl(), paramStr);

            UcardBaseResponse<GlobalOrderInfoDto> baseResponse = JSON.parseObject(response,new TypeReference<UcardBaseResponse<GlobalOrderInfoDto>>() {});
            if (!baseResponse.getSuccess()) {
                throw new ServiceException(baseResponse.getMessage());
            }
            if(!notify.getStatus().equals(baseResponse.getData().getStatus())){
                throw new ServiceException("系统错误");
            }

            if(!order.getStatus().equals(notify.getStatus())){
                order.setStatus(notify.getStatus());
                order.setModifyTime(new Date());
                globalPaymentOrderRepository.save(order);
            }
        } catch (Exception e) {
            log.error("调单通知回调失败", e);
            throw new ServiceException("调单通知回调失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleKycNotify(KycNotifyDto notify,UcardConfig ucardConfig) throws ServiceException {
        try {
            CardKycStatusTable table = kycStatusRepository.findByUniqueIdAndCardTypeId(notify.getUniqueId(),notify.getCardTypeId());
            if (table == null) {
                throw new ServiceException("kyc未认证");
            }

            KycEntity entity = new KycEntity();
            entity.setUniqueId(notify.getUniqueId());
            entity.setCardTypeId(notify.getCardTypeId());
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getKycStatusUrl(),paramStr);

            UcardBaseResponse<KycStatusDto> baseResponse = JSON.parseObject(response,new TypeReference<UcardBaseResponse<KycStatusDto>>() {});
            if (!baseResponse.getSuccess()) {
                throw new ServiceException(baseResponse.getMessage());
            }
            if(!notify.getStatus().equals(baseResponse.getData().getStatus())){
                throw new ServiceException("系统错误");
            }

            if (notify.getStatus() != table.getStatus()) {
                table.setStatus(notify.getStatus());
                table.setStatusDesc(notify.getStatusDesc());
                table.setModifyTime(new Date());
                kycStatusRepository.save(table);
            }
        } catch (Exception e) {
            log.error("用户KYC通知回调失败", e);
            throw new ServiceException("用户KYC通知回调失败");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleCardRecharge(CardRechargeNotifyDto notify,UcardConfig ucardConfig) throws ServiceException {
        try {
            CardRechargeOrderTable table = rechargeOrderRepository.findByMerchantOrderNo(notify.getOrderNo());
            if (table == null) {
                throw new ServiceException("订单不存在");
            }

            CardRechargeOrderQueryEntity entity = new CardRechargeOrderQueryEntity();
            entity.setMerchantOrderNo(notify.getOrderNo());
            String entityStr = JSON.toJSONString(entity);
            String paramStr = PayouCardUtil.initCommonRequest(entityStr,ucardConfig);
            // 发送请求
            String response = UcardCommonUtil.postJson(ucardConfig.getApiUrl() + ucardConfig.getCardOrderUrl(),paramStr);

            UcardBaseResponse<CardRechargeOrderDto> baseResponse = JSON.parseObject( response,new TypeReference<UcardBaseResponse<CardRechargeOrderDto>>() {});
            if (!baseResponse.getSuccess()) {
                throw new ServiceException(baseResponse.getMessage());
            }
            CardRechargeOrderDto dto = baseResponse.getData();
            if(!dto.getStatus().equals(String.valueOf(notify.getStatus()))){
                throw new ServiceException("系统错误");
            }

            if(!String.valueOf(notify.getStatus()).equals(table.getStatus())){
                BeanUtils.copyProperties(notify, table);
                table.setReceivedCurrency(dto.getReceivedCurrency());
                table.setExchangeRate(dto.getExchangeRate());
                //table.setTime(dto.getTime());
                table.setModifyTime(new Date());
                rechargeOrderRepository.save(table);

                if("2".equals(dto.getStatus())){
                    CardMerchantUserTable userTable = merchantUsereRepository.findByUniqueId(table.getUniqueId());
                    CustomInfoTable customTable = customInfoRepository.findFirstByCId(userTable.getCId());
                    customTable.setBalance(customTable.getBalance().add(table.getAmount()));
                    customInfoRepository.save(customTable);
                }
            }

        } catch (Exception e) {
            log.error("卡片充值结果通知回调失败", e);
            throw new ServiceException("卡片充值结果通知回调失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleCardActivate(CardActivateNotifyDto notify) throws ServiceException {
        try {
            UcardCardTable table = cardRepository.findByCardNo(notify.getCardNo());
            if (table == null) {
                throw new ServiceException("卡片不存在");
            }
            if ("0".equals(table.getStatus())) {
                table.setStatus(5 == notify.getStatus() ? "1" : "2");
//                table.setStatusStr(notify.getMsg());
                table.setModifyTime(new Date());
                cardRepository.save(table);
            }

        } catch (Exception e) {
            log.error("卡片激活结果通知回调失败", e);
            throw new ServiceException("卡片激活结果通知回调失败");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleCardFreeze(CardFreezeNotifyDto notify) throws ServiceException {
        try {
            UcardCardTable cardTable = cardRepository.findByCardNo(notify.getCardNo());
            if (1 == notify.getStatus()) {
                if (1 == notify.getRequestType() && "1".equals(cardTable.getFreezeStatus())) {
                    cardTable.setFreezeStatus("2");
                } else if (2 == notify.getRequestType() && "2".equals(cardTable.getFreezeStatus())) {
                    cardTable.setFreezeStatus("1");
                }
                cardTable.setModifyTime(new Date());
                cardRepository.save(cardTable);
            }

        } catch (Exception e) {
            log.error("卡片冻结、解冻、重发PIN处理状态回调失败", e);
            throw new ServiceException("卡片冻结、解冻、重发PIN处理状态回调失败");
        }

    }

    @Override
    public void handleVerify3DS(CardVerify3DSNotifyDto notify) throws ServiceException {
        try {

        } catch (Exception e) {
            log.error("3DS校验结果通知回调失败", e);
            throw new ServiceException("卡3DS校验结果通知回调失败");
        }
    }

    @Override
    public void handCardBillStatement(CardTransacOrderNotifyDto notify) throws ServiceException {
        try {
            CardTransacOrderTable table = new CardTransacOrderTable();
            BeanUtils.copyProperties(notify, table);
            table.setModifyTime(new Date());
            cardTransacOrderRepository.save(table);

        } catch (Exception e) {
            log.error("消费账单事件结果通知回调失败", e);
            throw new ServiceException("消费账单事件结果通知回调失败");
        }
    }

}
