package com.vsu.fcounter.wxfacepay;

import android.os.RemoteException;
import android.widget.Toast;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.tencent.wxpayface.IWxPayfaceCallback;
import com.tencent.wxpayface.WxPayFace;
import com.tencent.wxpayface.WxfacePayCommonCode;

import java.util.HashMap;
import java.util.Map;

import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;

class WxFacepayModule extends ReactContextBaseJavaModule {

    private ReactContext reactContext;
    private static final String RETURN_CODE = "return_code";
    private static final String RETURN_MSG = "return_msg";

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

    WxFacepayModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }

    @ReactMethod
    private void init(final Promise promise) {
        try {
            WxPayFace.getInstance().initWxpayface(reactContext, new IWxPayfaceCallback() {
                @Override
                public void response(Map info) throws RemoteException {
                    if (!isSuccessInfo(info)) {
                        promise.resolve(false);
                        return;
                    }
                    promise.resolve(true);
                }
            });
        } catch (Exception e) {
            promise.resolve(false);
        }
    }

    @ReactMethod
    private void initOptions(ReadableMap params, final Promise promise) {
        try {
            WxPayFace.getInstance().initWxpayface(reactContext, params.toHashMap(), new IWxPayfaceCallback() {
                @Override
                public void response(Map info) throws RemoteException {
                    if (!isSuccessInfo(info)) {
                        promise.resolve(false);
                        return;
                    }
                    promise.resolve(true);
                }
            });
        } catch (Exception e) {
            promise.resolve(false);
        }
    }

    @ReactMethod
    private void rawdata(final Promise promise) {
        WxPayFace.getInstance().getWxpayfaceRawdata(new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (!isSuccessInfo(info)) {
                    promise.resolve(false);
                    return;
                }
                String rawdata = info.get("rawdata").toString();
                promise.resolve(rawdata);
            }
        });
    }

    @ReactMethod
    private void facepay(ReadableMap params, final Promise promise) {
        HashMap data = params.toHashMap();
        WxPayFace.getInstance().getWxpayfaceCode(data, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (!isSuccessInfo(info)) {
                    promise.resolve(false);
                    return;
                }
                WritableMap res = Arguments.createMap();
                res.putString(RETURN_CODE, info.get(RETURN_CODE).toString());
                res.putString(RETURN_MSG, info.get(RETURN_MSG).toString());
//                res.putString("err_code", info.get("err_code").toString());
                res.putString("face_code", info.get("face_code").toString());
                res.putString("openid", info.get("openid").toString());
                res.putString("sub_openid", info.get("sub_openid").toString());
//                res.putString("telephone_used", info.get("telephone_used").toString());
//                res.putString("underage_state", info.get("underage_state").toString());
                promise.resolve(res);
            }
        });
    }

    @ReactMethod
    private void faceinfo(ReadableMap params, final Promise promise) {
        HashMap data = params.toHashMap();
        WxPayFace.getInstance().getWxpayfaceUserInfo(data, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (!isSuccessInfo(info)) {
                    promise.resolve(false);
                    return;
                }
                WritableMap res = Arguments.createMap();
                res.putString(RETURN_CODE, info.get(RETURN_CODE).toString());
                res.putString(RETURN_MSG, info.get(RETURN_MSG).toString());
                Object err_code = info.get("err_code");
                Object openid = info.get("openid");
                Object sub_openid = info.get("sub_openid");
                Object nickname = info.get("nickname");
                Object token = info.get("token");
                Object unionid_code = info.get("unionid_code");
                Object unionid_msg = info.get("unionid_msg");
                if (err_code != null) res.putString("err_code", err_code.toString());
                if (openid != null) res.putString("openid", openid.toString());
                if (sub_openid != null) res.putString("sub_openid", sub_openid.toString());
                if (nickname != null) res.putString("nickname", nickname.toString());
                if (token != null) res.putString("token", token.toString());
                if (unionid_code != null) res.putString("unionid_code", unionid_code.toString());
                if (unionid_msg != null) res.putString("unionid_msg", unionid_msg.toString());
                promise.resolve(res);
            }
        });
    }

    @ReactMethod
    private void getUserPayScoreStatus(ReadableMap params, final Promise promise) {
        HashMap data = params.toHashMap();
        WxPayFace.getInstance().getUserPayScoreStatus(data, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (!isSuccessInfo(info)) {
                    promise.resolve(false);
                    return;
                }
                WritableMap res = Arguments.createMap();
                res.putString(RETURN_CODE, info.get(RETURN_CODE).toString());
                res.putString(RETURN_MSG, info.get(RETURN_MSG).toString());
                res.putString("openid", info.get("openid").toString());
//                res.putString("sub_openid", info.get("sub_openid").toString());
                res.putString("face_sid", info.get("face_sid").toString());
                promise.resolve(res);
            }
        });
    }

    @ReactMethod
    private void update(ReadableMap params, final Promise promise) {
        HashMap data = params.toHashMap();
        WxPayFace.getInstance().updateWxpayfacePayResult(data, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (!isSuccessInfo(info)) {
                    promise.resolve(false);
                    return;
                }
                WritableMap res = Arguments.createMap();
                res.putString(RETURN_CODE, info.get(RETURN_CODE).toString());
                res.putString(RETURN_MSG, info.get(RETURN_MSG).toString());
//                res.putString("err_code", info.get("err_code").toString());
                promise.resolve(res);
            }
        });
    }

    @ReactMethod
    private void stop(ReadableMap params, final Promise promise) {
        HashMap data = params.toHashMap();
        WxPayFace.getInstance().stopWxpayface(data, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (!isSuccessInfo(info)) {
                    promise.resolve(false);
                    return;
                }
                WritableMap res = Arguments.createMap();
                res.putString(RETURN_CODE, info.get(RETURN_CODE).toString());
                res.putString(RETURN_MSG, info.get(RETURN_MSG).toString());
//                res.putString("err_code", info.get("err_code").toString());
                promise.resolve(res);
            }
        });
    }

    @ReactMethod
    private void release(Promise promise) {
        WxPayFace.getInstance().releaseWxpayface(reactContext);
        promise.resolve(true);
    }

    private boolean isSuccessInfo(Map info) {
        if (info == null) {
            showToast("调用返回为空, 请查看日志");
            new RuntimeException("调用返回为空").printStackTrace();
            return false;
        }
        String code = (String)info.get(RETURN_CODE);
        String msg = (String)info.get(RETURN_MSG);
        if (code == null || !code.equals(WxfacePayCommonCode.VAL_RSP_PARAMS_SUCCESS)) {
            showToast("失败：" + code + "," + msg);
            new RuntimeException("调用返回非成功信息: " + msg).printStackTrace();
            return false;
        }
        return true;
    }

    private void showToast(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(reactContext.getApplicationContext(), text, Toast.LENGTH_LONG).show();
            }
        });
    }


}
