package com.rv.member.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.frame.rv.widget.PayResult;
import com.ruiwenliu.wrapper.weight.ToastView;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.member.MemberCenterActivity;
import com.rv.member.bean.MemberListBean;
import com.rv.member.bean.BeanTourOrderPay;
import com.rv.member.bean.MemberOrderBean;
import com.rv.member.bean.MemberOrderPostBodyBean;
import com.rv.member.bean.PayBodyBean;
import com.rv.tourism.api.TourismApi;
import com.rv.tourism.bean.BeanTourOrderAliPay;
import com.rv.tourism.other.TravelerConfirmOrderActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.Map;

public class MemberPresenter extends CommonPresenter {
    private static final int SDK_ALI_PAY_FLAG = 11;

    public void pay(Context context, IWXAPI api, BeanTourOrderPay data) {
        try {
            PayReq req = new PayReq();
            req.appId = data.getData().getAppid();
            req.partnerId = data.getData().getPartnerid();
            req.prepayId = data.getData().getPrepayid();
            req.nonceStr = data.getData().getNoncestr();
            req.timeStamp = data.getData().getTimestamp();
            req.packageValue = data.getData().getPackageX();
            req.sign = data.getData().getSign();
            req.extData = "app data"; // optional
            api.sendReq(req);
        } catch (Exception e) {
            ToastView.getInstance(context).showToastContent("异常", Toast.LENGTH_SHORT);
        }
    }

    public void createOrder(MemberListBean.MemberCard card, int position) {

        MemberOrderPostBodyBean memberOrderPostBodyBean = new MemberOrderPostBodyBean("", card.getLevel(), card.getId());
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        postBodyData(RvFrameConfig.ADMIN_POST, position, ApiConfig.HTTP_URL_MEMBER_CREATE_ORDER, MemberOrderBean.class, memberOrderPostBodyBean, headMap, true);
    }

    /**
     * 订单支付
     */
    public void orderPay(String orderNo, int payWay, int type) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        if (payWay == 1) {
            postBodyData(RvFrameConfig.VEHICLE_ORDER, 3, ApiConfig.COMMIT_ORDER_PAY, BeanTourOrderPay.class, new PayBodyBean(orderNo, payWay, type), headMap, true);
        } else {
            postBodyData(RvFrameConfig.VEHICLE_ORDER, 4, TourismApi.COMMIT_ORDER_PAY, BeanTourOrderAliPay.class, new PayBodyBean(orderNo, payWay, type), headMap, true);
        }
    }

    public void aliPay(final MemberCenterActivity memberCenterActivity, final BeanTourOrderAliPay bean) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(memberCenterActivity);
                Map<String, String> result = alipay.payV2(bean.getData(), true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_ALI_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝返回数据handler
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_ALI_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        RxBus.post(new PaymentSuccessfulEvent());
                    } else if ("6001".equals(resultStatus)) {
                        RxBus.post(new PaymentFailedEvent());
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showToast(payResult.toString());
                    }
                    break;
                }
            }
        }
    };

}
