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

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
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.Observer;
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.ruiwenliu.wrapper.base.presenter.CommonPresenter;
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.OrderListAdapter;
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;

/**
 * Created :Auser
 * Date: 2019/5/28.
 * Desc:全部订单
 */

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

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

    public static AllOrderFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        AllOrderFragment fragment = new AllOrderFragment();
        fragment.setArguments(bundl);
        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 OrderListAdapter(new ArrayList<MultiItemEntity>());
        mAdapter.setOnLoadMoreListener(this, recyclerView);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        recyclerView.setAdapter(mAdapter);

        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.getNo()), 1);
                } else if (2 == dataBean.getType()) {
                    startActivityForResult(TravelOrderDetailsActivity.getIntent(_mActivity, dataBean.getNo()), 2);
                } else if (3 == dataBean.getType()) {
                    startActivityForResult(MemberOrderDetailsActivity.getIntent(_mActivity, dataBean.getNo()),3);
                }
            }
        });


        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int id = view.getId();
                OrderListBean.DataBeanX.DataBean dataBean = (OrderListBean.DataBeanX.DataBean) adapter.getItem(position);
                // 0–删除   1–创建订单   2–取消    3–待付款  4–待出行   5–出行中（进行中）   6–已完成
                switch (dataBean.getStatusX()) {
                    case 3:
                        if (id == R.id.tv_process) {
                            payShowSelect(dataBean.getNo(), dataBean.getOrderAmount());
                        } else if (id == R.id.tv_camp_process) {
                            payShowSelect(dataBean.getNo(), dataBean.getOrderAmount());
                        } else if (id == R.id.tv_member_pay) {
                            payShowSelect(dataBean.getNo(), dataBean.getOrderAmount());
                        }
                        break;
                    case 4:
                        if (id == R.id.tv_process) {
                            startActivity(PickUpTheCarQRCodeActivity.getIntent(_mActivity,dataBean.getNo()));
                        } else if (id == R.id.tv_camp_process) {
                            startActivity(GetOnTheCarQRCodeActivity.getIntent(_mActivity, dataBean.getNo()));
                        }
                        break;
                    case 5:
                        if (id == R.id.tv_process) {
                            startActivity(PickUpTheCarQRCodeActivity.getIntent(_mActivity, dataBean.getNo()));
                        } else if (id == R.id.tv_camp_process) {
                            startActivity(GetOnTheCarQRCodeActivity.getIntent(_mActivity, dataBean.getNo()));
                        }
                        break;
                    case 6:
                        break;
                }

            }
        });
        initRxbus();
    }

    private void initRxbus() {
        RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PaymentSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(PaymentSuccessfulEvent event) {
                        onRefresh();
                    }
                });
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {

    }

    @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);

        }
    }


    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);
        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;
                }
            }
        }
    };

}
