package com.reactlibrary.pay;

import android.Manifest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import com.alipay.sdk.app.PayTask;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import javax.annotation.Nonnull;

import androidx.annotation.NonNull;

public class PayManager extends ReactContextBaseJavaModule {

    private final ReactApplicationContext reactContext;

    private Handler mHandler;

    public static PayManager module;

    private Promise wxPayPromise;

    private IWXAPI wxApi;

    @NonNull
    @Override
    public String getName() {
        return "PayManager";
    }

    public PayManager(@Nonnull ReactApplicationContext context) {
        super(context);
        reactContext = context;
        PayManager.module = this;
    }


    //  注册微信key
    @ReactMethod
    public void wechatRegister(final String appKey) {

        final IWXAPI wxApi = WXAPIFactory.createWXAPI(this.reactContext, appKey, true);

        // 将该app注册到微信
        wxApi.registerApp(appKey);

        this.wxApi = wxApi;

    }


    //  微信支付
    @ReactMethod
    public void wechatPay(ReadableMap data, Promise promise) {
        if (wxApi == null) {
            String str = "请先注册微信ID";
            promise.reject(str, str);
            return;
        }

        if (!wxApi.isWXAppInstalled()) {
            promise.reject("未安装微信", "未安装微信");
            return;
        }

        this.wxPayPromise = promise;
        String appid = data.getString("appid");

        PayReq request = new PayReq();
        request.appId = appid;//子商户appid
        request.partnerId = data.getString("partnerid");
        request.prepayId = data.getString("prepayid");
        request.packageValue = data.getString("package");
        request.nonceStr = data.getString("noncestr");
        request.timeStamp = data.getString("timestamp");
        request.sign = data.getString("sign");
        wxApi.sendReq(request);
    }

    /*微信支付结果 回调*/
    public void wxPayResuly(BaseResp resp) {

        if (this.wxPayPromise == null) {
            return;
        }

        int errCode = resp.errCode;

        if (errCode == 0) {
            this.wxPayPromise.resolve("支付成功");
        } else {
            String error = errCode == -1 ? "支付错误" : "用户取消支付";
            this.wxPayPromise.reject(error, error);
        }
    }


    //  支付宝支付
    @ReactMethod
    public void aliPay(final ReadableMap data, final Promise promise) {

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                Map<String, String> result = (Map<String, String>) msg.obj;
                String resultStatus = result.get("resultStatus");

                if (resultStatus == "9000") {
                    promise.resolve(result.get("result"));
                } else {
                    promise.reject("支付失败", result.get("result"));
                }
            }

            ;
        };


        Runnable payRunnable = new Runnable() {
            String payInfo = data.getString("payInfo");

            Activity activity = getCurrentActivity();

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(payInfo, true);

                Message msg = new Message();
                msg.what = 12;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


}
