package com.rv.share.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
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.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.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.share.bean.AllGoodsListBean;
import com.rv.share.bean.BeanTourOrderAliPay;
import com.rv.share.bean.BeanTourOrderPay;
import com.rv.share.bean.OrderGoodsBean;
import com.rv.share.bean.PayBodyBean;
import com.rv.share.view.ShareChoiceDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuyife.okgo.OkGoUtil;

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

public class PreCardWebviewPresenter extends WebViewPresenter {

    public void showShareDialog(String url, String iconUrl, String title, String circleTitle, String descript, String imgUrl) {
        this.mUrl = url;
        this.iconUrl = iconUrl;
        this.mCircleTitle = circleTitle;
        this.mTitle = title;
        this.mDescript = descript;
        this.imgUrl = imgUrl;
        if (dialog == null) {
            dialog = new ShareChoiceDialog.Builder(getPresenterContext())
                    .setShareListener(myListener)
                    .setCopyVisiable(true)
                    .setWxVisiable(true)
                    .setWxCVisiable(true)
                    .setQQVisiable(true)
                    .setBillVisiable(false)
                    .create();
        }
        dialog.show();
    }


    private static final int SDK_ALI_PAY_FLAG = 11;

    private Context context;


    /******
     * 创建订单
     * @param title
     * @param detailList
     * @param number
     */
    public void createOrder(String title,AllGoodsListBean.DetailList detailList,int number) {
        if (detailList != null) {
            OrderBody orderBody = new OrderBody();
            orderBody.name = title;
            orderBody.picture = detailList.specsImg;
            orderBody.productId = detailList.goodsId;
            orderBody.specsId = detailList.id;
            orderBody.productSpecs = detailList.goodsSpecs;
            orderBody.productName = detailList.name;
            orderBody.number = number;
            Map<String, String> header = new HashMap<>(2);
            header.put("Authorization", OkGoUtil.getToken());
            postBodyData(1, ApiConfig.HTTP_URL_ACTIVITY_ADD, OrderGoodsBean.class, orderBody, header, true);
        }
    }

    class OrderBody {
        public String name;
        public String picture;
        public int type = 1;
        public long productId;
        public long specsId;
        public String productSpecs;
        public String productName;
        public int number;
    }

    /**
     * 订单支付
     */
    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, ApiConfig.COMMIT_ORDER_PAY, BeanTourOrderAliPay.class, new PayBodyBean(orderNo, payWay, type), headMap, true);
        }
    }


    public void pay(Context context, BeanTourOrderPay data) {
        try {

            IWXAPI api = WXAPIFactory.createWXAPI(context, RvFrameConfig.APP_ID);

            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 aliPay(final Activity activity, final BeanTourOrderAliPay bean) {
        context = activity;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                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")) {
                        ToastView.getInstance(context).showToastContent("支付成功！", Toast.LENGTH_SHORT);
                        RxBus.post(new PaymentSuccessfulEvent());
                    } else if ("6001".equals(resultStatus)) {
                        ToastView.getInstance(context).showToastContent("支付取消！", Toast.LENGTH_SHORT);
                        RxBus.post(new PaymentFailedEvent());
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showToast(payResult.toString());
                    }
                    break;
                }
            }
        }
    };


}
