package com.mmc.iuav.user.service.xzsz.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.mmc.iuav.general.CodeUtil;
import com.mmc.iuav.http.HttpsRequestUtil;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.user.constant.UserSystemConstant;
import com.mmc.iuav.user.dao.RealNameAuthDao;
import com.mmc.iuav.user.dao.wallet.PayWalletDao;
import com.mmc.iuav.user.dao.xzsz.XzDao;
import com.mmc.iuav.user.entity.RealNameAuthDO;
import com.mmc.iuav.user.entity.XzAuthDO;
import com.mmc.iuav.user.entity.XzWithdrawalApplyDO;
import com.mmc.iuav.user.entity.wallet.PayWalletDO;
import com.mmc.iuav.user.entity.wallet.WithdrawalLogDO;
import com.mmc.iuav.user.enums.WithdrawalMethod;
import com.mmc.iuav.user.enums.XzEnums;
import com.mmc.iuav.user.model.dto.LoginSuccessDTO;
import com.mmc.iuav.user.model.dto.xzsz.UsableCashPoolingDTO;
import com.mmc.iuav.user.model.vo.XzAuthVO;
import com.mmc.iuav.user.model.vo.XzWithdrawalVO;
import com.mmc.iuav.user.service.xzsz.XzService;
import com.mmc.iuav.user.util.TDateUtil;
import com.mmc.iuav.user.xzsz.SingleSubmitResp;
import com.mmc.iuav.user.xzsz.WithdrawalResp;
import com.piggy.settlement.sdk.client.sign.PiggySignApiClient;
import com.piggy.settlement.sdk.client.v2.bankreceipt.PiggyBankReceiptClient;
import com.piggy.settlement.sdk.client.v2.basics.PiggyOpenBasicsClient;
import com.piggy.settlement.sdk.client.v2.singlewithdraw.PiggySingleWithdrawalApiV2Client;
import com.piggy.settlement.sdk.util.v2.PiggyOpenBasicsAesUtil;
import com.piggy.settlement.sdk.vo.sign.PiggySignResultVo;
import com.piggy.settlement.sdk.vo.sign.PiggySignVo;
import com.piggy.settlement.sdk.vo.v2.bankreceipt.PiggyBankReceiptVo;
import com.piggy.settlement.sdk.vo.v2.basics.PiggyBasicsVo;
import com.piggy.settlement.sdk.vo.v2.singlewithdraw.PiggySingleWithdrawV2Vo;
import com.piggy.settlement.sdk.vo.v2.singlewithdraw.PiggySingleWithdrawalQueryV2Vo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zj
 * @Date: 2023/8/21 9:52
 */
@Service
@Slf4j
public class XzServiceImpl implements XzService {
    @Autowired
    private UserSystemConstant userSystemConstant;

    @Autowired
    private XzDao xzDao;

    @Resource
    private PayWalletDao payWalletDao;

    @Autowired
    private RealNameAuthDao realNameAuthDao;

    @Override
    public ResultBody getTaxFundList() {
        PiggyOpenBasicsClient piggyOpenBasicsClient = PiggyOpenBasicsClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggyOpenBasicsClient.getTaxFundList(PiggyBasicsVo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .build());
        return ResultBody.success(jsonObject.get("data"));
    }

    @Override
    public ResultBody getCashPooling() {
        PiggyOpenBasicsClient piggyOpenBasicsClient = PiggyOpenBasicsClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggyOpenBasicsClient.getCashPooling(PiggyBasicsVo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .build());
        System.out.println(jsonObject.toString());
        return ResultBody.success(jsonObject.get("data"));
    }

    @Override
    public List<UsableCashPoolingDTO> getUsableCashPooling() {
        PiggyOpenBasicsClient piggyOpenBasicsClient = PiggyOpenBasicsClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggyOpenBasicsClient.getTaxFundCashPooling(PiggyBasicsVo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .taxFundID(userSystemConstant.getTaxFundId())
                .build());
        System.out.println(jsonObject.toString());
        List<UsableCashPoolingDTO> data = JSONArray.parseArray(jsonObject.get("data").toString(), UsableCashPoolingDTO.class);
        return data;
    }

    @Override
    public String getContractScope(XzAuthVO xzAuthVO) {
        PiggySignApiClient piggySignApiClient = PiggySignApiClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggySignApiClient.getSignStatus(PiggySignResultVo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .idCardNo(xzAuthVO.getIdCardNo())
                .userName(xzAuthVO.getUsername())
                .position(userSystemConstant.getXzPosition())
                .build());
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }

    @Override
    public String hasKeyByUrl(LoginSuccessDTO loginSuccessDTO) {
        // 获取实名认证信息
        RealNameAuthDO realNameAuthDO = realNameAuthDao.getRealNameAuthByUId(loginSuccessDTO.getUserAccountId());
        if (realNameAuthDO == null) {
            return "先完成实名认证再签署！";
        }
        XzAuthVO xzAuthVO = new XzAuthVO(realNameAuthDO.getUserName(), realNameAuthDO.getIdNumber(),
                loginSuccessDTO.getPhoneNum(), null, realNameAuthDO.getFrontIdImg(), realNameAuthDO.getBackIdImg());
        // 查询是否已电子签约
        String contractScope = this.getContractScope(xzAuthVO);
        com.alibaba.fastjson2.JSONObject jsonObject1 = com.alibaba.fastjson2.JSONObject.parseObject(contractScope);
        if (jsonObject1.get("data") != null) {
            // 添加认证签约结果
            JSONObject signedResult = this.getSignedResult(xzAuthVO);
            if (signedResult.get("msg").equals("success")) {
                // log.info("Signed result: {}", signedResult);
                List<JSONObject> jsonObjects = JSONArray.parseArray(signedResult.get("data").toString(), JSONObject.class);
                // log.info("jsonObjects : {}", com.alibaba.fastjson2.JSONObject.toJSONString(jsonObjects));
                XzAuthDO xzAuthDO = xzDao.getXzAuthByUserAccountId(loginSuccessDTO.getUserAccountId());
                if (xzAuthDO == null && !CollectionUtils.isEmpty(jsonObjects)) {
                    xzAuthDO = buildXzAuthDO(loginSuccessDTO, jsonObjects.get(0));
                    xzDao.addAuth(xzAuthDO);
                }
            }
            return "success";
        } else {
            Map<String, Integer> userInfo = new HashMap<String, Integer>();
            userInfo.put("userAccountId", loginSuccessDTO.getUserAccountId());
            PiggySignApiClient piggySignApiClient = PiggySignApiClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
            JSONObject jsonObject = piggySignApiClient.getSignUrl(PiggySignVo.builder()
                    .appKey(userSystemConstant.getXzAppKey())
                    .customParams(com.alibaba.fastjson2.JSONObject.toJSONString(userInfo))
                    .idCardNo(realNameAuthDO.getIdNumber())
                    .infoSource("1")
                    .jumpPage("https://www.signtest.cn/signSuccess")
                    .mobile(loginSuccessDTO.getPhoneNum())
                    .notifyUrl(userSystemConstant.getAuthNotify())
                    .position(userSystemConstant.getXzPosition())
                    .userName(realNameAuthDO.getUserName())
                    .idCardImageFront(realNameAuthDO.getFrontIdImg())
                    .idCardImageBack(realNameAuthDO.getBackIdImg())
                    .build());
            // TODO 发送模板消息
            return jsonObject.get("data").toString();
        }
    }

    private XzAuthDO buildXzAuthDO(LoginSuccessDTO loginSuccessDTO, JSONObject jsonObject) {
        XzAuthDO xzAuthDO = new XzAuthDO();
        xzAuthDO.setUserAccountId(loginSuccessDTO.getUserAccountId());
        xzAuthDO.setName(jsonObject.get("name").toString());
        xzAuthDO.setIdCardNo(jsonObject.get("idCardNo").toString());
        xzAuthDO.setMobile(jsonObject.get("mobile").toString());
        xzAuthDO.setBankAccount(jsonObject.get("bankAccount").toString());
        xzAuthDO.setSubsidiary_name(jsonObject.get("subsidiary_name").toString());
        xzAuthDO.setDocument_id(jsonObject.get("document_id").toString());
        xzAuthDO.setXzAuthStatus(1);
        return xzAuthDO;
    }

    @Transactional
    @Override
    public String xzAuthNotify(JSONObject notify) {
        log.info("xzAuthNotify获取到的推送结果：{}", notify.toString());
        // 认证成功，修改认证状态
        if (notify.get("code").toString().equals("0")) {
            XzAuthDO authDO = notify.get("data", XzAuthDO.class);
            Integer userAccountId = (Integer) com.alibaba.fastjson2.JSONObject.parseObject(authDO.getCustomParams()).get("userAccountId");
            if (userAccountId != null) {
                XzAuthDO xzAuthDO = xzDao.getXzAuthByUserAccountId(userAccountId);
                if (xzAuthDO == null) {
                    authDO.setUserAccountId(userAccountId);
                    authDO.setXzAuthStatus(1);
                    xzDao.addAuth(authDO);
                    return "success";
                }
            }
        }
        return null;
    }

    @Override
    public JSONObject getSignedResult(XzAuthVO xzAuthVO) {
        PiggySignApiClient piggySignApiClient = PiggySignApiClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggySignApiClient.getSignResult(PiggySignResultVo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .idCardNo(xzAuthVO.getIdCardNo())
                .userName(xzAuthVO.getUsername())
                .build());
        System.out.println(jsonObject.toString());
        return jsonObject;
    }

    @Override
    public String viewContract(String documentId) {
        PiggySignApiClient piggySignApiClient = PiggySignApiClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggySignApiClient.viewContract(documentId);
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }

    @Override
    public ResultBody clearTestFace(String name, String idCard) {
        String s = HttpsRequestUtil.httpsGet("https://uat.xzsz.ltd/contract/sign/clearTestPerson" + "name=" + name + "&idCard=" + idCard, null);
        return ResultBody.success(s);
    }

    @Override
    public SingleSubmitResp singleSubmit(XzWithdrawalVO xzWithdrawalVO) {
        log.info("singleSubmit param: {}", com.alibaba.fastjson2.JSONObject.toJSONString(xzWithdrawalVO));
        PiggySingleWithdrawalApiV2Client v2Client = PiggySingleWithdrawalApiV2Client.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = v2Client.singleSubmit(PiggySingleWithdrawV2Vo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .bizAESContent(PiggyOpenBasicsAesUtil.produceAesData(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzAes(), PiggySingleWithdrawV2Vo.SingleWithdrawV2Vo.builder()
                        .notifyUrl(userSystemConstant.getWithdrawNotify())
                        .taxFundId(userSystemConstant.getTaxFundId())
                        .month(xzWithdrawalVO.getMonth())
                        .outerTradeNo(xzWithdrawalVO.getOuterTradeNo())
                        .empNum(xzWithdrawalVO.getEmpNum())
                        .empName(xzWithdrawalVO.getEmpName())
                        .empPhone(xzWithdrawalVO.getEmpPhone())
                        .licenseType(xzWithdrawalVO.getLicenseType())
                        .licenseId(xzWithdrawalVO.getLicenseId())
                        .settleType(xzWithdrawalVO.getSettleType())
                        .payAccount(xzWithdrawalVO.getPayAccount())
                        .positionName(userSystemConstant.getXzPosition())
                        .payAmount(xzWithdrawalVO.getPayAmount())
                        .bankRemo(xzWithdrawalVO.getBankRemo())
                        .build()))
                .build());
        log.info("singleSubmit res: {}", com.alibaba.fastjson2.JSONObject.toJSONString(jsonObject));
        SingleSubmitResp singleSubmitResp = com.alibaba.fastjson2.JSONObject.parseObject(jsonObject.toString(), SingleSubmitResp.class);
        return singleSubmitResp;
    }

    @Override
    public SingleSubmitResp singleSubmitLimit(XzWithdrawalVO xzWithdrawalVO) {
        PiggySingleWithdrawalApiV2Client v2Client = PiggySingleWithdrawalApiV2Client.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = v2Client.singleSubmitLimit(PiggySingleWithdrawV2Vo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .bizAESContent(PiggyOpenBasicsAesUtil.produceAesData(userSystemConstant.getXzAppKey(), userSystemConstant.getXzAes(), PiggySingleWithdrawV2Vo.SingleWithdrawV2Vo.builder()
                        .notifyUrl(xzWithdrawalVO.getNotifyUrl())
                        .taxFundId(xzWithdrawalVO.getTaxFundId())
                        .month(xzWithdrawalVO.getMonth())
                        .outerTradeNo(xzWithdrawalVO.getOuterTradeNo())
                        .empNum(xzWithdrawalVO.getEmpNum())
                        .empName(xzWithdrawalVO.getEmpName())
                        .empPhone(xzWithdrawalVO.getEmpPhone())
                        .licenseType(xzWithdrawalVO.getLicenseType())
                        .licenseId(xzWithdrawalVO.getLicenseId())
                        .settleType(xzWithdrawalVO.getSettleType())
                        .payAccount(xzWithdrawalVO.getPayAccount())
                        .positionName(xzWithdrawalVO.getPositionName())
                        .payAmount(xzWithdrawalVO.getPayAmount())
                        .bankRemo(xzWithdrawalVO.getBankRemo())
                        .build()))
                .build());
        System.out.println(jsonObject.toString());
        SingleSubmitResp singleSubmitResp = com.alibaba.fastjson2.JSONObject.parseObject(jsonObject.toString(), SingleSubmitResp.class);
        return singleSubmitResp;
    }

    @Override
    public WithdrawalResp querySingleTrade(String outerTradeNo) {
        PiggySingleWithdrawalApiV2Client v2Client = PiggySingleWithdrawalApiV2Client.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = v2Client.querySingleTrade(PiggySingleWithdrawalQueryV2Vo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .outerTradeNo(outerTradeNo)
                .build());
        WithdrawalResp withdrawalResp = com.alibaba.fastjson2.JSONObject.parseObject(jsonObject.toString(), WithdrawalResp.class);
        return withdrawalResp;
    }

    @Override
    public ResultBody querySingleReceipt(String frontLogNo) {
        PiggyBankReceiptClient piggyBankReceiptClient = PiggyBankReceiptClient.getInstanse(userSystemConstant.getXzAppSecret(), userSystemConstant.getXzDomain());
        JSONObject jsonObject = piggyBankReceiptClient.getSingleReceipt(PiggyBankReceiptVo.builder()
                .appKey(userSystemConstant.getXzAppKey())
                .frontLogNo(frontLogNo)
                .build());
        System.out.println(jsonObject.toString());
        if (jsonObject.get("isSuccess").toString().equals("T")) {
            return ResultBody.success(jsonObject.get("data"));
        } else {
            return ResultBody.error(jsonObject.get("errorMessage").toString());
        }
    }

    @Override
    @Transactional
    public String xzWithdrawNotify(JSONObject notify) {
        log.info("xzWithdrawNotify获取到的推送结果：{}", notify.toString());
        if (XzEnums.T.getCode().equals(notify.get(XzEnums.is_success.getCode()).toString())) {
            String s = decrypt(com.alibaba.fastjson2.JSONObject.parseObject(notify.get("data").toString()).get("bizAESContent").toString());
            WithdrawalResp.Data data = com.alibaba.fastjson2.JSONObject.parseObject(s, WithdrawalResp.Data.class);
            log.info("提现回调解密数据内容：{}", com.alibaba.fastjson2.JSONObject.toJSONString(data));
            // 获取用户提现申请信息
            XzWithdrawalApplyDO withdrawCashApplyDetails = payWalletDao.getWithdrawalApplyByIdOrOuterTradeNo(null, data.getOuterTradeNo());
            // 获取用户钱包信息
            PayWalletDO wallet = payWalletDao.getPayWalletByUser(withdrawCashApplyDetails.getUserAccountId());
            if (XzEnums.submit_result.getCode().equals(data.getNotifyType())) {
                // 对上报的数据进行业务校验，例如：是否超限、是否有余额、是否有电签、参数是否准确等等前置校验。如果校验成功,订单进入待发队列等待发放
                log.info("deal submitResult");
                // 判断返回的状态时否是成功
                if (XzEnums.success.getCode().equals(data.getTradeStatus())) {
                    // 更新提现申请记录
                    XzWithdrawalApplyDO xzWithdrawalApplyDO = new XzWithdrawalApplyDO();
                    xzWithdrawalApplyDO.setOuterTradeNo(data.getOuterTradeNo());
                    xzWithdrawalApplyDO.setSubmitStatus(data.getTradeStatus());
                    xzWithdrawalApplyDO.setTradeResult(data.getTradeResult());
                    xzWithdrawalApplyDO.setTaxFundId(userSystemConstant.getTaxFundId());
                    payWalletDao.updateWithdrawalApply(xzWithdrawalApplyDO);
                } else {
                    // 更新提现申请记录
                    XzWithdrawalApplyDO xzWithdrawalApplyDO = new XzWithdrawalApplyDO();
                    xzWithdrawalApplyDO.setOuterTradeNo(data.getOuterTradeNo());
                    xzWithdrawalApplyDO.setSubmitStatus(data.getTradeStatus());
                    xzWithdrawalApplyDO.setTradeResult(data.getTradeResult());
                    xzWithdrawalApplyDO.setTradeStatus(data.getTradeStatus());
                    payWalletDao.updateWithdrawalApply(xzWithdrawalApplyDO);
                    // 提现失败回滚用户金额
                    callbackUserPayWallet(data, withdrawCashApplyDetails, wallet, 0);
                }
            } else if (XzEnums.trade_result.getCode().equals(data.getNotifyType())) {
                // 根据回调信息返回数据更新提现申请
                if (withdrawCashApplyDetails.getTradeStatus() != null && withdrawCashApplyDetails.getTradeStatus().equals(XzEnums.success.getCode())) {
                    return "success";
                }
                XzWithdrawalApplyDO xzWithdrawalApplyDO = new XzWithdrawalApplyDO();
                int updateCount;
                // 判断返回的是成功还是失败
                if (XzEnums.success.getCode().equals(data.getTradeStatus())) {
                    // 修改提现申请状态
                    xzWithdrawalApplyDO.setTradeStatus(XzEnums.success.getCode());
                    xzWithdrawalApplyDO.setTradeTime(data.getTradeTime());
                    xzWithdrawalApplyDO.setOuterTradeNo(data.getOuterTradeNo());
                    xzWithdrawalApplyDO.setFrontLogNo(data.getFrontLogNo());
                    xzWithdrawalApplyDO.setTradeResult(data.getTradeResult());
                    updateCount = payWalletDao.updateWithdrawalApply(xzWithdrawalApplyDO);
                    if (updateCount != 1) {
                        log.error("回调返回提现成功时，修改提现申请信息失败，信息是：{}", JSON.toJSONString(xzWithdrawalApplyDO));
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "error";
                    }
                    // 解冻冻结金，记录流水
                    callbackUserPayWallet(data, withdrawCashApplyDetails, wallet, 1);
                    return "success";
                } else if (XzEnums.handle.getCode().equals(data.getTradeStatus())) {
                    // 修改提现申请状态
                    xzWithdrawalApplyDO.setTradeStatus(XzEnums.handle.getCode());
                    xzWithdrawalApplyDO.setTradeTime(data.getTradeTime());
                    xzWithdrawalApplyDO.setOuterTradeNo(data.getOuterTradeNo());
                    xzWithdrawalApplyDO.setFrontLogNo(data.getFrontLogNo());
                    xzWithdrawalApplyDO.setTradeResult(data.getTradeResult());
                    updateCount = payWalletDao.updateWithdrawalApply(xzWithdrawalApplyDO);
                    if (updateCount != 1) {
                        log.error("回调返回提现交易中时，修改提现申请信息失败，信息是：{}", JSON.toJSONString(xzWithdrawalApplyDO));
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "error";
                    }
                } else {
                    // 修改提现申请状态
                    xzWithdrawalApplyDO.setTradeStatus(XzEnums.failure.getCode());
                    xzWithdrawalApplyDO.setErrorMessage(data.getTradeFailCode());
                    xzWithdrawalApplyDO.setTradeTime(data.getTradeTime());
                    xzWithdrawalApplyDO.setOuterTradeNo(data.getOuterTradeNo());
                    xzWithdrawalApplyDO.setTradeResult(data.getTradeResult());
                    updateCount = payWalletDao.updateWithdrawalApply(xzWithdrawalApplyDO);
                    if (updateCount != 1) {
                        log.error("回调返回提现交易中时，修改提现申请信息失败，信息是：{}", JSON.toJSONString(xzWithdrawalApplyDO));
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "error";
                    }
                    // 提现失败回滚用户金额
                    callbackUserPayWallet(data, withdrawCashApplyDetails, wallet, 0);
                }
            }
        } else {
            log.info("xzWithdrawNotify fail：{}", notify);
        }
        return "success";
    }

    /**
     * @param data                     回调返回的数据
     * @param withdrawCashApplyDetails 提现申请信息
     * @param wallet                   用户钱包信息
     * @param flag                     0：失败 1：成功
     */
    @Transactional(rollbackFor = Exception.class)
    public void callbackUserPayWallet(WithdrawalResp.Data data, XzWithdrawalApplyDO withdrawCashApplyDetails, PayWalletDO wallet, Integer flag) {
        String payNo = "T" + TDateUtil.getDateStr(new Date(), TDateUtil.TYPE) + withdrawCashApplyDetails.getUserAccountId() + CodeUtil.getRandomNum(4);
        // 记录流水记录
        WithdrawalLogDO withdrawalLogDO = new WithdrawalLogDO();
        withdrawalLogDO.setPayNo(payNo);
        withdrawalLogDO.setXzWithdrawalApplyId(withdrawCashApplyDetails.getId());
        withdrawalLogDO.setPayTime(new Date());
        withdrawalLogDO.setUserAccountId(withdrawCashApplyDetails.getUserAccountId());
        withdrawalLogDO.setSalaryPaid(data.getPayAmount());
        if (flag == 0) {
            withdrawalLogDO.setPayMethod(WithdrawalMethod.TXSB.getCode());
        } else {
            withdrawalLogDO.setPayMethod(WithdrawalMethod.TXCG.getCode());
        }
        withdrawalLogDO.setSalaryFreeze(BigDecimal.ZERO);
        payWalletDao.insertWithdrawalLog(withdrawalLogDO);
        // 修改钱包信息，钱包冻结金额
        PayWalletDO payWalletDO = new PayWalletDO();
        payWalletDO.setPid(wallet.getPid());
        payWalletDO.setUserAccountId(withdrawCashApplyDetails.getUserAccountId());
        if (flag == 0) {
            payWalletDO.setSalaryAmt(wallet.getSalaryAmt().add(data.getPayAmount()));
        } else {
            payWalletDO.setSalaryWdl(wallet.getSalaryWdl().add(data.getPayAmount()));
        }
        payWalletDO.setWdlFreeze(wallet.getWdlFreeze().subtract(data.getPayAmount()));
        int updatePayWalletCount = payWalletDao.updatePayWallet(payWalletDO);
        if (updatePayWalletCount != 1) {
            log.error("回调返回提现时，修改钱包信息失败，信息是：{}", JSON.toJSONString(payWalletDO));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    public String decrypt(String aesData) {
        try {
            byte[] raw = userSystemConstant.getXzAppSecret().getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(userSystemConstant.getXzAes().getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            Charset charset = Charset.forName("UTF-8");
            String tempStr = URLDecoder.decode(aesData, charset);
            byte[] encrypted1 = Base64.decode(tempStr);
            byte[] original = cipher.doFinal(encrypted1);
            String jsonParam = new String(original, "UTF-8");
            return jsonParam;
        } catch (Exception e) {
            System.out.println("AES解密异常" + e);
        }
        return "";
    }

}
