package com.cool.store.service.wallet.impl;

import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.dao.*;
import com.cool.store.dao.store.StoreMasterSignerInfoDAO;
import com.cool.store.dao.wallet.OpenBankInfoDAO;
import com.cool.store.dao.wallet.TempOpenWalletInfoDAO;
import com.cool.store.dao.wallet.WalletPaymentOrderDAO;
import com.cool.store.dto.wallet.*;
import com.cool.store.entity.*;
import com.cool.store.entity.store.StoreMasterSignerInfoDO;
import com.cool.store.entity.wallet.OpenBankInfoDO;
import com.cool.store.entity.wallet.TempOpenWalletInfoDO;
import com.cool.store.entity.wallet.WalletPaymentOrderDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.MessageEnum;
import com.cool.store.enums.UserRoleEnum;
import com.cool.store.enums.point.ShopSubStageEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.enums.wallet.BankAccountTypeEnum;
import com.cool.store.enums.wallet.BankBusinessTypeEnum;
import com.cool.store.enums.wechat.WalletTypeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.ApplyLicenseMapper;
import com.cool.store.request.wallet.*;
import com.cool.store.service.UserAuthMappingService;
import com.cool.store.service.dict.impl.DictService;
import com.cool.store.service.impl.CommonService;
import com.cool.store.service.wallet.*;
import com.cool.store.utils.BeanUtil;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.UUIDUtils;
import com.cool.store.vo.wallet.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 钱包 服务实现类
 * </p>
 *
 * @author wangff
 * @since 2025/11/13
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WalletServiceImpl implements WalletService {
    private final ShopInfoDAO shopInfoDAO;
    private final ShopStageInfoDAO shopStageInfoDAO;
    private final ApplyLicenseMapper applyLicenseMapper;
    private final WalletApiService walletApiService;
    private final WalletPaymentOrderDAO walletPaymentOrderDAO;
    private final LineInfoDAO lineInfoDAO;
    private final RedisUtilPool redisUtilPool;
    private final QualificationsInfoDAO qualificationsInfoDAO;
    private  final StoreDao storeDao;
    private final StoreMasterSignerInfoDAO storeMasterSignerInfoDAO;
    private final TempOpenWalletInfoDAO tempOpenWalletInfoDAO;
    private final OpenBankInfoDAO openBankInfoDAO;
    private final DictService dictService;
    private final UserAuthMappingService userAuthMappingService;
    private final CommonService commonService;
    private final WalletTradeService walletTradeService;
    @Value("${wallet.org.id}")
    private Long orgId;

    private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Boolean accountCreate(AccountCreateRequest request) {
        ShopInfoDO shopInfo = getAndVerifyShopAndStage(request.getShopId());
        // 存储银行卡信息
        OpenBankInfoDO openBankInfoDO = OpenBankInfoDO.builder()
                .storeId(shopInfo.getStoreId())
                .settlementCard(request.getBankNumber())
                .bankBranchName(request.getBankName())
                .bankBranchCode(request.getBankNo())
                .bankReservedPhone(request.getBankMobile())
                .source(1)
                .build();
        openBankInfoDAO.insertOrUpdateByStoreId(openBankInfoDO);
        // 调用 创建门店签约人账户接口
        CreateStoreAndAccountRequest accountRequest = CreateStoreAndAccountRequest.builder()
                .outStoreId(shopInfo.getStoreId())
                .phoneNumber(request.getMobile())
                .accountType(BankAccountTypeEnum.PRIVATE.getType())
                .businessType(BankBusinessTypeEnum.PERSONAL.getType())
                .legalName(request.getUserName())
                .legalNo(request.getIdCardNo())
                .accountAliasName(request.getUserName() + "_" + UUIDUtils.get8UUID())
                .accountCardNo(request.getBankNumber())
                .accountPhone(request.getBankMobile())
                .bankNo(request.getBankNo())
                .bankName(request.getBankName())
                .build();
        StoreAccountDTO storeAndAccount = walletApiService.createStoreAndAccount(accountRequest);
        return StringUtils.isNotBlank(storeAndAccount.getAccountNo());
    }

    @Override
    public AccountAuthenticationVO authentication(WalletShopRequest request) {
        ShopInfoDO shopInfo = getAndVerifyShopAndStage(request.getShopId());
        // 调用 门店签约人账户鉴权申请接口
        AccountAuthenticationDTO authentication = walletApiService.authentication(new OutStoreIdRequest(shopInfo.getStoreId()));
        if (Objects.nonNull(authentication)) {
            if (authentication.getAccountStatus().equals(4)) {
                // 判断营业执照是否已经上传，已上传则调用打标接口
                addTagIfUploadLicense(request.getShopId(), shopInfo.getStoreId(), shopInfo.getLineId());
                // 直接返回开通成功的，流程流转
                // 判断一下缴费阶段是否开启，未开启则开启缴费阶段
                try {
                    walletOpenComplete(shopInfo);
                } catch (Exception e) {
                    log.info("阶段流转失败");
                }
            }
            return new AccountAuthenticationVO(authentication.getAccountStatus());
        }
        throw new ServiceException(ErrorCodeEnum.WALLET_OPEN_ACCOUNT_FAIL);
    }

    @Override
    public Boolean openAccount(AccountOpenRequest request) {
        // 校验阶段是否合法
        ShopInfoDO shopInfo = getAndVerifyShopAndStage(request.getShopId());

        // 调用 门店签约人账户开通接口
        log.info("开通账户");
        AccountVerifyDTO accountVerifyDTO = walletApiService.openAccount(new AccountVerifyRequest(shopInfo.getStoreId(), request.getCode()));
        if (!CommonConstants.INDEX_ONE.equals(accountVerifyDTO.getOpenStatus())) {
            throw new ServiceException(ErrorCodeEnum.WALLET_OPEN_ACCOUNT_FAIL);
        }

        walletOpenComplete(shopInfo);

        // 判断营业执照是否已经上传，已上传则调用打标接口
        addTagIfUploadLicense(request.getShopId(), shopInfo.getStoreId(), shopInfo.getLineId());
        return true;
    }

    public void walletOpenComplete(ShopInfoDO shopInfo) {
        // 更新钱包开通阶段状态
        List<ShopSubStageStatusEnum> updateSubStageList = new ArrayList<>();
        updateSubStageList.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_61);
        // 判断一下缴费阶段是否开启，未开启则开启缴费阶段  useStandardStore 普通店   标准店开启选配店型
        if (shopInfo.getUseStandardStore()==0){
            ShopStageInfoDO payStage = shopStageInfoDAO.getShopSubStageInfo(shopInfo.getId(), ShopSubStageEnum.SHOP_STAGE_7);
            if (ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_00.getShopSubStageStatus().equals(payStage.getShopSubStageStatus())) {
                updateSubStageList.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_70);
                LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
                Set<String> publishFranchiseFeeUsers = new HashSet<>();
                List<EnterpriseUserDO> joinUser = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.JOIN_OFFICE, lineInfo.getRegionId());
                if (Objects.nonNull(joinUser)) {
                    Set<String> joinUserIds = joinUser.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toSet());
                    publishFranchiseFeeUsers.addAll(joinUserIds);
                }
                List<EnterpriseUserDO> regionUser = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.REGION_OFFICE, lineInfo.getRegionId());
                if (Objects.nonNull(regionUser)) {
                    Set<String> regionUserIds = regionUser.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toSet());
                    publishFranchiseFeeUsers.addAll(regionUserIds);
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("partnerUsername", lineInfo.getUsername());
                map.put("partnerMobile", lineInfo.getMobile());
                //发送工作通知
                commonService.sendQWMessage(new ArrayList<>(publishFranchiseFeeUsers),
                        MessageEnum.MESSAGE_23,
                        map);
            }
        }else{
            updateSubStageList.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_280);
        }

        shopStageInfoDAO.batchUpdateShopStageStatus(shopInfo.getId(), updateSubStageList);
    }

    @Override
    public PageInfo<BankVO> getBankList(BankListRequest request) {
        GetBankRequest getBankRequest = new GetBankRequest();
        WalletBasicPageInfo pageParam = new WalletBasicPageInfo();
        pageParam.setCurrentPage(request.getPageNum());
        pageParam.setPageSize(request.getPageSize());
        getBankRequest.setPage(pageParam);
        getBankRequest.setHeadName(request.getHeadName());
        getBankRequest.setKeyword(request.getKeyword());
        getBankRequest.setHeadCode(request.getHeadCode());
        BankListDTO bankListDTO = walletApiService.getBankList(getBankRequest);
        return toPageInfo(bankListDTO.getPageData(), BankVO.class, bankListDTO.getPage());
    }

    public static <T, R> PageInfo<R> toPageInfo(List<T> list, Class<R> clazz, WalletBasicPageInfo page) {
        PageInfo<R> result = new PageInfo<>();
        result.setPageNum(page.getCurrentPage());
        result.setPageSize(page.getPageSize());
        result.setPages(page.getCount());
        result.setTotal(page.getTotal());
        result.setList(CollectionUtils.isNotEmpty(list) ? (list.get(0).getClass().equals(clazz) ? (List<R>) list : BeanUtil.toList(list, clazz)) : Collections.emptyList());
        return result;
    }

    @Override
    public void addTagIfUploadLicense(Long shopId, String storeId, Long lineId) {
        LicenseTransactDO license = applyLicenseMapper.selectByShopId(shopId);
        // 营业执照已上传，调用打标接口
        if (Objects.nonNull(license) && StringUtils.isNotBlank(license.getCreditUrl())) {
            try {
                // 判断一下账户的开通状态
                if (enableAddTag(storeId)) {
                    OpenBankInfoDO openBankInfo = getAndUpdateOpenBankInfo(storeId, lineId, license);
                    // 调用 签约人账户打标（升级）接口
                    log.info("营业执照已上传，账户打标");
                    AccountAddTagRequest tagRequest = AccountAddTagRequest.builder()
                            .outStoreId(storeId)
                            .licenseNo(openBankInfo.getBusinessLicenseCode())
                            .licenseName(openBankInfo.getBusinessLicenseName())
                            .legalName(openBankInfo.getLegalName())
                            .legalNo(openBankInfo.getLegalIdCard())
                            .legalPhone(openBankInfo.getLegalPhone())
                            .certPhotoA(openBankInfo.getLegalIdCardFront())
                            .certPhotoB(openBankInfo.getLegalIdCardBack())
                            .licensePhoto(openBankInfo.getBusinessLicensePhoto())
                            .signatoryPhotoA(openBankInfo.getSignerIdCardFront())
                            .signatoryPhotoB(openBankInfo.getSignerIdCardBack())
                            .build();
                    executeAddTag(tagRequest);
                }
            } catch (ServiceException e) {
                // 平安打标 签约人和法人一致时，同步返回，失败原因从msg中取
                String key = MessageFormat.format(RedisConstant.WALLET_OPEN_FAIL, storeId, WalletTypeEnum.PING_AN.getType());
                redisUtilPool.setString(key, e.getErrorCode().equals(ErrorCodeEnum.WALLET_API_ERROR.getCode()) ? e.getMessage() : "系统异常");
                log.info("营业执照已上传，接口异常", e);
            } catch (Exception e) {
                log.error("营业执照已上传，打标失败", e);
            }
        }
    }

    /**
     * 执行打标接口，执行失败缓存标记
     */
    private void executeAddTag(AccountAddTagRequest tagRequest) {
        AddTagDTO addTagDTO = walletApiService.addTag(tagRequest);
        log.info("打标接口调用成功，response:{}", JSONObject.toJSONString(addTagDTO));
        // 如果网商创建失败，缓存标记
        if (CommonConstants.INDEX_TWO.equals(addTagDTO.getWsStatus())) {
            redisUtilPool.setString(MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_TAG_FAIL, tagRequest.getOutStoreId()), "1");
        } else {
            // 网商创建成功，记录已激活状态
            redisUtilPool.setString(MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_ACTIVATED, tagRequest.getOutStoreId()), "1");
        }
    }

    /**
     * 获取并更新门店开通网商信息
     */
    private OpenBankInfoDO getAndUpdateOpenBankInfo(String storeId, Long lineId, LicenseTransactDO license) {
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(lineId);
        QualificationsInfoDO qualificationsInfoDO = qualificationsInfoDAO.getByLineId(lineId);
        OpenBankInfoDO openBankInfoDO = OpenBankInfoDO.builder()
                .storeId(storeId)
                .signerName(lineInfoDO.getUsername())
                .signerIdCard(qualificationsInfoDO.getIdCardNo())
                .signerPhone(lineInfoDO.getMobile())
                .signerIdCardFront(qualificationsInfoDO.getFrontOfIdCard())
                .signerIdCardBack(qualificationsInfoDO.getBackOfIdCard())
                .businessLicenseName(license.getBusinessLicense())
                .businessLicenseCode(license.getCreditCode())
                .businessLicensePhoto(license.getCreditUrl())
                .legalName(license.getLicenseLegalPerson())
                .legalIdCard(license.getLicenseLegalIdCardNo())
                .legalPhone(license.getLicenseLegalMobile())
                .legalIdCardFront(license.getLicenseLegalIdCardFront())
                .legalIdCardBack(license.getLicenseLegalIdCardBack())
                .build();
        openBankInfoDAO.insertOrUpdateByStoreId(openBankInfoDO);
        return openBankInfoDO;
    }

    /**
     * 账户存在且未打标
     */
    private boolean enableAddTag(String storeId) {
        List<AccountInfoDTO> accountInfo = walletApiService.getAccountInfo(new OutStoreIdRequest(storeId));
        return CollectionUtils.isNotEmpty(accountInfo) && accountInfo.size() == 1 && accountInfo.get(0).getLabelingStatus().equals(0);
    }

    @Override
    public Boolean addTagCallback(AddTagCallbackNoticeRequest request) {
        try {
            String key = MessageFormat.format(RedisConstant.WALLET_OPEN_FAIL, request.getOutStoreId(), WalletTypeEnum.PING_AN.getType());
            if (Integer.valueOf(2).equals(request.getStatus())) {
                redisUtilPool.setString(key, request.getErrorMsg());
            } else {
                redisUtilPool.delKey(key);
            }
        } catch (Exception e) {
            log.info("平安打标回调失败", e);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean largePaymentCallback(PaymentDTO request) {
        try {
            walletPaymentOrderDAO.updateOrderByPaymentId(request.getOutStoreId(), request.getPaymentId(), request.getOrderStatus());
        } catch (Exception e) {
            log.error("大额充值回调失败", e);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean onlineCommercialBankCallback(OnlineCommercialBankCallbackRequest request) {
        try {
            String key = MessageFormat.format(RedisConstant.WALLET_OPEN_FAIL, request.getOutStoreId(), "1");
            if (Integer.valueOf(5).equals(request.getAccountStatus())) {
                redisUtilPool.setString(key, request.getFailReason());
            } else {
                // 开通成功，判断是否为新开店，如果是进行阶段流转
                ShopInfoDO shopInfo = shopInfoDAO.getShopInfoByStoreId(request.getOutStoreId());
                if (Objects.nonNull(shopInfo)) {
                    ShopStageInfoDO payStage = shopStageInfoDAO.getShopSubStageInfo(shopInfo.getId(), ShopSubStageEnum.SHOP_STAGE_6);
                    if (ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_60.getShopSubStageStatus().equals(payStage.getShopSubStageStatus())) {
                        walletOpenComplete(shopInfo);
                    }
                }
                redisUtilPool.delKey(key);
            }
            // 如果创建成功，删除网商开通失败标识
            if (Integer.valueOf(4).equals(request.getAccountStatus())) {
                redisUtilPool.delKey(MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_TAG_FAIL, request.getOutStoreId()));
                redisUtilPool.delKey(MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_ACTIVATED, request.getOutStoreId()));
            }
        } catch (Exception e) {
            log.info("平安打标回调失败", e);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean accountTradeCallback(AccountTradeCallbackRequest request) {
//        if (CommonConstants.INDEX_ONE.equals(request.getTradeType())) {
//            walletTradeService.tradeCallback(request.getOutStoreId(), request.getReqNo(), String.valueOf(request.getTradeId()), request.getTradeStatus());
//        }
        return Boolean.TRUE;
    }

    @Override
    public AccountDataVO getAccountList(AccountQueryRequest request) {
        String storeId = getStoreId(request);
        List<AccountInfoDTO> accountInfo = walletApiService.getAccountInfo(new OutStoreIdRequest(storeId));
        List<AccountInfoVO> accountList = accountInfo.stream()
                .filter(v -> Objects.isNull(request.getWalletType()) || request.getWalletType().equals(v.getWalletType()))
                .map(v -> {
                    AccountInfoVO vo = BeanUtil.toBean(v, AccountInfoVO.class);
                    String key = MessageFormat.format(RedisConstant.WALLET_OPEN_FAIL, storeId, String.valueOf(v.getWalletType()));
                    vo.setFailReason(redisUtilPool.getString(key));
                    return vo;
                }).collect(Collectors.toList());
        boolean onlineBankOpenFail = false;
        boolean activated = false;
        if (WalletTypeEnum.ONLINE_BANK.getType().equals(request.getWalletType())) {
            onlineBankOpenFail = getOnlineBankFailTag(storeId);
            String key = MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_ACTIVATED, storeId);
            activated = StringUtils.isNotBlank(redisUtilPool.getString(key));
        }
        return new AccountDataVO(onlineBankOpenFail, activated, accountList);
    }

    @Override
    public AccountInfoVO getAccountInfo(AccountQueryRequest request) {
        String storeId = getStoreId(request);
        List<AccountInfoDTO> accountInfo = walletApiService.getAccountInfo(new OutStoreIdRequest(storeId));
        AccountInfoDTO accountInfoDTO = accountInfo.stream().filter(v -> v.getAccountNo().equals(request.getAccountNo())).findFirst().orElse(null);
        return BeanUtil.toBean(accountInfoDTO, AccountInfoVO.class);
    }

    @Override
    public AccountBillPageVO getBillPage(AccountBillQueryRequest request) {
        String storeId = getStoreId(request);
        LocalDate now = LocalDate.now();
        if (Objects.isNull(request.getBeginDate()) || Objects.isNull(request.getEndDate())) {
            request.setBeginDate(Date.valueOf(now.withDayOfMonth(1)));
            request.setEndDate(Date.valueOf(now));
        }
        BillPageRequest billPageRequest = BillPageRequest.builder()
                .outStoreId(storeId)
                .beginDate(DateUtil.format(request.getBeginDate(), "yyyy-MM-dd HH:mm:ss"))
                .endDate(DateUtil.format(request.getEndDate(), "yyyy-MM-dd HH:mm:ss"))
                .walletType(request.getWalletType())
                .isLegal(request.getIsLegal())
                .recordType(request.getRecordType())
                .feeItemId(request.getFeeItemId())
                .currentPage(request.getPageNum())
                .pageSize(request.getPageSize())
                .build();
        BillPageDTO billPage = walletApiService.getBillPage(billPageRequest);
        PageInfo<TradeRecordDTO> data = toPageInfo(billPage.getPageData(), TradeRecordDTO.class, billPage.getPage());
        return new AccountBillPageVO(data, billPage.getGetAmount(), billPage.getUseAmount());
    }

    @Override
    public TradeRecordDTO getBillDetail(BillDetailRequest request) {
        return walletApiService.getBillDetail(request);
    }

    @Override
    public Boolean passwordUpdate(AccountPasswordRequest request) {
        String storeId = getStoreId(request);
        UpdatePasswordRequest passwordRequest = BeanUtil.toBean(request, UpdatePasswordRequest.class);
        passwordRequest.setOutStoreId(storeId);
        walletApiService.upholdPwd(passwordRequest);
        return true;
    }

    @Override
    public PasswordDTO existPassword(OutStoreIdRequest request) {
        PasswordDTO passwordDTO = walletApiService.passwordIsExist(request);
        List<AccountInfoDTO> list = walletApiService.getAccountInfo(request);
        Boolean isExistAccount = false;
        if (CollectionUtils.isNotEmpty( list)){
            isExistAccount = Boolean.TRUE;
        }
        passwordDTO.setIsExistAccount(isExistAccount);
        return passwordDTO;
    }

    @Override
    public AccountPaymentVO payment(AccountPaymentRequest request) {
        ShopInfoDO shopInfo = null;
        if (Objects.nonNull(request.getShopId())) {
            shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        } else if (StringUtils.isNotBlank(request.getStoreId())) {
            shopInfo = shopInfoDAO.getShopInfoByStoreId(request.getStoreId());
        }
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        String storeId = shopInfo.getStoreId();
        LineInfoDO lineInfo = lineInfoDAO.getByPartnerId(shopInfo.getPartnerId());
        if (Objects.isNull(lineInfo)) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        String paymentId = UUIDUtils.get32UUID();
        LargePaymentRequest paymentRequest = new LargePaymentRequest(storeId, paymentId, lineInfo.getUsername(), request.getAmount().toString());
        LargePaymentDTO resultDTO = walletApiService.largePayment(paymentRequest);

        long expiryCountdown = 0;
        if (StringUtils.isNotBlank(resultDTO.getExpireTime())) {
            expiryCountdown = Math.max(0, Duration.between(LocalDateTime.now(), LocalDateTime.parse(resultDTO.getExpireTime(), formatter)).getSeconds());
        }
        WalletPaymentOrderDO orderDO = WalletPaymentOrderDO.builder()
                .storeId(storeId)
                .paymentId(paymentId)
                .type(0)
                .amount(request.getAmount())
                .expireTime(resultDTO.getExpireTime())
                .orderStatus(3)
                .build();
        walletPaymentOrderDAO.insertSelective(orderDO);
        AccountPaymentVO result = BeanUtil.toBean(resultDTO, AccountPaymentVO.class);
        result.setExpiryCountdown(expiryCountdown);
        return result;
    }

    @Override
    public PageInfo<WalletPaymentOrderVO> nonPaymentOrderPage(LargePaymentQueryRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        String storeId = getStoreId(request);
        List<WalletPaymentOrderDO> list = walletPaymentOrderDAO.getNonPaymentList(storeId);
        PageInfo<WalletPaymentOrderDO> page = new PageInfo<>(list);
        return BeanUtil.toPage(page, WalletPaymentOrderVO.class);
    }

    @Override
    public AccountPaymentVO paymentDetail(String paymentId) {
        PaymentDetailRequest request = new PaymentDetailRequest();
        request.setPaymentId(paymentId);
        PaymentDTO resultDTO = walletApiService.largePaymentQuery(request);

        long expiryCountdown = 0;
        if (StringUtils.isNotBlank(resultDTO.getExpireTime())) {
            expiryCountdown = Math.max(0, Duration.between(LocalDateTime.now(), LocalDateTime.parse(resultDTO.getExpireTime(), formatter)).getSeconds());
        }
        AccountPaymentVO result = BeanUtil.toBean(resultDTO, AccountPaymentVO.class);
        result.setExpiryCountdown(expiryCountdown);
        return result;
    }

    @Override
    public WithDrawerDTO withDrawer(WalletWithDrawerRequest request) {
        String storeId = getStoreId(request);
        String reqNo = UUIDUtils.get32UUID();
        WithDrawerRequest withDrawerRequest = new WithDrawerRequest(storeId, request.getPayPwd(), reqNo, request.getAmount().toString(), "提现", request.getWalletType());
        WithDrawerDTO withdraw = walletApiService.withdraw(withDrawerRequest);
        if ("2".equals(withdraw.getTradeStatus())) {
            throw new ServiceException(ErrorCodeEnum.WALLET_WITH_DRAWER_FAIL);
        }
        WalletPaymentOrderDO orderDO = WalletPaymentOrderDO.builder()
                .storeId(storeId)
                .paymentId(reqNo)
                .type(1)
                .amount(request.getAmount())
                .orderStatus(1)
                .build();
        walletPaymentOrderDAO.insertSelective(orderDO);
        return withdraw;
    }

    @Override
    public PageInfo<AccountPageVO>  getAllAccountList(CoolAccountBatchQueryRequest request) {
        AccountBatchQueryRequest accountBatchQueryRequest = request.convertToAccountBatchQueryRequest();
        AccountPageDTO accountList = walletApiService.getAccountList(accountBatchQueryRequest);
        List<AccountPageVO> list = BeanUtil.toList(accountList.getPageData(), AccountPageVO.class, CopyOptions.create().setFieldMapping(Collections.singletonMap("outStoreId", "storeId")));
        PageInfo<AccountPageVO> page = toPageInfo(list, AccountPageVO.class, accountList.getPage());
        List<String> storeIds = CollStreamUtil.toList(page.getList(), AccountPageVO::getStoreId);
        Map<String, String> storeNameMap = getStoreNameMap(storeIds);
        page.getList().forEach(v -> v.setStoreName(storeNameMap.get(v.getStoreId())));
        return page;
    }

    private Map<String, String> getStoreNameMap(List<String> storeIds) {
        Map<String, String> storeNameMap = new HashMap<>();
        List<StoreDO> stores = storeDao.getEffectiveStoreByStoreIds(storeIds);
        Map<String, String> storeMap = CollStreamUtil.toMap(stores, StoreDO::getStoreId, StoreDO::getStoreName);
        storeNameMap.putAll(storeMap);
        List<ShopInfoDO> shops = shopInfoDAO.getShopInfoByStoreIds(storeIds);
        Map<String, String> shopMap = CollStreamUtil.toMap(shops, ShopInfoDO::getStoreId, ShopInfoDO::getShopName);
        storeNameMap.putAll(shopMap);
        return storeNameMap;
    }

    @Override
    public PageInfo<TradeRecordDTO> getTradeRecordList(CoolTradeRecodePageRequest request,Boolean orgFlag) {
        TradeRecodePageRequest tradeRecodePageRequest = request.convertToTradeRecodePageRequest();
        if (orgFlag){
            tradeRecodePageRequest.setOrgId(orgId);
        }
        TradeRecordListDTO tradeRecordListDTO = walletApiService.getTradeRecordList(tradeRecodePageRequest);
        return toPageInfo(tradeRecordListDTO.getPageData(), TradeRecordDTO.class, tradeRecordListDTO.getPage());
    }

    @Override
    public PageInfo<TradeRecordDTO> getRechargeTradeRecordList(CoolTradeRecodeRequest request) {
        //充值的FeeItemId 是 400
        if (request.getFeeItemId()==null){
            request.setFeeItemId(400);
        }
        List<AccountInfoDTO> accountInfoList = walletApiService.getAccountInfo(new OutStoreIdRequest(request.getStoreId()));
        if (CollectionUtils.isEmpty(accountInfoList)){
            throw new ServiceException(ErrorCodeEnum.NOT_EXIST_WANG_SHANG_ACCOUNT);
        }
        AccountInfoDTO accountInfoDTO = accountInfoList.get(0);
        TradeRecodePageRequest tradeRecodePageRequest = request.convertToTradeRecodePageRequest();
        tradeRecodePageRequest.setAccountNo(accountInfoDTO.getAccountNo());
//        String a = "{\"page\":{\"currentPage\":1,\"pageSize\":10,\"total\":37,\"count\":4,\"first\":true,\"last\":false},\"pageData\":[{\"reqNo\":\"422712987693189\",\"tradeId\":422712987734149,\"outTradeNo\":\"202604030907217199\",\"feeItemId\":209,\"feeItemName\":\"提现\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000219703200034\",\"inAccountNo\":\"6214836146244633\",\"inAccountName\":\"苏竹红\",\"outAccountName\":\"望江县苏荷服装店(个体工商户)\",\"withdrawalBankCardNo\":\"6214836146244633\",\"withdrawalBankCardName\":\"苏竹红\",\"amount\":\"0.01\",\"tradeStatus\":1,\"tradeType\":2,\"remark\":\"提现\",\"errMsg\":\"\",\"createTime\":\"2026-04-09 11:03:33 +0800 CST\",\"outThirdStoreId\":\"0b382f3b789d4a82919d863626eb46a0\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"20260406102649175873\",\"tradeId\":421642280509638,\"outTradeNo\":\"202604590659624412\",\"feeItemId\":315,\"feeItemName\":\"加盟保证金\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000230437105734\",\"inAccountNo\":\"226801000229636396595\",\"inAccountName\":\"海南正新多品牌管理有限公司\",\"outAccountName\":\"王彦召\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"13000.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-06 10:26:49 +0800 CST\",\"outThirdStoreId\":\"6fa404c6888f44389882d5b106a0126f\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"20260406102649175192\",\"tradeId\":421642279608518,\"outTradeNo\":\"202604590659247677\",\"feeItemId\":311,\"feeItemName\":\"管理费(年)\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000230437105734\",\"inAccountNo\":\"226801000229636396595\",\"inAccountName\":\"海南正新多品牌管理有限公司\",\"outAccountName\":\"王彦召\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"7200.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-06 10:26:49 +0800 CST\",\"outThirdStoreId\":\"6fa404c6888f44389882d5b106a0126f\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"20260406102649174677\",\"tradeId\":421642279346374,\"outTradeNo\":\"202604590659649754\",\"feeItemId\":310,\"feeItemName\":\"加盟费\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000230437105734\",\"inAccountNo\":\"226801000229636396595\",\"inAccountName\":\"海南正新多品牌管理有限公司\",\"outAccountName\":\"王彦召\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"23000.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-06 10:26:49 +0800 CST\",\"outThirdStoreId\":\"6fa404c6888f44389882d5b106a0126f\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"20260406102649175449\",\"tradeId\":421642279850182,\"outTradeNo\":\"202604590659269101\",\"feeItemId\":312,\"feeItemName\":\"品牌使用费(年)\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000230437105734\",\"inAccountNo\":\"226801000229636396595\",\"inAccountName\":\"海南正新多品牌管理有限公司\",\"outAccountName\":\"王彦召\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"6000.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-06 10:26:49 +0800 CST\",\"outThirdStoreId\":\"6fa404c6888f44389882d5b106a0126f\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"2026040410152060066006730073317634\",\"tradeId\":421001139474629,\"outTradeNo\":\"202604730466944804\",\"feeItemId\":400,\"feeItemName\":\"账户充值\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"6222620170012855081\",\"inAccountNo\":\"226801000230437105734\",\"inAccountName\":\"王彦召\",\"outAccountName\":\"王彦召\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"167000.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-04 14:58:01 +0800 CST\",\"outThirdStoreId\":\"\",\"inThirdStoreId\":\"6fa404c6888f44389882d5b106a0126f\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"2026040410152060066006730073306436\",\"tradeId\":420940632989893,\"outTradeNo\":\"202604730466816938\",\"feeItemId\":400,\"feeItemName\":\"账户充值\",\"outStoreCode\":\"\",\"inStoreCode\":\"\",\"outStoreName\":\"\",\"inStoreName\":\"\",\"outAccountNo\":\"6222620170012855081\",\"inAccountNo\":\"226801000230437105734\",\"inAccountName\":\"王彦召\",\"outAccountName\":\"王彦召\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"10.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-04 10:51:49 +0800 CST\",\"outThirdStoreId\":\"\",\"inThirdStoreId\":\"6fa404c6888f44389882d5b106a0126f\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"2026040310152060066006860064494468\",\"tradeId\":420447948849349,\"outTradeNo\":\"202604860357164314\",\"feeItemId\":400,\"feeItemName\":\"账户充值\",\"outStoreCode\":\"\",\"inStoreCode\":\"M24933\",\"outStoreName\":\"\",\"inStoreName\":\"正新鸡排五马街蝉街店\",\"outAccountNo\":\"6222801422141101593\",\"inAccountNo\":\"226801000230176116869\",\"inAccountName\":\"池晓静\",\"outAccountName\":\"池晓静\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"22538.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-03 01:27:05 +0800 CST\",\"outThirdStoreId\":\"\",\"inThirdStoreId\":\"125f9cb54d254ef19b2ba7f6919c7aab\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"20260402143630390598\",\"tradeId\":420288065171654,\"outTradeNo\":\"202604590257151330\",\"feeItemId\":315,\"feeItemName\":\"加盟保证金\",\"outStoreCode\":\"M24933\",\"inStoreCode\":\"\",\"outStoreName\":\"正新鸡排五马街蝉街店\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000230176116869\",\"inAccountNo\":\"226801000229636396595\",\"inAccountName\":\"海南正新多品牌管理有限公司\",\"outAccountName\":\"池晓静\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"13000.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-02 14:36:30 +0800 CST\",\"outThirdStoreId\":\"125f9cb54d254ef19b2ba7f6919c7aab\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"},{\"reqNo\":\"20260402143630390720\",\"tradeId\":420288064905414,\"outTradeNo\":\"202604590256834068\",\"feeItemId\":312,\"feeItemName\":\"品牌使用费(年)\",\"outStoreCode\":\"M24933\",\"inStoreCode\":\"\",\"outStoreName\":\"正新鸡排五马街蝉街店\",\"inStoreName\":\"\",\"outAccountNo\":\"226801000230176116869\",\"inAccountNo\":\"226801000229636396595\",\"inAccountName\":\"海南正新多品牌管理有限公司\",\"outAccountName\":\"池晓静\",\"withdrawalBankCardNo\":\"\",\"withdrawalBankCardName\":\"\",\"amount\":\"6000.00\",\"tradeStatus\":1,\"tradeType\":1,\"remark\":\"\",\"errMsg\":\"\",\"createTime\":\"2026-04-02 14:36:30 +0800 CST\",\"outThirdStoreId\":\"125f9cb54d254ef19b2ba7f6919c7aab\",\"inThirdStoreId\":\"\",\"outAccountBankName\":\"\",\"outAccountBankCardNo\":\"\",\"outCompanyCode\":\"\",\"outCompanyName\":\"\",\"inAccountBankName\":\"\",\"inAccountBankCardNo\":\"\",\"inCompanyCode\":\"\",\"inCompanyName\":\"\",\"transType\":\"\"}]}\n";
//        if (StringUtils.isNotEmpty(a)){
//            TradeRecordListDTO tradeRecordListDTO = JSONObject.parseObject(a, TradeRecordListDTO.class);
//            return toPageInfo(tradeRecordListDTO.getPageData(), TradeRecordDTO.class, tradeRecordListDTO.getPage());
//        }
        TradeRecordListDTO tradeRecordListDTO = walletApiService.getTradeRecordList(tradeRecodePageRequest);
        return toPageInfo(tradeRecordListDTO.getPageData(), TradeRecordDTO.class, tradeRecordListDTO.getPage());
    }

    @Override
    public OpenBasicInfoDTO getOpenBasicInfo(String storeId, String storeCode) {
        OpenBasicInfoDTO openBasicInfoDTO = new OpenBasicInfoDTO();
        //非首次提交 获取上次提交的信息 其他情况走主数据与营账通开通数据
        OpenBankInfoDO openBankInfo;
        if (StringUtils.isNotBlank(storeId)) {
            openBankInfo = openBankInfoDAO.getOpenBankInfoByStoreId(storeId);
        } else {
            openBankInfo = openBankInfoDAO.getOpenBankInfo(storeCode);
        }
        if (Objects.nonNull(openBankInfo)){
            openBasicInfoDTO.setSignerName(openBankInfo.getSignerName());
            openBasicInfoDTO.setSignerIdCard(openBankInfo.getSignerIdCard());
            openBasicInfoDTO.setSignerPhone(openBankInfo.getSignerPhone());
            openBasicInfoDTO.setSignerIdCardFront(openBankInfo.getSignerIdCardFront());
            openBasicInfoDTO.setSignerIdCardBack(openBankInfo.getSignerIdCardBack());
            openBasicInfoDTO.setBusinessLicenseName(openBankInfo.getBusinessLicenseName());
            openBasicInfoDTO.setBusinessLicensePhoto(openBankInfo.getBusinessLicensePhoto());
            openBasicInfoDTO.setBusinessLicenseCode(openBankInfo.getBusinessLicenseCode());
            openBasicInfoDTO.setSettlementCard(openBankInfo.getSettlementCard());
            openBasicInfoDTO.setBankBranchName(openBankInfo.getBankBranchName());
            openBasicInfoDTO.setBankBranchCode(openBankInfo.getBankBranchCode());
            openBasicInfoDTO.setBankReservedPhone(openBankInfo.getBankReservedPhone());
            BeanUtil.copyProperties(openBankInfo, openBasicInfoDTO);
            dictService.fillDictField(openBasicInfoDTO);
            return openBasicInfoDTO;
        }
        //先查询当前门店
        StoreDO store = storeDao.getByStoreNum(storeCode);
        if (Objects.isNull( store)){
            return null;
        }
        Map<String, StoreMasterSignerInfoDO> signerMapByStoreIds = storeMasterSignerInfoDAO.getSignerMapByStoreIds(Collections.singletonList(store.getStoreId()));
        StoreMasterSignerInfoDO signerInfoDO = signerMapByStoreIds.get(store.getStoreId());

        if (Objects.nonNull(signerInfoDO)){
            openBasicInfoDTO.setSignerName(signerInfoDO.getSigner1Name());
            openBasicInfoDTO.setSignerIdCard(signerInfoDO.getSigner1IdCardNo());
            openBasicInfoDTO.setSignerPhone(signerInfoDO.getSigner1Mobile());
            openBasicInfoDTO.setSignerIdCardFront(signerInfoDO.getSigner1IdCardFront());
            openBasicInfoDTO.setSignerIdCardBack(signerInfoDO.getSigner1IdCardBack());
        }
        TempOpenWalletInfoDO tempOpenWalletInfoByStoreCode = tempOpenWalletInfoDAO.getTempOpenWalletInfoByStoreCode(storeCode);
        if (Objects.nonNull(tempOpenWalletInfoByStoreCode)){
            openBasicInfoDTO.setBusinessLicenseName(tempOpenWalletInfoByStoreCode.getBusinessRegName());
            openBasicInfoDTO.setBusinessLicenseCode(tempOpenWalletInfoByStoreCode.getBusinessLicenseNo());
            openBasicInfoDTO.setSettlementCard(tempOpenWalletInfoByStoreCode.getSettlementCardNo());
            openBasicInfoDTO.setBankBranchName(tempOpenWalletInfoByStoreCode.getBankBranchName());
            openBasicInfoDTO.setBankBranchCode(tempOpenWalletInfoByStoreCode.getBankBranchNo());
            openBasicInfoDTO.setBankReservedPhone(tempOpenWalletInfoByStoreCode.getBankReservedPhone());
        }
        return openBasicInfoDTO;
    }


    @Override
    public Boolean openOnlineBankAccount(CoolOpenBasicInfoRequest request) {
        if (StringUtils.isBlank(request.getLegalSignerRelation())) {
            throw new ServiceException(ErrorCodeEnum.MINI_PROGRAM_VERSION_TOO_LOW);
        }
        //如果法人是签约人 覆盖法人的信息 取签约人的信息
        if (request.getLegalIsSigner()==1){
            request.setLegalName(request.getSignerName());
            request.setLegalIdCard(request.getSignerIdCard());
            request.setLegalPhone(request.getSignerPhone());
            request.setLegalIdCardFront(request.getSignerIdCardFront());
            request.setLegalBankCard(request.getSettlementCard());
            request.setLegalBankBranchName(request.getBankBranchName());
            request.setLegalBankBranchCode(request.getBankBranchCode());
            request.setLegalBankReservedPhone(request.getBankReservedPhone());
        }
        //首先存储提交的信息
        OpenBankInfoDO openBankInfoDO = new OpenBankInfoDO();
        BeanUtil.copyProperties(request, openBankInfoDO);
        //查询是否有提交过
        OpenBankInfoDO openBankInfo = openBankInfoDAO.getOpenBankInfo(request.getStoreCode());
        if (Objects.isNull(openBankInfo)){
            openBankInfoDAO.insertSelective(openBankInfoDO);
        }else {
            openBankInfoDAO.updateByStoreCode(openBankInfoDO);
        }
        // 如果是开店流程中网商开通失败，则重新调用打标接口
        if (getOnlineBankFailTag(request.getStoreId())) {
            onlineBankFailReOpen(request);
            return true;
        }
        OldStoreAccountCreateV2Request oldStoreAccountCreateRequest = new OldStoreAccountCreateV2Request();
        StoreDO store = storeDao.getByStoreNum(request.getStoreCode());
        oldStoreAccountCreateRequest.setOutStoreId(store.getStoreId());
        oldStoreAccountCreateRequest.setPhoneNumber(request.getSignerPhone());
        oldStoreAccountCreateRequest.setLegalAccountType(2);
        oldStoreAccountCreateRequest.setLegalAccountCardNo(request.getLegalBankCard());
        oldStoreAccountCreateRequest.setLegalAccountPhone(request.getLegalPhone());
        oldStoreAccountCreateRequest.setLegalBankNo(request.getLegalBankBranchCode());
        oldStoreAccountCreateRequest.setLegalBankName(request.getLegalBankBranchName());
        oldStoreAccountCreateRequest.setSignatoryAccountType(2);
        oldStoreAccountCreateRequest.setSignatoryAccountCardNo(request.getSettlementCard());
        oldStoreAccountCreateRequest.setSignatoryAccountPhone(request.getBankReservedPhone());
        oldStoreAccountCreateRequest.setSignatoryBankNo(request.getBankBranchCode());
        oldStoreAccountCreateRequest.setSignatoryBankName(request.getBankBranchName());
        oldStoreAccountCreateRequest.setRelation(request.getLegalSignerRelation());
        oldStoreAccountCreateRequest.setLicenseNo(request.getBusinessLicenseCode());
        oldStoreAccountCreateRequest.setLicenseName(request.getBusinessLicenseName());
        oldStoreAccountCreateRequest.setLegalName(request.getLegalName());
        oldStoreAccountCreateRequest.setLegalNo(request.getLegalIdCard());
        oldStoreAccountCreateRequest.setLegalPhone(request.getLegalPhone());
        oldStoreAccountCreateRequest.setLegalIdcardExpireTime(request.getLegalIdCardExpireTime());
        //账户简称使用编码+名称
        String code = StringUtils.isNotBlank(store.getStoreNum())?store.getStoreNum():"";
        String name = StringUtils.isNotBlank(store.getMiniProgramOrderStoreName())?store.getMiniProgramOrderStoreName():store.getStoreName();
        oldStoreAccountCreateRequest.setAccountAliasName(code+name);
        oldStoreAccountCreateRequest.setCertPhotoA(request.getLegalIdCardFront());
        oldStoreAccountCreateRequest.setCertPhotoB(request.getLegalIdCardBack());
        oldStoreAccountCreateRequest.setLicensePhoto(request.getBusinessLicensePhoto());
        oldStoreAccountCreateRequest.setSignatoryName(request.getSignerName());
        oldStoreAccountCreateRequest.setSignatoryPhone(request.getSignerPhone());
        oldStoreAccountCreateRequest.setSignatoryNo(request.getSignerIdCard());
        oldStoreAccountCreateRequest.setSignatoryPhotoA(request.getSignerIdCardFront());
        oldStoreAccountCreateRequest.setSignatoryPhotoB(request.getSignerIdCardBack());
        walletApiService.oldStoreOpenAccountV2(oldStoreAccountCreateRequest);
        // 网商创建成功，记录已激活状态
        redisUtilPool.setString(MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_ACTIVATED, store.getStoreId()), "1");
        return Boolean.TRUE;
    }

    @Override
    public Boolean newStoreOpenOnlineBankAccount(NewWsCreateAccountRequest request) {
        ShopInfoDO store = shopInfoDAO.getShopInfo(request.getShopId());
        if (Objects.isNull(store)) {
            throw new ServiceException(ErrorCodeEnum.STORE_NOT_EXIST);
        }
        NewStoreAccountCreateRequest walletRequest = new NewStoreAccountCreateRequest();
        walletRequest.setOutStoreId(store.getStoreId());
        walletRequest.setPhoneNumber(request.getSignerPhone());
        walletRequest.setAccountAliasName(request.getSignerName() + UUIDUtils.get8UUID());
        walletRequest.setLegalName(request.getSignerName());
        walletRequest.setLegalNo(request.getSignerIdCard());
        walletRequest.setLegalPhone(request.getSignerPhone());
        walletRequest.setLegalAccountCardNo(request.getSettlementCard());
        walletRequest.setLegalAccountPhone(request.getBankReservedPhone());
        walletRequest.setLegalBankNo(request.getBankBranchCode());
        walletRequest.setLegalBankName(request.getBankBranchName());
        walletRequest.setCertPhotoA(request.getSignerIdCardFront());
        walletRequest.setCertPhotoB(request.getSignerIdCardBack());
        walletApiService.newStoreOpenAccount(walletRequest);
        return true;
    }

    /**
     * 获取开店流程网商银行开通失败标记
     */
    private boolean getOnlineBankFailTag(String storeId) {
        String key = MessageFormat.format(RedisConstant.WALLET_ONLINE_BANK_TAG_FAIL, storeId);
        String flag = redisUtilPool.getString(key);
        return StringUtils.isNotBlank(flag);
    }
    
    /**
     * 开通流程创建网商银行账户失败的情况下，重新开通
     */
    private void onlineBankFailReOpen(CoolOpenBasicInfoRequest request) {
        log.info("网商钱包开通失败后重新提交打标接口");
        AccountAddTagRequest tagRequest = AccountAddTagRequest.builder()
                .outStoreId(request.getStoreId())
                .licenseNo(request.getBusinessLicenseCode())
                .licenseName(request.getBusinessLicenseName())
                .legalName(request.getLegalName())
                .legalNo(request.getLegalIdCard())
                .legalPhone(request.getLegalPhone())
                .certPhotoA(request.getLegalIdCardFront())
                .certPhotoB(request.getLegalIdCardBack())
                .licensePhoto(request.getBusinessLicensePhoto())
                .signatoryPhotoA(request.getSignerIdCardFront())
                .signatoryPhotoB(request.getSignerIdCardBack())
                .build();
        executeAddTag(tagRequest);
    }

    @Override
    public Boolean onlineBankActive(StoreShopRequest request) {
        String storeId = getStoreId(request);
        walletApiService.textMsgSend(new TextMsgSendRequest(storeId));
        return true;
    }

    @Override
    public List<BankInfoDTO> findBankHeadName() {
        return walletApiService.findBankHeadName();
    }

    @Override
    public WsPayAccountDTO wsPayAccountQuery(StoreShopRequest request) {
        String storeId = getStoreId(request);
        return walletApiService.wsPayAccountQuery(new OutStoreIdRequest(storeId));
    }

    @Override
    public PageInfo<AccountInfoDTO> getOrgAccountInfoList(CoolAccountPageRequest request) {
        AccountPageRequest accountPageRequest = new AccountPageRequest();
        accountPageRequest.setOrgId(orgId);
        accountPageRequest.setWalletType(request.getWalletType());
        accountPageRequest.setAccNo(request.getAccNo());
        accountPageRequest.setAccName(request.getAccName());
        WalletBasicPageInfo walletBasicPageInfo = new WalletBasicPageInfo();
        walletBasicPageInfo.setCurrentPage(request.getPageNum());
        walletBasicPageInfo.setPageSize(request.getPageSize());
        accountPageRequest.setPage(walletBasicPageInfo);
        OrgAccountDTO orgAccount = walletApiService.findOrgAccount(accountPageRequest);
        return toPageInfo(orgAccount.getPageData(),AccountInfoDTO.class,orgAccount.getPage());
    }

    public String getStoreId(StoreShopRequest request) {
        String storeId = request.getStoreId();
        if (StringUtils.isBlank(storeId) && Objects.nonNull(request.getShopId())) {
            ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
            storeId = Objects.nonNull(shopInfo) ? shopInfo.getStoreId() : null;
        }
        if (StringUtils.isBlank(storeId)) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        return storeId;
    }

    /**
     * 查询并校验门店是否存在以及阶段是否处于平安钱包未开通状态
     */
    private ShopInfoDO getAndVerifyShopAndStage(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        ShopStageInfoDO stageInfo = shopStageInfoDAO.getShopSubStageInfo(shopId, ShopSubStageEnum.SHOP_STAGE_6);
        if (!ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_60.getShopSubStageStatus().equals(stageInfo.getShopSubStageStatus())) {
            throw new ServiceException(ErrorCodeEnum.SHOP_STAGE_NOT_OPERATE);
        }
        return shopInfo;
    }
}
