package com.tjzhxx.union.weixinapi;

import android.content.Context;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tjzhxx.union.entity.request.WxPayReq;

import java.util.Random;

/**
 * 描述:
 * @author yanghuaxiong
 * @create 2021/9/11 8:51 PM
 * 
 */
public class WxPay {
    public static OnPayResultListener onPayResultListener;
    private IWXAPI api;
    PayReq req;

    private Context context;

    public WxPay(Context context) {
        this.context = context;
    }

    public void pay(WxPayReq wxPayReq) {
        String appId = wxPayReq.getAppid();
        api = WXAPIFactory.createWXAPI(context, appId);
        req = new PayReq();
        req.appId = appId;
        req.partnerId = wxPayReq.getPartnerid();
        req.prepayId = wxPayReq.getPrepayid();
        req.packageValue = wxPayReq.getPackageX();
        req.nonceStr = wxPayReq.getNoncestr();
        req.timeStamp = wxPayReq.getTimestamp();
        req.sign = wxPayReq.getSign();
        api.registerApp(appId);
        api.sendReq(req);

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private String genAppSign() {
        StringBuilder sb = new StringBuilder();
        sb.append("appid=" + req.appId);
        sb.append("&noncestr=" + req.nonceStr);
        sb.append("&package=" + req.packageValue);
        sb.append("&partnerid=" + req.partnerId);
        sb.append("&prepayid=" + req.prepayId);
        sb.append("&timestamp=" + req.timeStamp);
        sb.append("&key=e8b1ae8576eef64f09ebb9c9a6964cae");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    /**
     * 支付返回结果监听
     */
    public interface OnPayResultListener {
        void onSuccess();

        void onError();
    }

    public void setOnPayResultListener(OnPayResultListener onPayResultListener) {
        this.onPayResultListener = onPayResultListener;
    }
}