package com.ruoyi.ss.pay.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ServiceConstants;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.redis.RedisLock;
import com.ruoyi.common.enums.PayChannel;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.pay.tm.TmPayService;
import com.ruoyi.common.pay.tm.enums.RefundStatus;
import com.ruoyi.common.pay.tm.vo.RefundInfo;
import com.ruoyi.common.pay.wx.Payable;
import com.ruoyi.common.pay.wx.RefundAble;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.wx.vo.WeChatMiniAuthorizeVo;
import com.ruoyi.ss.channel.domain.ChannelQuery;
import com.ruoyi.ss.channel.domain.ChannelVO;
import com.ruoyi.ss.channel.service.IChannelService;
import com.ruoyi.ss.order.domain.Order;
import com.ruoyi.ss.order.domain.OrderBO;
import com.ruoyi.ss.order.domain.OrderVO;
import com.ruoyi.ss.order.service.IOrderService;
import com.ruoyi.ss.pay.service.IWxPayService;
import com.ruoyi.ss.payBill.domain.PayBill;
import com.ruoyi.ss.payBill.domain.PayBillVO;
import com.ruoyi.ss.payBill.service.PayBillConverter;
import com.ruoyi.ss.payBill.service.PayBillService;
import com.ruoyi.ss.refund.domain.Refund;
import com.ruoyi.ss.refund.service.IRefundService;
import com.ruoyi.ss.user.domain.UserVO;
import com.ruoyi.ss.user.service.IUserService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.app.AppServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.QueryByOutRefundNoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.constant.ServiceConstants.REFUND_STATUS_SUCCESS;

/**
 * 微信支付服务
 * @author qzz
 * 2024/3/11
 */
@Service
@Slf4j
public class WxPayService implements IWxPayService {

    @Autowired
    private IOrderService orderService;

    @Resource
    private IUserService asUserService;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private IChannelService channelService;

    @Resource
    private IRefundService etRefundService;

    @Resource
    private PayBillService payBillService;

    @Resource
    private PayBillConverter payBillConverter;

    private static final String CNY = "CNY";

    private static final String PREPAY_LOCK = "prepay:";

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Value("${ruoyi.isTest}")
    private boolean isTest;

    @Value("${ruoyi.privateKeyPath}")
    private String path;


    @Override
    public PrepayWithRequestPaymentResponse prepayWithRequestPayment(OrderBO order) {
        String billNo = order.getOrder().getOrderNo();
        ChannelVO channelVO = order.getChannel();

        try {
            // 创建支付单
            PayBill po = payBillConverter.toPo(order);
            payBillService.createPayBill(po);

            if (PayChannel.CT_WX.equalsCode(channelVO.getCode())) {
                log.info("----------微信官方支付-------------");
                return getPrepayWithRequestPaymentResponse(order.getOrder(), order.getUser(), channelVO, po.getPayNo(), po.getDescription());
            } else if (PayChannel.TM_WX.equalsCode(channelVO.getCode())) {
                log.info("----------太米支付-------------");
                return getPrepayWithRequestPaymentResponse(order, po, channelVO);
            } else {
                throw new ServiceException("支付渠道【" + channelVO.getCode() + "】暂不支持");
            }
        } finally {
            redisLock.unlock(PREPAY_LOCK + billNo);
        }
    }

    private static PrepayWithRequestPaymentResponse getPrepayWithRequestPaymentResponse(OrderBO order, PayBill po, ChannelVO channelVO) {
        Payable payable = new Payable();
        payable.setAmount(order.getOrder().getPayFee().multiply(new BigDecimal(100)).longValue());
        payable.setOutTradeNo(po.getPayNo());
        payable.setDescription(po.getDescription());
        payable.setOpenid(order.getUser().getWxopenid());
        payable.setAppid(channelVO.getAppid());
        return TmPayService.pay(channelVO, payable);
    }

    private String getOpenId(String jsCode,String appId,String secret) {
        //根据jsCode换取openid
        String url = StrUtil.format("https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code", appId, secret, jsCode);
        String s = HttpUtils.sendGet(url);
        WeChatMiniAuthorizeVo authorizeVo = JSONObject.parseObject(s, WeChatMiniAuthorizeVo.class);
        if (StringUtils.isEmpty(s) ) {
            throw new ServiceException("微信平台接口异常，没任何数据返回！");
        }
        return authorizeVo.getOpenid();
    }

    private PrepayWithRequestPaymentResponse getPrepayWithRequestPaymentResponse(Order order, User user, ChannelVO channelVO, String outTradeNo, String description) {
        PrepayRequest request = new PrepayRequest();
        request.setAmount(getAmount(order.getPayFee()));
        request.setOutTradeNo(outTradeNo);
        request.setAppid(channelVO.getAppid());
        request.setMchid(channelVO.getMerchantId());
        request.setDescription(description);
        log.info("支付渠道------{}", JSON.toJSON(channelVO));
        request.setNotifyUrl(channelVO.getNotifyUrl());
        request.setPayer(getPayer(user.getWxopenid()));
        JsapiServiceExtension jsapiServiceExtension = getJsapiServiceExtension(channelVO);
        return jsapiServiceExtension.prepayWithRequestPayment(request);
    }



    private JsapiServiceExtension getJsapiServiceExtension(ChannelVO channelVO) {
        String privateKeyPath = channelVO.getPrivateKeyPath();
        log.info("是否是测试环境------{}", isTest);
        if(isTest){
            privateKeyPath = path;
        }
        // 初始化商户配置
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(channelVO.getMerchantId())
                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(channelVO.getMerchantSerialNumber())
                .apiV3Key(channelVO.getApiV3Key())
                .build();
        // 初始化服务
        return new JsapiServiceExtension
                .Builder()
                .config(config)
                .signType("RSA") // 不填默认为RSA
                .build();
    }

    private AppServiceExtension getAppServiceExtension(ChannelVO channelVO) {
        // 初始化商户配置
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(channelVO.getMerchantId())
                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                .privateKeyFromPath(channelVO.getPrivateKeyPath())
                .merchantSerialNumber(channelVO.getMerchantSerialNumber())
                .apiV3Key(channelVO.getApiV3Key())
                .build();
        // 初始化服务
        return new AppServiceExtension
                .Builder()
                .config(config)
                .build();
    }


//    /**
//     * 根据订单号查询订单
//     * @param outTradeNo 商户订单号
//     * @return
//     */
//    @Override
//    public PaymentResult queryOrderByOutTradeNo(String outTradeNo) {
//        EtOrder order = orderService.selectEtOrderByOutTradeNo(outTradeNo);
//        ChannelVO channelVO = channelService.selectSmChannelByChannelId(order.getPayChannel());
//        PaymentResult paymentResult1 = new PaymentResult();
//        if(PayChannel.CT_WX.equalsCode(channelVO.getCode()) || PayChannel.YS_WX.equalsCode(channelVO.getCode())){
//            QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
//            request.setMchid(channelVO.getMerchantId());
//            request.setOutTradeNo(outTradeNo);
//            JsapiService jsapiService = getJsapiService(channelVO);
//            Transaction transaction = jsapiService.queryOrderByOutTradeNo(request);
//            log.info("微信查询订单信息outTradeNo={}-----【{}】",outTradeNo,JSON.toJSON(transaction));
//            paymentResult1.setTransaction(transaction);
//            return paymentResult1;
//        }else if(PayChannel.TL_WX.equalsCode(channelVO.getCode())){
//            Map<String, String> result = sybPayService.queryOrderByOutTradeNo(order.getOutTradeNo());
//            if(SybTrxStatus.isSuccess(result.get("trxstatus"))) {
//                paymentResult1.setResult(result);
//                return paymentResult1;
//            }
//            return null;
//        }else{
//            throw new ServiceException("支付渠道【"+channelVO.getCode()+"】暂不支持");
//        }
//    }

    /**
     * 关闭订单
     * @param outTradeNo 商户订单号
     * @return
     */
    @Override
    public boolean closeOrder(String outTradeNo,ChannelVO channelVO) {
        JsapiServiceExtension jsapiServiceExtension = getJsapiServiceExtension(channelVO);
        // 关闭订单
        CloseOrderRequest closeOrderRequest = new CloseOrderRequest();
        closeOrderRequest.setMchid(channelVO.getMerchantId());
        closeOrderRequest.setOutTradeNo(outTradeNo);
        jsapiServiceExtension.closeOrder(closeOrderRequest);
        return true;
    }

//    /**
//     * 根据订单号查询订单
//     * @param orderNo 商户订单号
//     * @return
//     */
//    @Override
//    public Boolean queryResultByOrderNo(String orderNo) {
//        EtOrder order = orderService.selectEtOrderByOrderNo(orderNo);
//        ChannelVO channelVO = channelService.selectSmChannelByChannelId(order.getPayChannel());
//        if(PayChannel.CT_WX.equalsCode(channelVO.getCode()) || PayChannel.YS_WX.equalsCode(channelVO.getCode())){
//            QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
//            request.setMchid(channelVO.getMerchantId());
//            if(StrUtil.isBlank(order.getOutTradeNo())){
//                return false;
//            }
//            request.setOutTradeNo(order.getOutTradeNo());
//            JsapiService jsapiService = getJsapiService(channelVO);
//            Transaction transaction = jsapiService.queryOrderByOutTradeNo(request);
//            // 订单未支付并且微信支付结果是成功的情况下，更新订单状态和用户余额
//            if(transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)){
//                if(order.getPaid().equals(ServiceConstants.ORDER_PAY_STATUS_NON_PAYMENT)){
//                    order.setPaid("1");
//                    order.setPayTime(DateUtils.parseTime(transaction.getSuccessTime()));
//                    order.setPayType(ServiceConstants.PAY_TYPE_WX);
//                    log.info("【主动查询】押金支付");
//                    order.setStatus(ServiceConstants.ORDER_STATUS_ORDER_END);
//                    if(ServiceConstants.ORDER_TYPE_RIDING.equals(order.getType())){
//                        order.setMark("主动查询-骑行支付");
//                    }else{
//                        order.setMark("押金支付");
//                        // 更新用户余额
//                        AsUser asUser = asUserMapper.selectUserById(order.getUserId());
//                        asUser.setBalance(order.getTotalFee());
//                        int updateUser = asUserMapper.updateUser(asUser);
//                        if(updateUser==0){
//                            log.error("【微信支付回调】更新用户押金失败");
//                            throw new ServiceException("【微信支付回调】更新用户押金失败");
//                        }
//                    }
//                    int updateEtOrder = orderService.updateEtOrder(order);
//                    if(updateEtOrder==0){
//                        log.error("【微信支付回调】更新订单信息失败");
//                        throw new ServiceException("【微信支付回调】更新订单信息失败");
//                    }
//                }
//                return true;
//            }
//        }else if(PayChannel.TL_WX.equalsCode(channelVO.getCode())){
//            Map<String, String> result = sybPayService.queryOrderByOutTradeNo(order.getOutTradeNo());
//            if(SybTrxStatus.isSuccess(result.get("trxstatus"))) {
//                return true;
//            }
//        }else{
//            throw new ServiceException("支付渠道【"+channelVO.getCode()+"】暂不支持");
//        }
//        return false;
//    }

    private JsapiService getJsapiService(ChannelVO channelVO) {
        // 初始化商户配置
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(channelVO.getMerchantId())
                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                .privateKeyFromPath(channelVO.getPrivateKeyPath())
                .merchantSerialNumber(channelVO.getMerchantSerialNumber())
                .apiV3Key(channelVO.getApiV3Key())
                .build();
        // 初始化服务
        return new JsapiService.Builder().config(config).build();
    }

    /**
     * 退款
     * @param etOrder 原订单对象
     *              paid、payChannel、payFee
     * @param reason 退款原因
     * @param amount 退款金额
     * @param outRefundNo 退款订单号
     * @param payNo 支付单号
     */
    @Override
    public void refund(OrderVO etOrder, String reason, BigDecimal amount, String outRefundNo, String payNo) {
        if(!etOrder.getPaid().equals(ServiceConstants.ORDER_PAY_STATUS_PAID)) throw new ServiceException("订单状态异常");
        ChannelVO channelVO = channelService.selectChannelByChannelId(etOrder.getPayChannel());
        if (channelVO == null) {
            throw new ServiceException("支付渠道不存在: " + etOrder.getPayChannel());
        }

        if(PayChannel.CT_WX.equalsCode(channelVO.getCode())){
            log.info("----------{}-------------","微信官方退款");
            CreateRequest request = new CreateRequest();
            // todo 用支付表
            request.setOutTradeNo(payNo);
            request.setOutRefundNo(outRefundNo);
            request.setReason(reason);
            request.setAmount(getAmountReq(etOrder.getPayFee(),amount));
            request.setNotifyUrl(channelVO.getRefundNotifyUrl());
            log.info("【退款】请求微信参数:【{}】",JSON.toJSONString(request));
            RefundService refundService = getRefundService(channelVO);
            try {
                com.wechat.pay.java.service.refund.model.Refund refund = refundService.create(request);
                log.info("【退款】微信返回结果:【{}】",JSON.toJSONString(refund));
            }catch (com.wechat.pay.java.core.exception.ServiceException e){
                log.error("【微信退款】退款失败:{}",e.getErrorMessage());
                throw e;
            }
        }else if(PayChannel.TM_WX.equalsCode(channelVO.getCode())){
            log.info("----------{}-------------","太米微信退款");
            RefundAble refundAble = new RefundAble();
            refundAble.setOutTradeNo(payNo);
            refundAble.setOutRefundNo(outRefundNo);
            refundAble.setReason(reason);
            refundAble.setAmount(amount.multiply(new BigDecimal(100)).longValue());
            log.info("【退款】请求太米参数:【{}】",JSON.toJSONString(refundAble));
            RefundInfo refund = TmPayService.refund(channelVO, refundAble);
            ServiceUtil.assertion(!RefundStatus.isSuccess(refund.getRefundStatus().getCode()), "发起退款失败:" + refund.getRefundMessage());
            scheduledExecutorService.schedule(() -> {
                handleRefundSuccess(outRefundNo);
            }, 0, TimeUnit.SECONDS);
        }else{
            throw new ServiceException("支付渠道【"+channelVO.getCode()+"】暂不支持");
        }
    }

    /**
     * 退款成功后的处理
     * @param refundNo 退款订单号
     */
    private void handleRefundSuccess(String refundNo) {
        Refund rlRefund = new Refund();
        rlRefund.setRefundNo(refundNo);
        rlRefund.setStatus(REFUND_STATUS_SUCCESS);
//        rlRefund.setRefundResult(Constants.SUCCESS2);
        int i = etRefundService.updateEtRefundByRefundNo(rlRefund);
        if(i==0){
            log.error("【通联退款】更新退款单失败");
            throw new ServiceException("【通联退款】更新退款单失败");
        }
    }

    private RefundService getRefundService(ChannelVO channelVO){
        String privateKeyPath = channelVO.getPrivateKeyPath();
        log.info("是否是测试环境------{}", isTest);
        if(isTest){
            privateKeyPath = path;
        }
        // 初始化商户配置
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(channelVO.getMerchantId())
                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(channelVO.getMerchantSerialNumber())
                .apiV3Key(channelVO.getApiV3Key())
                .build();
        // 初始化服务
        return new RefundService.Builder().config(config).build();
    }

//    /**
//     * 发起商家转账
//     * @param sysDept 运营商对象
//     * @param batchNo 批次号
//     * @param batchName 批次名称
//     * @param batchRemark 转账说明
//     * @param totalAmount 转账总金额
//     * @param totalNum 转账总笔数
//     * @param transferDetailInputs 转账明细列表
//     */
//    @Override
//    public InitiateBatchTransferResponse transfer(SysDept sysDept,String batchNo,String batchName,String batchRemark,BigDecimal totalAmount,Integer totalNum,List<TransferDetailInput> transferDetailInputs) {
////        SysDept sysDept = getDeptObjByAreaId(areaId);
//        InitiateBatchTransferRequest request = new InitiateBatchTransferRequest();
//        request.setAppid(sysDept.getAppid());
//        request.setOutBatchNo(batchNo);
//        request.setBatchName(batchName);
//        request.setBatchRemark(batchRemark);
//        request.setTotalAmount(totalAmount.multiply(new BigDecimal(100)).longValue());
//        request.setTotalNum(totalNum);
//        request.setTransferDetailList(transferDetailInputs);
//        log.info("【发起商家转账】请求微信参数:【{}】",JSON.toJSONString(request));
////        TransferBatchService transferService = getTransferService(sysDept);
////        InitiateBatchTransferResponse initiateBatchTransferResponse = transferService.initiateBatchTransfer(request);
////        log.info("【发起商家转账】微信返回结果:【{}】",JSON.toJSONString(initiateBatchTransferResponse));
////        return initiateBatchTransferResponse;
//        return null;
//    }

//    private TransferBatchService getTransferService(SysDept sysDept){
//        // 初始化商户配置
//        Config config = new RSAAutoCertificateConfig.Builder()
//                .merchantId(sysDept.getMerchantId())
//                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
//                .privateKeyFromPath(sysDept.getPrivateKeyPath())
//                .merchantSerialNumber(sysDept.getMerchantSerialNumber())
//                .apiV3Key(sysDept.getApiV3Key())
//                .build();
//        // 初始化服务
//        return new TransferBatchService.Builder().config(config).build();
//    }


//    /**
//     * 根据运营区id获取运营商对象
//     * @param areaId
//     * @return
//     */
//    @Override
//    public SysDept getDeptObjByAreaId(Long areaId) {
//        SysDept sysDept;
//        List<EtAreaDept> areaId1 = etAreaDeptMapper.selectList(new QueryWrapper<EtAreaDept>().eq("area_id", areaId));
//        if (ObjectUtil.isNotEmpty(areaId1) && areaId1.size() > 0){
//            EtAreaDept etAreaDept = areaId1.get(0);
//             sysDept = deptService.selectDeptById(etAreaDept.getDeptId());
//            log.info("获取到运营商对象：【{}】",JSON.toJSON(sysDept));
//        }else{
//            log.info("区域：【{}】没有绑定运营商",areaId);
//            return null;
//        }
//        return sysDept;
//    }

    @Override
    public com.wechat.pay.java.service.refund.model.Refund queryByOutRefundNo(String outRefundNo) {
        Refund refund = etRefundService.selectEtRefundByRefundNo(outRefundNo);
        if (refund == null) {
            throw new ServiceException("没有找到退款记录: " + outRefundNo);
        }
        PayBillVO payBillVO = payBillService.selectPayBillByPayId(refund.getPayId());
        ServiceUtil.assertion(ObjectUtil.isNull(payBillVO), "支付订单不存在");
        ChannelVO channelVO = channelService.selectChannelByChannelId(payBillVO.getChannelId());
        ServiceUtil.assertion(ObjectUtil.isNull(channelVO), "渠道不存在");
        QueryByOutRefundNoRequest request = new QueryByOutRefundNoRequest();
        request.setOutRefundNo(outRefundNo);
        RefundService refundService = getRefundService(channelVO);
        return refundService.queryByOutRefundNo(request);
    }

//    /** 请求分账API */
//    public OrdersEntity createOrder(SysDept sysDept,String transactionId,List<CreateOrderReceiver> receivers) {
//        CreateOrderRequest request = new CreateOrderRequest();
//        request.setAppid(sysDept.getAppid());
//        request.setTransactionId(transactionId);// 微信订单号
//        request.setOutOrderNo(IdUtils.getOrderNo("fz"));// 商户系统内部分账单号
//        request.setReceivers(receivers);
//        request.setUnfreezeUnsplit(true);
//        ProfitsharingService profitsharingService = getProfitsharingService(sysDept);
//        return profitsharingService.createOrder(request);
//    }
//
//    /** 添加分账接收方 */
//    @Override
//    public AddReceiverResponse addReceiver(String wxopenid,Long deptId,String type) {
//        SysDept sysDept = deptService.selectDeptById(deptId);
//        AddReceiverRequest request = new AddReceiverRequest();
//        request.setAppid(sysDept.getAppid());
//        if(type.equals(ServiceConstants.PROFITSHARING_TYPE_PLATFORM)){
//            request.setType(ReceiverType.MERCHANT_ID);
//        }else{
//            request.setType(ReceiverType.PERSONAL_OPENID);
//        }
//        request.setAccount(wxopenid);
//        request.setRelationType(ReceiverRelationType.PARTNER);
//        ProfitsharingService profitsharingService = getProfitsharingService(sysDept);
//        return profitsharingService.addReceiver(request);
//    }

//    /** 删除分账接收方 */
//    public DeleteReceiverResponse deleteReceiver(String wxopenid,Long deptId,String type) {
//        SysDept sysDept = deptService.selectDeptById(deptId);
//        DeleteReceiverRequest request = new DeleteReceiverRequest();
//        request.setAppid(sysDept.getAppid());
//        if(type.equals(ServiceConstants.PROFITSHARING_TYPE_PLATFORM)){
//            request.setType(ReceiverType.MERCHANT_ID);
//        }else{
//            request.setType(ReceiverType.PERSONAL_OPENID);
//        }
//        request.setAccount(wxopenid);
//        ProfitsharingService profitsharingService = getProfitsharingService(sysDept);
//        return profitsharingService.deleteReceiver(request);
//    }

//    private ProfitsharingService getProfitsharingService(SysDept sysDept) {
//        Config config = new RSAAutoCertificateConfig.Builder()
//                        .merchantId(sysDept.getMerchantId())
//                        // 使用 com.wechat.pay.java.core.util中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
//                        .privateKeyFromPath(sysDept.getPrivateKeyPath())
//                        .merchantSerialNumber(sysDept.getMerchantSerialNumber())
//                        .apiV3Key(sysDept.getApiV3Key())
//                        .build();
//        // 初始化服务
//        return new ProfitsharingService.Builder().config(config).build();
//    }


//    /**
//     * 验签并解析
//     * @param request 请求
//     * @param body 请求体
//     * @param clazz 返回值类型
//     */
//    private <T> T checkAndParse(HttpServletRequest request, String body, Class<T> clazz) {
//        // 构造 RequestParam
//        RequestParam requestParam = new RequestParam.Builder()
//                .serialNumber(request.getHeader("Wechatpay-Serial"))
//                .nonce(request.getHeader("Wechatpay-Nonce"))
//                .signature(request.getHeader("Wechatpay-Signature"))
//                .timestamp(request.getHeader("Wechatpay-Timestamp"))
//                .body(body)
//                .build();
//        // 验签
//        return notificationParser.parse(requestParam, clazz);
//    }

    private Payer getPayer(String openId) {
        Payer payer = new Payer();
        payer.setOpenid(openId);
        return payer;
    }

    private Amount getAmount(BigDecimal money) {
        Amount amount = new Amount();
        amount.setTotal(money.multiply(new BigDecimal(100)).intValue());
        amount.setCurrency(CNY);
        return amount;
    }

    private AmountReq getAmountReq(BigDecimal total,BigDecimal rerundAmount) {
        AmountReq amount = new AmountReq();
        amount.setTotal(total.multiply(new BigDecimal(100)).longValue());
        amount.setRefund(rerundAmount.multiply(new BigDecimal(100)).longValue());
        amount.setCurrency(CNY);
        return amount;
    }


}
