package com.yn.bftl.thirdparty.modules.chinaums.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.yn.bftl.common.common.exception.YnceError;
import com.yn.bftl.common.common.util.ByxRouteUtil;
import com.yn.bftl.common.common.util.RSAEncryptorUtil;
import com.yn.bftl.common.common.util.RouteUtil;
import com.yn.bftl.common.modules.auth.vo.ChinaumsAuthInfoVO;
import com.yn.bftl.common.modules.base.entity.BaseElecBank;
import com.yn.bftl.common.modules.company.entity.ChinaumsAuthInfo;
import com.yn.bftl.common.modules.company.entity.ChinaumsBankCard;
import com.yn.bftl.common.modules.company.entity.Company;
import com.yn.bftl.common.modules.company.enums.ApplicationStatus;
import com.yn.bftl.common.modules.company.enums.ChinaumsBankCardStatus;
import com.yn.bftl.common.modules.configuration.entity.ThirdPartyPaySet;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.common.repository.CompanyRepository;
import com.yn.bftl.thirdparty.common.service.BaseMemberService;
import com.yn.bftl.thirdparty.common.service.ByxTradeWayService;
import com.yn.bftl.thirdparty.common.transfer.ByxApplicationStatusTransfer;
import com.yn.bftl.thirdparty.common.util.SequenceUtil;
import com.yn.bftl.thirdparty.modules.business.repository.MetaFileRepository;
import com.yn.bftl.thirdparty.modules.business.service.MetaFileService;
import com.yn.bftl.thirdparty.modules.business.util.ThirdPartyConfigUtil;
import com.yn.bftl.thirdparty.modules.chinaums.dto.*;
import com.yn.bftl.thirdparty.modules.chinaums.dto.byx.ByxChinaumsCreateCusDTO;
import com.yn.bftl.thirdparty.modules.chinaums.dto.byx.ByxChinaumsPasswordUpdateDTO;
import com.yn.bftl.thirdparty.modules.chinaums.dto.byx.ByxPasswordResetDTO;
import com.yn.bftl.thirdparty.modules.chinaums.dto.chinaums.ChinaumsStatusDTO;
import com.yn.bftl.thirdparty.modules.chinaums.dto.chinaums.ChinaumsUpdateCusDTO;
import com.yn.bftl.thirdparty.modules.chinaums.dto.chinaums.ChinaumsUpdateMchDTO;
import com.yn.bftl.thirdparty.modules.chinaums.repository.ChinaumsAuthInfoRepository;
import com.yn.bftl.thirdparty.modules.chinaums.repository.ChinaumsBankCardRepository;
import com.yn.bftl.thirdparty.modules.chinaums.service.AuthService;
import com.yn.bftl.thirdparty.modules.chinaums.service.BaseElecBankService;
import com.yn.bftl.thirdparty.modules.chinaums.util.ByxChinaumsUtil;
import com.yn.bftl.thirdparty.modules.chinaums.vo.ChinaumsApplicationStatusVO;
import com.yn.bftl.thirdparty.modules.chinaums.vo.byx.ByxChinaumsMchRegInfoDetailVO;
import com.yn.bftl.thirdparty.modules.chinaums.vo.byx.ByxChinaumsMchRegInfoVO;
import com.yn.bftl.thirdparty.modules.chinaums.vo.byx.ByxMchCreateVO;
import com.yn.bftl.thirdparty.modules.chinaums.vo.chinaums.ChinaumsMchStatus;
import com.yn.bftl.thirdparty.modules.secret.service.RandomKeyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 商户服务实现类
 *
 * @author huabiao
 * @create 2022/12/6  15:27
 **/
@Slf4j
@Service
public class AuthServiceImpl extends BaseMemberService implements AuthService {

    @Resource
    private ByxChinaumsUtil byxChinaumsUtil;
    @Resource
    private ChinaumsAuthInfoRepository chinaumsAuthInfoRepository;
    @Resource
    private SequenceUtil sequenceUtil;
    @Resource
    private MetaFileRepository metaFileRepository;
    @Resource
    private MetaFileService metaFileService;
    @Resource
    private CompanyRepository companyRepository;
    @Resource
    private ChinaumsBankCardRepository chinaumsBankCardRepository;

    @Resource
    private RandomKeyService randomKeyService;

    @Resource
    private ByxTradeWayService byxTradeWayService;

    @Resource
    private ThirdPartyConfigUtil thirdPartyConfigUtil;

    @Resource
    private BaseElecBankService baseElecBankService;

    @Transactional
    @Override
    public ByxMchCreateVO getMchCreateUrl() {
        Company company = getUser().getCompany();
        String registerNo = company.getRegisterNo();
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo != null && ApplicationStatus.REGISTER_SUCCESS.equals(chinaumsAuthInfo.getApplicationStatus())) {
            throw new YnceErrorException(YnceError.YNCE_218002);
        }
        if (chinaumsAuthInfo != null && chinaumsAuthInfo.getMchId() != null && !chinaumsAuthInfo.getMchId().equals(registerNo)) {
            registerNo = chinaumsAuthInfo.getMchId();
        }
        ThirdPartyPaySet thirdPartyPaySet = thirdPartyConfigUtil.getPlatform();
        JSONObject params = new JSONObject();
        if (StringUtils.isNotEmpty(registerNo)) {
            params.put("registerNo", registerNo);
        }
        params.put("jumpType", "11");
        params.put("callbackUrl", thirdPartyPaySet.getThirdPartyUrl() + "/templates/goback.html");
        params.put("notifyUrl", thirdPartyPaySet.getThirdPartyUrl() + "/chinaums/call_back/byx/result");
        ByxMchCreateVO byxMchCreateVO = byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_GET_MERCHANT_OPEN_URL, params, ByxMchCreateVO.class, true);
        company.setRegisterNo(byxMchCreateVO.getRegisterNo());
        companyRepository.saveAndFlush(company);

        synchronized (this) {
            if (chinaumsAuthInfo == null) {
                chinaumsAuthInfo = new ChinaumsAuthInfo();
                String outRequestNo = sequenceUtil.getNextSequenceNumber("YLRZ");
                chinaumsAuthInfo.setCompany(company);
                chinaumsAuthInfo.setOutRequestNo(outRequestNo);
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_UNCOMMIT);
                chinaumsAuthInfo.setMchId(byxMchCreateVO.getRegisterNo());
                chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
            }
        }
        return byxMchCreateVO;
    }

    public ByxMchCreateVO getFileUrl() {
//        Company company = getUser().getCompany();
//
//        ThirdPartyPaySet thirdPartyPaySet = thirdPartyConfigUtil.getPlatform();
        JSONObject params = new JSONObject();
        params.put("jumpType", "12");
//        params.put("callbackUrl", "http://www.baidu.com");
//        params.put("notifyUrl", thirdPartyPaySet.getThirdPartyUrl() + "/byx/chinaums/call_back/result");
        return byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_GET_MERCHANT_OPEN_URL, params, ByxMchCreateVO.class);
    }

    @Override
    public void mchCreate(MchCreateDTO mchCreateDTO) {
//        Company company = getUser().getCompany();
//        // 平台订单号
//        String outRequestNo;
//        // 判断该企业是否已认证
//        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
//        if (chinaumsAuthInfo != null) {
//            // 判断状态，若为失败可重新发起
//            if (!chinaumsAuthInfo.getApplicationStatus().equals(ApplicationStatus.FAILED)) {
//                throw new YnceErrorException(YnceError.YNCE_218010);
//            }
//        } else {
//            // 保存认证信息
//            chinaumsAuthInfo = new ChinaumsAuthInfo();
//            outRequestNo = sequenceUtil.getNextSequenceNumber("YLRZ");
//            chinaumsAuthInfo.setCompany(company);
//            chinaumsAuthInfo.setOutRequestNo(outRequestNo);
//        }
//        // 处理图片
//        chinaumsAuthInfo.setBusinessLicenseCopyFile(metaFileRepository.findById(mchCreateDTO.getBusinessLicenseCopyId()).orElse(null));
//        chinaumsAuthInfo.setLegalPersonIdCardCopyFile(metaFileRepository.findById(mchCreateDTO.getLegalPersonIdCardCopyId()).orElse(null));
//        chinaumsAuthInfo.setLegalPersonIdCardNationalFile(metaFileRepository.findById(mchCreateDTO.getLegalPersonIdCardNationalId()).orElse(null));
//        if (mchCreateDTO.getOrganizationCertCopyId() != null) {
//            chinaumsAuthInfo.setOrganizationCertCopyFile(metaFileRepository.findById(mchCreateDTO.getOrganizationCertCopyId()).orElse(null));
//        }
//        if (mchCreateDTO.getTaxRegistrationCertCopyId() != null) {
//            chinaumsAuthInfo.setTaxRegistrationCertCopyFile(metaFileRepository.findById(mchCreateDTO.getTaxRegistrationCertCopyId()).orElse(null));
//        }
//        if (mchCreateDTO.getContactIdCardCopyId() != null) {
//            chinaumsAuthInfo.setContactIdCardCopyFile(metaFileRepository.findById(mchCreateDTO.getContactIdCardCopyId()).orElse(null));
//        }
//        if (mchCreateDTO.getContactIdCardNationalId() != null) {
//            chinaumsAuthInfo.setContactIdCardNationalFile(metaFileRepository.findById(mchCreateDTO.getContactIdCardNationalId()).orElse(null));
//        }
//        BeanUtils.copyProperties(mchCreateDTO, chinaumsAuthInfo, "outRequestNo", "company");
//        chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CHECKING);
//        // 拼接银联请求DTO
//        ChinaumsCreateMchDTO chinaumsCreateMchDTO = new ChinaumsCreateMchDTO();
//        BeanUtils.copyProperties(mchCreateDTO, chinaumsCreateMchDTO);
//        chinaumsCreateMchDTO.setOutRequestNo(chinaumsAuthInfo.getOutRequestNo());
//        // 根据营业执照开始结束时间处理
//        String businessLicenseValidTime = mchCreateDTO.getBusinessLicenseStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        if (mchCreateDTO.getBusinessLicenseEndTime() == null) {
//            businessLicenseValidTime += ",长期";
//        } else {
//            businessLicenseValidTime = businessLicenseValidTime + "," + mchCreateDTO.getBusinessLicenseEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        }
//        chinaumsCreateMchDTO.setBusinessLicenseValidTime(businessLicenseValidTime);
//        // 根据组织机构开始结束时间处理
//        if (mchCreateDTO.getOrganizationCertStartTime() != null) {
//            String organizationCertValidTime = mchCreateDTO.getOrganizationCertStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            if (mchCreateDTO.getOrganizationCertEndTime() == null) {
//                organizationCertValidTime += ",长期";
//            } else {
//                organizationCertValidTime = businessLicenseValidTime + "," + mchCreateDTO.getOrganizationCertEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            }
//            chinaumsCreateMchDTO.setOrganizationCertValidTime(organizationCertValidTime);
//        }
//        // 根据法人证件开始结束时间处理
//        String legalPersonIdCardValidTime = mchCreateDTO.getLegalPersonIdCardStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        if (mchCreateDTO.getLegalPersonIdCardEndTime() == null) {
//            legalPersonIdCardValidTime += ",长期";
//        } else {
//            legalPersonIdCardValidTime = legalPersonIdCardValidTime + "," + mchCreateDTO.getLegalPersonIdCardEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        }
//        chinaumsCreateMchDTO.setLegalPersonIdCardValidTime(legalPersonIdCardValidTime);
//        // 对敏感信息加密处理
//        String publicKey = chinaumsUtil.getPublicKey();
//        try {
//            // 开户名称
//            chinaumsCreateMchDTO.setSettleAcctName(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getSettleAcctName(), publicKey));
//            // 银行账号
//            chinaumsCreateMchDTO.setSettleAcctBankAcctNo(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getSettleAcctBankAcctNo(), publicKey));
//            // 法人姓名
//            chinaumsCreateMchDTO.setLegalPersonIdCardName(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getLegalPersonIdCardName(), publicKey));
//            // 法人证件号码
//            chinaumsCreateMchDTO.setLegalPersonIdCardNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getLegalPersonIdCardNumber(), publicKey));
//            // 联系人姓名
//            chinaumsCreateMchDTO.setContactIdCardName(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactIdCardName(), publicKey));
//            // 联系人身份证件号码
//            chinaumsCreateMchDTO.setContactIdCardNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactIdCardNumber(), publicKey));
//            // 法人手机号
//            chinaumsCreateMchDTO.setLegalPersonMobileNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getLegalPersonMobileNumber(), publicKey));
//            // 联系人手机号
//            chinaumsCreateMchDTO.setContactMobileNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactMobileNumber(), publicKey));
//            // 联系人邮箱
//            chinaumsCreateMchDTO.setContactEmail(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactEmail(), publicKey));
//            // 交易密码
//            chinaumsCreateMchDTO.setPassword(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getPassword(), publicKey));
//        } catch (Exception exception) {
//            throw new YnceErrorException(YnceError.YNCE_218014);
//        }
//        // 当不填写联系人时，将法人信息保存进去
//        if (!mchCreateDTO.getIsFillContact()) {
//            chinaumsCreateMchDTO.setContactIdCardName(chinaumsCreateMchDTO.getLegalPersonIdCardName());
//            chinaumsCreateMchDTO.setContactIdCardType(chinaumsCreateMchDTO.getLegalPersonIdCardType());
//            chinaumsCreateMchDTO.setContactIdCardCopy(chinaumsCreateMchDTO.getLegalPersonIdCardCopy());
//            chinaumsCreateMchDTO.setContactIdCardNational(chinaumsCreateMchDTO.getLegalPersonIdCardNational());
//            chinaumsCreateMchDTO.setContactIdCardNumber(chinaumsCreateMchDTO.getLegalPersonIdCardNumber());
//            chinaumsCreateMchDTO.setContactIdCardValidTime(chinaumsCreateMchDTO.getLegalPersonIdCardValidTime());
//            chinaumsCreateMchDTO.setContactMobileNumber(chinaumsCreateMchDTO.getLegalPersonMobileNumber());
//        }
//        // 将法人信息保存进去受益人信息
//        chinaumsCreateMchDTO.setBeneficiaryIdCardName(chinaumsCreateMchDTO.getLegalPersonIdCardName());
//        chinaumsCreateMchDTO.setBeneficiaryIdCardType(chinaumsCreateMchDTO.getLegalPersonIdCardType());
//        chinaumsCreateMchDTO.setBeneficiaryIdCardNumber(chinaumsCreateMchDTO.getLegalPersonIdCardNumber());
//        chinaumsCreateMchDTO.setBeneficiaryIdCardValidTime(chinaumsCreateMchDTO.getLegalPersonIdCardValidTime());
//        chinaumsCreateMchDTO.setBeneficiaryIdCardCopy(chinaumsCreateMchDTO.getLegalPersonIdCardCopy());
//        chinaumsCreateMchDTO.setBeneficiaryIdCardNational(chinaumsCreateMchDTO.getLegalPersonIdCardNational());
//        chinaumsCreateMchDTO.setBeneficiaryAddress(chinaumsCreateMchDTO.getBusinessLicenseCompanyAddress());
//        // 将法人信息保存进去实际控股人信息
//        chinaumsCreateMchDTO.setHoldingCompanyType("2");
//        chinaumsCreateMchDTO.setHoldingCompanyName(chinaumsCreateMchDTO.getBusinessLicenseCompanyName());
//        chinaumsCreateMchDTO.setHoldingCompanyLicenseNumber(chinaumsCreateMchDTO.getBusinessLicenseNumber());
//        chinaumsCreateMchDTO.setHoldingCompanyLicenseValidTime(chinaumsCreateMchDTO.getBusinessLicenseValidTime());
//        chinaumsCreateMchDTO.setHoldingCompanyLicenseType(chinaumsCreateMchDTO.getLegalPersonIdCardType());
//        // 企业信息
//        chinaumsCreateMchDTO.setBusinessInfoRegisteredCapital(10000000);
//        chinaumsCreateMchDTO.setBusinessInfoRegisteredTel(mchCreateDTO.getLegalPersonMobileNumber());
//        chinaumsCreateMchDTO.setBusinessInfoAddress(chinaumsCreateMchDTO.getBusinessLicenseCompanyAddress());
//        Map jsonObject = chinaumsUtil.execute(RouteUtil.ROUTE_WALLET_MCH_APPLICATIONS, (JSONObject) JSONObject.toJSON(chinaumsCreateMchDTO), Map.class);
//        // 生成成功获取系统订单号
//        chinaumsAuthInfo.setMchApplicationId(jsonObject.get("mchApplicationId").toString());
//        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
    }

    //TODO:等银行确认
//    public boolean validatePassword(String password) {
//        Company company = getUser().getCompany();
//        JSONObject params = new JSONObject();
//        params.put("walletId", company.getWalletId());
//        byxTradeWayService.setTradeWayInCert(company.getWalletId(), params);
//        byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_WALLET_APPLICATIONS_REG_INFO)
//    }

    @Override
    public ChinaumsApplicationStatusVO status() {
        Company company = getUser().getCompany();
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo == null) {
            ChinaumsApplicationStatusVO chinaumsApplicationStatusVO = new ChinaumsApplicationStatusVO();
            // 企业
            chinaumsApplicationStatusVO.setApplicationType("2");
            chinaumsApplicationStatusVO.setOrganizationType("2");
            chinaumsApplicationStatusVO.setFailureMsgs(YnceError.YNCE_218009.getMsg());
            chinaumsApplicationStatusVO.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_UNCOMMIT);
            return chinaumsApplicationStatusVO;
        }
        String applicationType;
        String applicationId;
        if (StringUtils.isNotBlank(chinaumsAuthInfo.getCusApplicationId())) {
            applicationType = "1";
//            applicationId = chinaumsAuthInfo.getCusApplicationId();
        } else {
            applicationType = "2";
//            applicationId = chinaumsAuthInfo.getMchApplicationId();
        }
        // 处理状态
        try {
            handleApplicationStatus(applicationType, company.getRegisterNo(), chinaumsAuthInfo);
        } catch (Exception e) {
            log.warn("处理银联认证状态异常 - ", e);
        }
        ChinaumsApplicationStatusVO chinaumsApplicationStatusVO = new ChinaumsApplicationStatusVO();
        BeanUtils.copyProperties(chinaumsAuthInfo, chinaumsApplicationStatusVO);
        chinaumsApplicationStatusVO.setApplicationType(applicationType);
        chinaumsApplicationStatusVO.setOrganizationType(chinaumsAuthInfo.getOrganizationType());
        return chinaumsApplicationStatusVO;
    }

    @Override
    public ChinaumsAuthInfoVO getAuthInfo() {
        Company company = getUser().getCompany();
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo == null) {
            throw new YnceErrorException(YnceError.YNCE_218009);
        }
        ChinaumsAuthInfoVO chinaumsAuthInfoVO = new ChinaumsAuthInfoVO();
        BeanUtils.copyProperties(chinaumsAuthInfo, chinaumsAuthInfoVO,
                "businessLicenseCopyFile",
                "organizationCertCopyFile",
                "taxRegistrationCertCopyFile",
                "legalPersonIdCardCopyFile",
                "legalPersonIdCardNationalFile",
                "contactIdCardCopyFile",
                "contactIdCardNationalFile");
        // 图片转化
        chinaumsAuthInfoVO.setBusinessLicenseCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getBusinessLicenseCopyFile()));
        chinaumsAuthInfoVO.setOrganizationCertCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getOrganizationCertCopyFile()));
        chinaumsAuthInfoVO.setTaxRegistrationCertCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getTaxRegistrationCertCopyFile()));
        chinaumsAuthInfoVO.setTaxRegistrationCertCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getTaxRegistrationCertCopyFile()));
        chinaumsAuthInfoVO.setLegalPersonIdCardCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getLegalPersonIdCardCopyFile()));
        chinaumsAuthInfoVO.setLegalPersonIdCardNationalFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getLegalPersonIdCardNationalFile()));
        chinaumsAuthInfoVO.setContactIdCardCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getContactIdCardCopyFile()));
        chinaumsAuthInfoVO.setContactIdCardNationalFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getContactIdCardNationalFile()));
        chinaumsAuthInfoVO.setIdCardCopyFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getIdCardCopyFile()));
        chinaumsAuthInfoVO.setIdCardNationalFile(metaFileService.getMetaFileVO(chinaumsAuthInfo.getIdCardNationalFile()));
        return chinaumsAuthInfoVO;
    }

    @Override
    public ChinaumsAuthInfo getCurrentAuthInfo() {
        Company company = getUser().getCompany();
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo == null) {
            throw new YnceErrorException(YnceError.YNCE_218009);
        }
        return chinaumsAuthInfo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleApplicationStatus(String applicationType, String registerNo, ChinaumsAuthInfo chinaumsAuthInfo) {
        if (StringUtils.isBlank(registerNo)) {
            return false;
        }
        Company company = companyRepository.findByRegisterNo(registerNo);
        if (company == null) {
            return false;
        }
        if (chinaumsAuthInfo == null) {
            chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByMchId(registerNo);
            // 若查询不到则返回
            if (chinaumsAuthInfo == null) {
                log.error("商家注册回调处理异常，找不到注册号-{}", registerNo);
                return false;
            }
        }
        if (chinaumsAuthInfo.getApplicationStatus().equals(ApplicationStatus.REGISTER_SUCCESS)) {
            return true;
        }
        JSONObject params = new JSONObject();
        params.put("registerNo", registerNo);
        ByxChinaumsMchRegInfoVO chinaumsMchRegInfoVO = byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_WALLET_APPLICATIONS_REG_INFO, params, ByxChinaumsMchRegInfoVO.class, true);
        if (chinaumsMchRegInfoVO == null || chinaumsMchRegInfoVO.getList() == null || chinaumsMchRegInfoVO.getList().size() < 1) {
            throw new RuntimeException("找不到商家认证信息.");
        }
        ByxChinaumsMchRegInfoDetailVO detailVO = chinaumsMchRegInfoVO.getList().get(0);
        this.setRegStatusFromCondition(detailVO.getRegStatus(), chinaumsAuthInfo);
        if (!detailVO.getRegStatus().equals("10")) {
            chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
            return true;
        }
        // 处理注册成功状态 即getRegStatus == 10
        // 保存企业电子账簿ID
        if (StringUtils.isBlank(company.getWalletId())) {
            company.setWalletId(detailVO.getBwalletId());
            companyRepository.save(company);
        }

        // 保存相关信息到认证信息中
        chinaumsAuthInfo.setRelAcctNo(detailVO.getBwalletId());
        chinaumsAuthInfo.setBalanceAcctId(detailVO.getBwalletId());
        chinaumsAuthInfo.setBusinessLicenseNumber(detailVO.getBizLicNo());
        chinaumsAuthInfo.setBusinessLicenseCompanyName(detailVO.getCompanyName());
        chinaumsAuthInfo.setBusinessLicenseCompanyAddress(detailVO.getRegistAddr());
        chinaumsAuthInfo.setContactIdCardName(detailVO.getContactName());
        chinaumsAuthInfo.setContactMobileNumber(detailVO.getContactPhoneNum());
        chinaumsAuthInfo.setContactEmail(detailVO.getContactEmail());
        chinaumsAuthInfo.setLegalPersonIdCardName(detailVO.getLegalName());
        chinaumsAuthInfo.setLegalPersonIdCardType(detailVO.getLegalIdType());
        chinaumsAuthInfo.setLegalPersonMobileNumber(detailVO.getLegalPhoneNum());
        chinaumsAuthInfo.setSettleAcctBankBranchCode(detailVO.getBankNo());
        chinaumsAuthInfo.setSettleAcctBankName(detailVO.getBankName());
        chinaumsAuthInfo.setSettleAcctName(detailVO.getBwalletAcctName());
        chinaumsAuthInfo.setIdCardNumber(detailVO.getLegalIdCard());
        chinaumsAuthInfo.setSettleAcctBankAcctNo(detailVO.getSettAcctNo());
        chinaumsAuthInfo.setElecBankNo(chinaumsAuthInfo.getElecBankNo());
        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
        return true;
    }

    public void setRegStatusFromCondition(String regStatus, ChinaumsAuthInfo chinaumsAuthInfo) {
        switch (regStatus) {
            case "01": // 01-已发送注册链接 email；
            case "02": // 02-已验证邮箱（已验证注册链接）
            case "03": // 03-认证材料待提交；
            case "21": // 21-申请待提交（子商户注册时使用）；
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_UNCOMMIT);
                break;
            case "04": // 04-材料自动检查不通过
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_FAIL);
                break;
            case "07": // 07-初审不通过
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.FIRST_AUDITING_FAIL);
                break;
            case "09": // 09-复审不通过
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.SECOND_AUDITING_FAIL);
                break;
            case "11": // 11-注册失败
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.REGISTER_FAIL);
                break;
            case "05":  // 05-认证材料已提交（待审核）
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_SUCCESS);
                break;
            case "06": // 06-初审通过
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.FIRST_AUDITING_SUCCESS);
                break;
            case "08": // 08-复审通过
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.SECOND_AUDITING_SUCCESS);
                break;
            case "10": // 10-注册完成（添加用户成功、开户成功）；
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.REGISTER_SUCCESS);
                break;
        }
    }

    public ChinaumsAuthInfo changeChinaumsAuthInfoStatus(ByxChinaumsCallBackDTO byxChinaumsCallBackDTO) {
        if (byxChinaumsCallBackDTO == null ||
                StringUtils.isEmpty(byxChinaumsCallBackDTO.getRegisterNo()) ||
                StringUtils.isEmpty(byxChinaumsCallBackDTO.getRegStatus())) {
            return null;
        }
        Company company = companyRepository.findByRegisterNo(byxChinaumsCallBackDTO.getRegisterNo());
        if (company == null) {
            return null;
        }
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo == null) {
            chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByMchId(byxChinaumsCallBackDTO.getRegisterNo());
            // 若查询不到则返回
            if (chinaumsAuthInfo == null) {
                log.error("商家注册回调处理异常，找不到注册号-{}", byxChinaumsCallBackDTO.getRegisterNo());
                return null;
            }
        }
        this.setRegStatusFromCondition(byxChinaumsCallBackDTO.getRegStatus(), chinaumsAuthInfo);
        if (!byxChinaumsCallBackDTO.getRegStatus().equals("10")) {
            chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
            return chinaumsAuthInfo;
        }
        return chinaumsAuthInfo;
    }

    public ChinaumsAuthInfo changeChinaumsAuthInfoStatus(ByxChinaumsCallBackDTO byxChinaumsCallBackDTO, ChinaumsAuthInfo chinaumsAuthInfo) {
        this.setRegStatusFromCondition(byxChinaumsCallBackDTO.getRegStatus(), chinaumsAuthInfo);
        if (!byxChinaumsCallBackDTO.getRegStatus().equals("10")) {
            chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
            return chinaumsAuthInfo;
        }
        return chinaumsAuthInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleMchCallBackSuccess(ByxChinaumsCallBackDTO byxChinaumsCallBackDTO) {
        if (byxChinaumsCallBackDTO == null ||
                StringUtils.isEmpty(byxChinaumsCallBackDTO.getRegisterNo()) ||
                StringUtils.isEmpty(byxChinaumsCallBackDTO.getRegStatus())) {
            return null;
        }
        Company company = companyRepository.findByRegisterNo(byxChinaumsCallBackDTO.getRegisterNo());
        if (company == null) {
            return null;
        }
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo == null) {
            chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByMchId(byxChinaumsCallBackDTO.getRegisterNo());
            // 若查询不到则返回
            if (chinaumsAuthInfo == null) {
                log.error("商家注册回调处理异常，找不到注册号-{}", byxChinaumsCallBackDTO.getRegisterNo());
                return null;
            }
        }
        if (chinaumsAuthInfo.getApplicationStatus().equals(ApplicationStatus.REGISTER_SUCCESS)) {
            return true;
        }
        chinaumsAuthInfo = this.changeChinaumsAuthInfoStatus(byxChinaumsCallBackDTO, chinaumsAuthInfo);
        if (chinaumsAuthInfo == null) {
            return false;
        }

        if (!byxChinaumsCallBackDTO.getRegStatus().equals("10")) {
            return true;
        }
        // 处理注册成功状态 即getRegStatus == 10
        // 保存企业电子账簿ID
        if (StringUtils.isBlank(company.getWalletId())) {
            company.setWalletId(byxChinaumsCallBackDTO.getWalletId());
            companyRepository.save(company);
        }
        // 保存相关信息到认证信息中
        chinaumsAuthInfo.setRelAcctNo(byxChinaumsCallBackDTO.getWalletId());
        chinaumsAuthInfo.setBalanceAcctId(byxChinaumsCallBackDTO.getWalletId());
        chinaumsAuthInfo.setBusinessLicenseNumber(byxChinaumsCallBackDTO.getBizLicNo());
        chinaumsAuthInfo.setBusinessLicenseCompanyName(byxChinaumsCallBackDTO.getCompanyName());


        JSONObject params = new JSONObject();
        params.put("registerNo", byxChinaumsCallBackDTO.getRegisterNo());
        ByxChinaumsMchRegInfoVO chinaumsMchRegInfoVO = byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_WALLET_APPLICATIONS_REG_INFO, params, ByxChinaumsMchRegInfoVO.class, true);
        if (chinaumsMchRegInfoVO != null && chinaumsMchRegInfoVO.getList() != null && chinaumsMchRegInfoVO.getList().size() > 0) {
            ByxChinaumsMchRegInfoDetailVO detailVO = chinaumsMchRegInfoVO.getList().get(0);
            chinaumsAuthInfo.setBusinessLicenseCompanyAddress(detailVO.getRegistAddr());
            chinaumsAuthInfo.setContactIdCardName(detailVO.getContactName());
            chinaumsAuthInfo.setContactMobileNumber(detailVO.getContactPhoneNum());
            chinaumsAuthInfo.setContactEmail(detailVO.getContactEmail());
            chinaumsAuthInfo.setLegalPersonIdCardName(detailVO.getLegalName());
            chinaumsAuthInfo.setLegalPersonIdCardType(detailVO.getLegalIdType());
            chinaumsAuthInfo.setLegalPersonMobileNumber(detailVO.getLegalPhoneNum());
            chinaumsAuthInfo.setSettleAcctBankBranchCode(detailVO.getBankNo());
            chinaumsAuthInfo.setSettleAcctBankName(detailVO.getBankName());
            chinaumsAuthInfo.setSettleAcctName(detailVO.getBwalletAcctName());
            chinaumsAuthInfo.setIdCardNumber(detailVO.getLegalIdCard());
            chinaumsAuthInfo.setSettleAcctBankAcctNo(detailVO.getSettAcctNo());
            chinaumsAuthInfo.setElecBankNo(detailVO.getElecBankNo());
        }

        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);

        return true;
    }


    @Override
    @Transactional
    public void cusCreate(CusCreateDTO cusCreateDTO) {
        Company company = getUser().getCompany();
        // 平台订单号
        String outRequestNo;
        // 判断该企业是否已认证
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (chinaumsAuthInfo != null) {
            // 判断状态，若为失败可重新发起
            if (!chinaumsAuthInfo.getApplicationStatus().equals(ApplicationStatus.REGISTER_FAIL)) {
                throw new YnceErrorException(YnceError.YNCE_218010);
            }
        } else {
            // 保存认证信息
            chinaumsAuthInfo = new ChinaumsAuthInfo();
            outRequestNo = sequenceUtil.getNextSequenceNumber("YLRZ");
            chinaumsAuthInfo.setCompany(company);
            chinaumsAuthInfo.setOutRequestNo(outRequestNo);
        }
        // 处理图片
        chinaumsAuthInfo.setIdCardCopyFile(metaFileRepository.findById(cusCreateDTO.getIdCardCopyId()).orElse(null));
        chinaumsAuthInfo.setIdCardNationalFile(metaFileRepository.findById(cusCreateDTO.getIdCardNationalId()).orElse(null));
        BeanUtils.copyProperties(cusCreateDTO, chinaumsAuthInfo, "outRequestNo", "company");
        chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_SUCCESS);
        // 拼接请求数据
        ByxChinaumsCreateCusDTO chinaumsCreateCusDTO = new ByxChinaumsCreateCusDTO();
//        ChinaumsCreateCusDTO chinaumsCreateCusDTO = new ChinaumsCreateCusDTO();
//        BeanUtils.copyProperties(cusCreateDTO, chinaumsCreateCusDTO);
//        chinaumsCreateCusDTO.setOutRequestNo(chinaumsAuthInfo.getOutRequestNo());

        chinaumsCreateCusDTO.setMctOrderNo(chinaumsAuthInfo.getOutRequestNo());
        chinaumsCreateCusDTO.setUserName(cusCreateDTO.getSettleAcctName());
        chinaumsCreateCusDTO.setMobileNo(cusCreateDTO.getMobileNumber());
        chinaumsCreateCusDTO.setIdCard(cusCreateDTO.getIdCardNumber());
        // 使用银行卡三要素类型
        chinaumsCreateCusDTO.setAuthType(1);
        chinaumsCreateCusDTO.setBankAcctNo(cusCreateDTO.getSettleAcctBankAcctNo());
        chinaumsCreateCusDTO.setIsActive(1);
        chinaumsCreateCusDTO.setEncryptPwd(cusCreateDTO.getPassword());
        //1：H5 密码键盘加密（H5、小程序）。
        //2：非 H5 密码键盘加密（PC、ios、安卓）。
        chinaumsCreateCusDTO.setEncryptType("2");
        chinaumsCreateCusDTO.setPlugRandomKey(randomKeyService.getOneKey());

        // 证件开始结束时间处理
//        String idCardValidTime = cusCreateDTO.getIdCardStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        if (cusCreateDTO.getIdCardEndTime() == null) {
//            idCardValidTime += ",长期";
//        } else {
//            idCardValidTime = idCardValidTime + "," + cusCreateDTO.getIdCardEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        }
//        chinaumsCreateCusDTO.setIdCardValidTime(idCardValidTime);
        // 对敏感信息加密处理
//        String publicKey = chinaumsUtil.getPublicKey();
//        try {
        // 证件号码
//            chinaumsCreateCusDTO.setIdCardNumber(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getIdCardNumber(), publicKey));
//            // 证件名称
//            chinaumsCreateCusDTO.setIdCardName(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getIdCardName(), publicKey));
//            // 手机号码
//            chinaumsCreateCusDTO.setMobileNumber(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getMobileNumber(), publicKey));
//            // 开户名称
//            chinaumsCreateCusDTO.setSettleAcctName(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getSettleAcctName(), publicKey));
//            // 银行账号
//            chinaumsCreateCusDTO.setSettleAcctBankAcctNo(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getSettleAcctBankAcctNo(), publicKey));
        // 交易密码
//            chinaumsCreateCusDTO.setPassword(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getPassword(), publicKey));
//        } catch (Exception exception) {
//            throw new YnceErrorException(YnceError.YNCE_218014);
//        }
//        chinaumsCreateCusDTO.setSettleAcctProfession("40100");
//        chinaumsCreateCusDTO.setNationality("1");
        JSONObject jsonObject = byxChinaumsUtil.execute(RouteUtil.ROUTE_WALLET_CUS_APPLICATIONS, (JSONObject) JSONObject.toJSON(chinaumsCreateCusDTO), JSONObject.class);
        if (jsonObject == null || jsonObject.get("walletId") == null) {
            log.error("认证失败，调用ROUTE_WALLET_CUS_APPLICATIONS异常");
            throw new YnceErrorException(YnceError.YNCE_218001, "认证失败，未知异常");
        }
        // 生成成功获取个人系统订单号/交易订单号
        // 注：交易订单号有可能为空，若为空则cusApplicationId存储的是walletId
        chinaumsAuthInfo.setCusApplicationId(jsonObject.get("transOrderNo") == null ? jsonObject.get("walletId").toString() : jsonObject.get("transOrderNo").toString());
        chinaumsAuthInfo.setBalanceAcctId(jsonObject.get("walletId").toString());
//        company.setWalletId(jsonObject.get("walletId").toString());
//        companyRepository.saveAndFlush(company);
        chinaumsAuthInfo.setApplicationStatus(ByxApplicationStatusTransfer.transfer(jsonObject.get("IDImagesStatus") == null ? "" : jsonObject.get("IDImagesStatus").toString()));
//        chinaumsAuthInfo.setSettleAcctType("1");
        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean accountValidation(String outRequestNo) {
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByOutRequestNo(outRequestNo);
        if (chinaumsAuthInfo == null) {
            return false;
        } else {
            if (chinaumsAuthInfo.getApplicationStatus().equals(ApplicationStatus.FIRST_AUDITING_SUCCESS)) {
                chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.FIRST_AUDITING_SUCCESS);
                chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
            }
            return true;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cusUpdate(CusCreateDTO cusCreateDTO) {
        // 获取企业银联认证信息
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(getUser().getCompany().getId());
        if (chinaumsAuthInfo == null) {
            throw new YnceErrorException(YnceError.YNCE_218009);
        }
        if (!chinaumsAuthInfo.getApplicationStatus().equals(ApplicationStatus.REGISTER_SUCCESS)) {
            throw new YnceErrorException(YnceError.YNCE_218030, "当前认证状态不允许修改");
        }
        // 不允许修改身份证号
        if (!chinaumsAuthInfo.getIdCardNumber().equals(cusCreateDTO.getIdCardNumber())) {
            throw new YnceErrorException(YnceError.YNCE_218030, "身份证不允许修改");
        }
        // 处理图片
        chinaumsAuthInfo.setIdCardCopyFile(metaFileRepository.findById(cusCreateDTO.getIdCardCopyId()).orElse(null));
        chinaumsAuthInfo.setIdCardNationalFile(metaFileRepository.findById(cusCreateDTO.getIdCardNationalId()).orElse(null));
        chinaumsAuthInfo.setOutRequestNo(sequenceUtil.getNextSequenceNumber("YLRZ"));
        BeanUtils.copyProperties(cusCreateDTO, chinaumsAuthInfo, "outRequestNo", "company");
        // 拼接请求数据
        ChinaumsUpdateCusDTO chinaumsUpdateCusDTO = new ChinaumsUpdateCusDTO();
        BeanUtils.copyProperties(cusCreateDTO, chinaumsUpdateCusDTO);
        chinaumsUpdateCusDTO.setOutRequestNo(chinaumsAuthInfo.getOutRequestNo());
        // 证件开始结束时间处理
        String idCardValidTime = cusCreateDTO.getIdCardStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (cusCreateDTO.getIdCardEndTime() == null) {
            idCardValidTime += ",长期";
        } else {
            idCardValidTime = idCardValidTime + "," + cusCreateDTO.getIdCardEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        chinaumsUpdateCusDTO.setIdCardValidTime(idCardValidTime);
        // 对敏感信息加密处理
        String publicKey = byxChinaumsUtil.getPublicKey();
        try {
            // 证件号码
            chinaumsUpdateCusDTO.setIdCardNumber(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getIdCardNumber(), publicKey));
            // 证件名称
            chinaumsUpdateCusDTO.setIdCardName(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getIdCardName(), publicKey));
            // 手机号码
            chinaumsUpdateCusDTO.setMobileNumber(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getMobileNumber(), publicKey));
            // 开户名称
            chinaumsUpdateCusDTO.setSettleAcctName(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getSettleAcctName(), publicKey));
            // 银行账号
            chinaumsUpdateCusDTO.setSettleAcctBankAcctNo(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getSettleAcctBankAcctNo(), publicKey));
            // 交易密码
            chinaumsUpdateCusDTO.setPassword(RSAEncryptorUtil.encryptByPublicKey(cusCreateDTO.getPassword(), publicKey));
        } catch (Exception exception) {
            throw new YnceErrorException(YnceError.YNCE_218014);
        }
        chinaumsUpdateCusDTO.setSettleAcctProfession("40100");
        chinaumsUpdateCusDTO.setNationality("1");
        chinaumsUpdateCusDTO.setCusId(chinaumsAuthInfo.getCusId());
        JSONObject jsonObject = byxChinaumsUtil.execute(RouteUtil.ROUTE_WALLET_CUS_APPLICATIONS_RENEW, (JSONObject) JSONObject.toJSON(chinaumsUpdateCusDTO), JSONObject.class);
        // 调用查询接口
        ChinaumsMchStatus chinaumsMchStatus = byxChinaumsUtil.execute(RouteUtil.ROUTE_WALLET_CUS_APPLICATIONS_STATUS,
                (JSONObject) JSONObject.toJSON(ChinaumsStatusDTO.builder().cusApplicationId(jsonObject.get("cusApplicationId").toString()).build()), ChinaumsMchStatus.class);
        if (chinaumsMchStatus.getApplicationStatus().equals("succeeded")) {
            // 保存相关信息到认证信息中
            chinaumsAuthInfo.setBindAcctName(cusCreateDTO.getIdCardName());
            chinaumsAuthInfo.setSettleAcctId(chinaumsMchStatus.getSettleAcctId());
            chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
            // 保存银行卡信息（若存在则不再添加）
            String settleAcctBankAcctNo = chinaumsAuthInfo.getSettleAcctBankAcctNo();
            if (CollectionUtils.isEmpty(chinaumsAuthInfo.getChinaumsBankCard())
                    || !chinaumsAuthInfo.getChinaumsBankCard().stream().filter(chinaumsBankCard -> chinaumsBankCard.getBankAcctNo().equals(settleAcctBankAcctNo)).findFirst().isPresent()) {
                ChinaumsBankCard chinaumsBankCard = new ChinaumsBankCard();
                chinaumsBankCard.setBankCode(chinaumsAuthInfo.getSettleAcctBankCode());
                chinaumsBankCard.setBankBranchCode(chinaumsAuthInfo.getSettleAcctBankBranchCode());
                chinaumsBankCard.setBankAcctNo(chinaumsAuthInfo.getSettleAcctBankAcctNo());
                chinaumsBankCard.setMobileNumber(chinaumsAuthInfo.getMobileNumber());
                chinaumsBankCard.setChinaumsAuthInfo(chinaumsAuthInfo);
                chinaumsBankCard.setOutRequestNo(chinaumsAuthInfo.getOutRequestNo());
                chinaumsBankCard.setBankAcctType(chinaumsAuthInfo.getSettleAcctType());
                chinaumsBankCard.setBankName(chinaumsAuthInfo.getSettleAcctBankName());
                chinaumsBankCard.setSettleAcctId(chinaumsMchStatus.getSettleAcctId());
                chinaumsBankCard.setStatus(ChinaumsBankCardStatus.SUCCEEDED);
                chinaumsBankCardRepository.save(chinaumsBankCard);
            }
        } else if (chinaumsMchStatus.getApplicationStatus().equals("failed")) {
            throw new YnceErrorException(YnceError.YNCE_218030, chinaumsMchStatus.getFailureMsgs());
        }
        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void passwordUpdate(PasswordUpdateDTO passwordUpdateDTO) {
        // 获取电子账簿ID
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(getUser().getCompany().getId());
        if (chinaumsAuthInfo == null) {
            throw new YnceErrorException(YnceError.YNCE_218009);
        }
        ByxChinaumsPasswordUpdateDTO byxChinaumsPasswordUpdateDTO = new ByxChinaumsPasswordUpdateDTO();
        byxChinaumsPasswordUpdateDTO.setEncryptOrigPwd(passwordUpdateDTO.getOriginalPassword());
        byxChinaumsPasswordUpdateDTO.setEncryptNewPwd(passwordUpdateDTO.getNewPassword());
        byxChinaumsPasswordUpdateDTO.setPlugRandomKey(passwordUpdateDTO.getPlugRandomKey());
        byxChinaumsPasswordUpdateDTO.setWalletId(chinaumsAuthInfo.getBalanceAcctId());
        byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_WALLET_UPAPI_ACCT_PASSWORDS_MODIFY, (JSONObject) JSONObject.toJSON(byxChinaumsPasswordUpdateDTO), JSONObject.class);
        chinaumsAuthInfo.setPassword(passwordUpdateDTO.getNewPassword());
        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void passwordReset(PasswordResetDTO passwordResetDTO) {
        // 获取电子账簿ID
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(getUser().getCompany().getId());
        if (chinaumsAuthInfo == null) {
            throw new YnceErrorException(YnceError.YNCE_218009);
        }
        ByxPasswordResetDTO byxPasswordResetDTO = new ByxPasswordResetDTO();
        byxPasswordResetDTO.setLegalSmsAuthCode(passwordResetDTO.getSmsCode());
        byxPasswordResetDTO.setWalletId(chinaumsAuthInfo.getBalanceAcctId());
        byxPasswordResetDTO.setEncryptNewPwd(passwordResetDTO.getNewPassword());
        byxPasswordResetDTO.setEncryptType("1");
        byxPasswordResetDTO.setPlugRandomKey(passwordResetDTO.getPlugRandomKey());

        byxPasswordResetDTO.setLegalName(chinaumsAuthInfo.getLegalPersonIdCardName());
        byxPasswordResetDTO.setLegalIdCard(chinaumsAuthInfo.getLegalPersonIdCardNumber());
        byxPasswordResetDTO.setLegalPhoneNum(chinaumsAuthInfo.getLegalPersonMobileNumber());

        byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_WALLET_UPAPI_ACCT_PASSWORDS_RESET, (JSONObject) JSONObject.toJSON(byxPasswordResetDTO), JSONObject.class);
//        chinaumsAuthInfo.setPassword(passwordResetDTO.getNewPassword());
        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mchUpdate(MchCreateDTO mchCreateDTO) {
        Company company = getUser().getCompany();
        // 只有认证成功的可以调用修改接口
        if (StringUtils.isBlank(company.getWalletId())) {
            throw new YnceErrorException(YnceError.YNCE_218034);
        }
        ChinaumsAuthInfo chinaumsAuthInfo = chinaumsAuthInfoRepository.findFirstByCompanyId(company.getId());
        if (ApplicationStatus.REGISTER_SUCCESS.equals(chinaumsAuthInfo.getApplicationStatus())) {
            // 生成平台订单号
            chinaumsAuthInfo.setOutRequestNo(sequenceUtil.getNextSequenceNumber("YLRZ"));
        }
        // 处理图片
        chinaumsAuthInfo.setBusinessLicenseCopyFile(metaFileRepository.findById(mchCreateDTO.getBusinessLicenseCopyId()).orElse(null));
        chinaumsAuthInfo.setLegalPersonIdCardCopyFile(metaFileRepository.findById(mchCreateDTO.getLegalPersonIdCardCopyId()).orElse(null));
        chinaumsAuthInfo.setLegalPersonIdCardNationalFile(metaFileRepository.findById(mchCreateDTO.getLegalPersonIdCardNationalId()).orElse(null));
        if (mchCreateDTO.getOrganizationCertCopyId() != null) {
            chinaumsAuthInfo.setOrganizationCertCopyFile(metaFileRepository.findById(mchCreateDTO.getOrganizationCertCopyId()).orElse(null));
        }
        if (mchCreateDTO.getTaxRegistrationCertCopyId() != null) {
            chinaumsAuthInfo.setTaxRegistrationCertCopyFile(metaFileRepository.findById(mchCreateDTO.getTaxRegistrationCertCopyId()).orElse(null));
        }
        if (mchCreateDTO.getContactIdCardCopyId() != null) {
            chinaumsAuthInfo.setContactIdCardCopyFile(metaFileRepository.findById(mchCreateDTO.getContactIdCardCopyId()).orElse(null));
        }
        if (mchCreateDTO.getContactIdCardNationalId() != null) {
            chinaumsAuthInfo.setContactIdCardNationalFile(metaFileRepository.findById(mchCreateDTO.getContactIdCardNationalId()).orElse(null));
        }
        BeanUtils.copyProperties(mchCreateDTO, chinaumsAuthInfo, "outRequestNo", "company");
        chinaumsAuthInfo.setApplicationStatus(ApplicationStatus.CERTIFICATION_MAT_UNCOMMIT);
        // 拼接银联请求DTO
        ChinaumsUpdateMchDTO chinaumsUpdateMchDTO = new ChinaumsUpdateMchDTO();
        chinaumsUpdateMchDTO.setMchId(chinaumsAuthInfo.getMchId());
        BeanUtils.copyProperties(mchCreateDTO, chinaumsUpdateMchDTO);
        chinaumsUpdateMchDTO.setOutRequestNo(chinaumsAuthInfo.getOutRequestNo());
        // 根据营业执照开始结束时间处理
        String businessLicenseValidTime = mchCreateDTO.getBusinessLicenseStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (mchCreateDTO.getBusinessLicenseEndTime() == null) {
            businessLicenseValidTime += ",长期";
        } else {
            businessLicenseValidTime = businessLicenseValidTime + "," + mchCreateDTO.getBusinessLicenseEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        chinaumsUpdateMchDTO.setBusinessLicenseValidTime(businessLicenseValidTime);
        // 根据组织机构开始结束时间处理
        if (mchCreateDTO.getOrganizationCertStartTime() != null) {
            String organizationCertValidTime = mchCreateDTO.getOrganizationCertStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (mchCreateDTO.getOrganizationCertEndTime() == null) {
                organizationCertValidTime += ",长期";
            } else {
                organizationCertValidTime = businessLicenseValidTime + "," + mchCreateDTO.getOrganizationCertEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
            chinaumsUpdateMchDTO.setOrganizationCertValidTime(organizationCertValidTime);
        }
        // 根据法人证件开始结束时间处理
        String legalPersonIdCardValidTime = mchCreateDTO.getLegalPersonIdCardStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (mchCreateDTO.getLegalPersonIdCardEndTime() == null) {
            legalPersonIdCardValidTime += ",长期";
        } else {
            legalPersonIdCardValidTime = legalPersonIdCardValidTime + "," + mchCreateDTO.getLegalPersonIdCardEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        chinaumsUpdateMchDTO.setLegalPersonIdCardValidTime(legalPersonIdCardValidTime);
        // 对敏感信息加密处理
        String publicKey = byxChinaumsUtil.getPublicKey();
        try {
            // 开户名称
            chinaumsUpdateMchDTO.setSettleAcctName(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getSettleAcctName(), publicKey));
            // 银行账号
            chinaumsUpdateMchDTO.setSettleAcctBankAcctNo(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getSettleAcctBankAcctNo(), publicKey));
            // 法人姓名
            chinaumsUpdateMchDTO.setLegalPersonIdCardName(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getLegalPersonIdCardName(), publicKey));
            // 法人证件号码
            chinaumsUpdateMchDTO.setLegalPersonIdCardNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getLegalPersonIdCardNumber(), publicKey));
            // 联系人姓名
            chinaumsUpdateMchDTO.setContactIdCardName(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactIdCardName(), publicKey));
            // 联系人身份证件号码
            chinaumsUpdateMchDTO.setContactIdCardNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactIdCardNumber(), publicKey));
            // 法人手机号
            chinaumsUpdateMchDTO.setLegalPersonMobileNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getLegalPersonMobileNumber(), publicKey));
            // 联系人手机号
            chinaumsUpdateMchDTO.setContactMobileNumber(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactMobileNumber(), publicKey));
            // 联系人邮箱
            chinaumsUpdateMchDTO.setContactEmail(RSAEncryptorUtil.encryptByPublicKey(mchCreateDTO.getContactEmail(), publicKey));
            // 无需设置交易密码
            chinaumsUpdateMchDTO.setPassword(null);
        } catch (Exception exception) {
            throw new YnceErrorException(YnceError.YNCE_218014);
        }
        // 当不填写联系人时，将法人信息保存进去
        if (!mchCreateDTO.getIsFillContact()) {
            chinaumsUpdateMchDTO.setContactIdCardName(chinaumsUpdateMchDTO.getLegalPersonIdCardName());
            chinaumsUpdateMchDTO.setContactIdCardType(chinaumsUpdateMchDTO.getLegalPersonIdCardType());
            chinaumsUpdateMchDTO.setContactIdCardCopy(chinaumsUpdateMchDTO.getLegalPersonIdCardCopy());
            chinaumsUpdateMchDTO.setContactIdCardNational(chinaumsUpdateMchDTO.getLegalPersonIdCardNational());
            chinaumsUpdateMchDTO.setContactIdCardNumber(chinaumsUpdateMchDTO.getLegalPersonIdCardNumber());
            chinaumsUpdateMchDTO.setContactIdCardValidTime(chinaumsUpdateMchDTO.getLegalPersonIdCardValidTime());
            chinaumsUpdateMchDTO.setContactMobileNumber(chinaumsUpdateMchDTO.getLegalPersonMobileNumber());
        }
        // 将法人信息保存进去受益人信息
        chinaumsUpdateMchDTO.setBeneficiaryIdCardName(chinaumsUpdateMchDTO.getLegalPersonIdCardName());
        chinaumsUpdateMchDTO.setBeneficiaryIdCardType(chinaumsUpdateMchDTO.getLegalPersonIdCardType());
        chinaumsUpdateMchDTO.setBeneficiaryIdCardNumber(chinaumsUpdateMchDTO.getLegalPersonIdCardNumber());
        chinaumsUpdateMchDTO.setBeneficiaryIdCardValidTime(chinaumsUpdateMchDTO.getLegalPersonIdCardValidTime());
        chinaumsUpdateMchDTO.setBeneficiaryIdCardCopy(chinaumsUpdateMchDTO.getLegalPersonIdCardCopy());
        chinaumsUpdateMchDTO.setBeneficiaryIdCardNational(chinaumsUpdateMchDTO.getLegalPersonIdCardNational());
        chinaumsUpdateMchDTO.setBeneficiaryAddress(chinaumsUpdateMchDTO.getBusinessLicenseCompanyAddress());
        // 将法人信息保存进去实际控股人信息
        chinaumsUpdateMchDTO.setHoldingCompanyType("2");
        chinaumsUpdateMchDTO.setHoldingCompanyName(chinaumsUpdateMchDTO.getBusinessLicenseCompanyName());
        chinaumsUpdateMchDTO.setHoldingCompanyLicenseNumber(chinaumsUpdateMchDTO.getBusinessLicenseNumber());
        chinaumsUpdateMchDTO.setHoldingCompanyLicenseValidTime(chinaumsUpdateMchDTO.getBusinessLicenseValidTime());
        chinaumsUpdateMchDTO.setHoldingCompanyLicenseType(chinaumsUpdateMchDTO.getLegalPersonIdCardType());
        // 企业信息
        chinaumsUpdateMchDTO.setBusinessInfoRegisteredCapital(10000000);
        chinaumsUpdateMchDTO.setBusinessInfoRegisteredTel(mchCreateDTO.getLegalPersonMobileNumber());
        chinaumsUpdateMchDTO.setBusinessInfoAddress(chinaumsUpdateMchDTO.getBusinessLicenseCompanyAddress());
        Map jsonObject = byxChinaumsUtil.execute(RouteUtil.ROUTE_WALLET_MCH_APPLICATIONS_RENEW, (JSONObject) JSONObject.toJSON(chinaumsUpdateMchDTO), Map.class);
        // 生成成功获取系统订单号
        chinaumsAuthInfo.setMchApplicationId(jsonObject.get("mchApplicationId").toString());
        chinaumsAuthInfoRepository.save(chinaumsAuthInfo);
    }
}
