package com.cooleshow.student.ui.mine;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.student.R;
import com.cooleshow.student.bean.PayTestBean;
import com.cooleshow.student.bean.alipay.AuthResult;
import com.cooleshow.student.bean.alipay.PayResult;
import com.cooleshow.student.bean.weixinpay.WeixinPayInfo;
import com.cooleshow.student.contract.PayTestContract;
import com.cooleshow.student.databinding.ActivityPayTestBinding;
import com.cooleshow.student.presenter.mine.PayTestPresenter;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/25 13:46
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_PAY_TEST)
public class PayTestActivity extends BaseMVPActivity<ActivityPayTestBinding, PayTestPresenter> implements PayTestContract.PayTestView, View.OnClickListener {
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private IWXAPI api;

    @Override
    public void onClick(View view) {
        String orderNo = viewBinding.etId.getText().toString().trim();
        switch (view.getId()) {
            case R.id.tv_weixin:
                if (TextUtils.isEmpty(orderNo)) {
                    ToastUtil.getInstance().showShort("输入订单号");
                    break;
                }
                doWeixinPay(orderNo);


                break;
            case R.id.tv_alipay:
                if (TextUtils.isEmpty(orderNo)) {
                    ToastUtil.getInstance().showShort("输入订单号");
                    break;
                }
                doAliPay(orderNo);
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
        //沙箱环境支付
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp("wx97408cd22c879ff7");
    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "测试支付");
        viewBinding.tvWeixin.setOnClickListener(this);
        viewBinding.tvAlipay.setOnClickListener(this);
    }

    @Override
    protected ActivityPayTestBinding getLayoutView() {
        return ActivityPayTestBinding.inflate(getLayoutInflater());
    }

    @Override
    protected PayTestPresenter createPresenter() {
        return new PayTestPresenter();
    }

    public void doAliPay(String orderNo) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("orderNo", orderNo);
            jsonObject.putOpt("payChannel", "ali_app");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.orderPay(jsonObject.toString());
    }

    public void doWeixinPay(String orderNo) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("orderNo", orderNo);
            jsonObject.putOpt("payChannel", "wx_app");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.orderPay(jsonObject.toString());
    }

    @Override
    public void orderPaySuccess(PayTestBean o) {
        if (o != null) {
            if (o.payChannel.equals("ali_app")) {
                String orderInfo = o.pay_info;
                final Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayTestActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }else{
                //微信
                Gson gson=new Gson();
                WeixinPayInfo weixinPayInfo = gson.fromJson(o.pay_info, WeixinPayInfo.class);
                PayReq req = new PayReq();
                req.appId = weixinPayInfo.getAppid();
//                req.appId ="wx97408cd22c879ff7";
                req.partnerId = weixinPayInfo.getPartnerid();
                req.prepayId = weixinPayInfo.getPrepayid();
                req.nonceStr = weixinPayInfo.getNoncestr();
                req.timeStamp = weixinPayInfo.getTimestamp();
                req.packageValue = weixinPayInfo.getPackageValue();
                req.sign = weixinPayInfo.getSign();

//                    req.extData			= "app data"; // optional
                //正在前往微信支付
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                api.sendReq(req);
            }
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        isAlipayOk = true;
                        ToastUtil.getInstance().showShort("支付成功");
                    } else {
//                        isAlipayOk = false;
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(VipInfoActivity.this, getString(R.string.pay_failed) + payResult.getMemo());
                        ToastUtil.getInstance().showShort("支付失败"+resultStatus);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        showAlert(MainActivity.this, getString(R.string.auth_success) + authResult);
                    } else {
                        // 其他状态值则为授权失败
//                        showAlert(MainActivity.this, getString(R.string.auth_failed) + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };


}
