package com.rv.home.rv.module.ui.main.home.order;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
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.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.component.dialog.PaymentTypeSelection;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.ConfirmOrderActivity;
import com.rv.home.rv.module.ui.main.home.bean.EffectiveTimeBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderAliPayBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderPayBean;
import com.rv.home.rv.module.ui.main.home.order.adapter.ForPaymentAdapter;
import com.rv.home.rv.module.ui.main.home.order.bean.OrderListBean;
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.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created :Auser
 * Date: 2019/5/28.
 * Desc:待付款
 */

public class ForPaymentFragment extends BaseFragment<CommonPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    ForPaymentAdapter mAdapter;
    private int mPage;
    private int countPage;
    private IWXAPI api;
    private int payType = 1;//选择支付类型

    private static final int SDK_ALI_PAY_FLAG = 11;

    private OrderListBean.DataBeanX.DataBean payBean = null;
    private int payPosition = -1;
    private OrderListActivity.SwitchListener mListener;

    public static ForPaymentFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        ForPaymentFragment fragment = new ForPaymentFragment();
        fragment.setArguments(bundl);
        return fragment;
    }

    public static ForPaymentFragment getInstance(int type, OrderListActivity.SwitchListener listener) {
        ForPaymentFragment fragment = getInstance(type);
        fragment.mListener = listener;
        return fragment;
    }

    @Override
    public int getViewLayout() {
        return R.layout.common_refresh;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        api = WXAPIFactory.createWXAPI(_mActivity, RvFrameConfig.APP_ID);
        recyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        mAdapter = new ForPaymentAdapter(new ArrayList<MultiItemEntity>());
        mAdapter.setOnLoadMoreListener(this, recyclerView);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        recyclerView.setAdapter(mAdapter);
        initRxBus();

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderListBean.DataBeanX.DataBean dataBean = (OrderListBean.DataBeanX.DataBean) adapter.getItem(position);
                if (1 == dataBean.getType()) {
                    startActivityForResult(OrderDetailActivity.getIntent(_mActivity, dataBean), 1);
                } else if (2 == dataBean.getType()) {
                    startActivityForResult(TravelOrderDetailsActivity.getIntent(_mActivity, dataBean), 2);
                } else if (3 == dataBean.getType()) {
                    startActivityForResult(MemberOrderDetailsActivity.getIntent(_mActivity, dataBean), 3);
                }
            }
        });


        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                payPosition = position;
                int id = view.getId();
                if (id == R.id.tv_process || id == R.id.tv_camp_process || id == R.id.tv_member_pay) {
                    payBean = (OrderListBean.DataBeanX.DataBean) adapter.getItem(position);
                    payShowSelect(payBean.getNo(), payBean.getRealAmount());
                }
            }
        });
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {

    }

    private Disposable disposable;

    @SuppressLint("CheckResult")
    private void initRxBus() {

        disposable = RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<PaymentSuccessfulEvent>() {
                    @Override
                    public void accept(PaymentSuccessfulEvent payEvent) throws Exception {
                        if (payPosition != -1) {
                            if (mAdapter != null && !mAdapter.getData().isEmpty()) {
                                mAdapter.getData().remove(payPosition);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                        if (mListener != null) {
                            mListener.switchTab(3);
                        }
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                processData((OrderListBean) result);
                break;
            case 1:
                pay((OrderPayBean) result);
                break;
            case 2:
                aliPayData((OrderAliPayBean) result);
                break;
        }
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        onRefresh();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        orderData(mPage);
    }

    @Override
    public void onLoadMoreRequested() {
        if (mPage >= countPage) {
            mAdapter.loadMoreEnd();

        } else {
            mPage++;
            orderData(mPage);

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            onRefresh();
        }
    }

    private void orderData(int page) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> mapData = new LinkedHashMap<>();
        mapData.put("page", page);
        mapData.put("limit", 10);
        mapData.put("status", 3);
        mPresenter.getData(RvFrameConfig.VEHICLE_ORDER, 0, ApiConfig.HTTP_URL_ORDER_LIST, OrderListBean.class, mapData, headMap, page == 1 ? true : false);
    }

    /**
     * 处理请求数据
     *
     * @param bean
     */
    private void processData(OrderListBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getTotalPage();
            mAdapter.addNewData(bean);
            mSimpleRefreshLayout.onRefreshComplete();
            if (bean.getData().getTotalCount() == 0) {
                mAdapter.setEmptyView(getEmptyView(recyclerView, -1, _mActivity.getString(R.string.rv_select_not_data)));
                mAdapter.notifyDataSetChanged();
            }

        } else {
            mAdapter.addData(bean.getData().getData());
            mAdapter.loadMoreComplete();
        }
    }

    /**
     * 支付类型选择
     */
    private void payShowSelect(final String no, final double orderAmount) {
        payType = 1;
        PaymentTypeSelection dialog = new PaymentTypeSelection(_mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.tv_amount, String.format("￥%1$s", orderAmount));
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        if (id == R.id.iv_close) {
                            dismiss();
                        } else if (id == R.id.ll_item_wechat) {
                            payType = 1;
                            helper.getView(R.id.iv_wx_select).setSelected(true);
                            helper.getView(R.id.iv_alipy_select).setSelected(false);
                        } else if (id == R.id.ll_item_alipay) {
                            payType = 2;
                            helper.getView(R.id.iv_wx_select).setSelected(false);
                            helper.getView(R.id.iv_alipy_select).setSelected(true);
                        } else if (id == R.id.tv_pay_immediately) {
                            dismiss();
                            createOrder(no);
                        }
                    }
                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
            }
        };
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    private void createOrder(String orderNo) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        headMap.put("Authorization", OkGoUtil.getToken());
        if (payType == 1) {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 1, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderPayBean.class, new payBody(orderNo, payType, 1), headMap, true);
        }else {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 2, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderAliPayBean.class, new payBody(orderNo, payType, 1), headMap, true);
        }
    }


    public class payBody {
        private String orderNo;
        private int payWay;
        private int type;

        public payBody(String orderNo, int payWay, int type) {
            this.orderNo = orderNo;
            this.payWay = payWay;
            this.type = type;
        }

        public String getOrderNo() {
            return orderNo;
        }

        public void setOrderNo(String orderNo) {
            this.orderNo = orderNo;
        }

        public int getPayWay() {
            return payWay;
        }

        public void setPayWay(int payWay) {
            this.payWay = payWay;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }


    private void pay(OrderPayBean 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) {
            showToast("异常");
        }

    }


    /**
     * 显示支付宝签名
     */
    public void aliPayData(final OrderAliPayBean bean) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(_mActivity);
                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)) {
                        showToast("支付取消！");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast(payResult.toString());
                    }
                    break;
                }
            }
        }
    };

}
