package com.xxrv.invoice.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.bus.Observer;
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.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.xxrv.invoice.R;
import com.xxrv.invoice.R2;
import com.xxrv.invoice.adapter.OrderInvoicingCarAdapter;
import com.xxrv.invoice.api.InvoiceApi;
import com.xxrv.invoice.bean.Invoiceing;
import com.xxrv.invoice.bean.OrderInvoicingCarBean;
import com.xxrv.invoice.bus.InvoicingSuccessEvent;
import com.xxrv.invoice.presenter.InvoicePresenter;
import com.yuyife.okgo.OkGoUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 租车开发票订单列表
 */
public class OrderInvoicingCarActivity extends BaseStatusActivity<InvoicePresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {

    @BindView(R2.id.rv_content)
    RecyclerView rvContent;
    @BindView(R2.id.tv_number)
    TextView tvNumber;
    @BindView(R2.id.tv_price)
    TextView tvPrice;
    @BindView(R2.id.cb_all)
    CheckBox cbAll;
    @BindView(R2.id.iv_noorder_hint)
    ImageView ivNoorderHint;
    @BindView(R2.id.tv_item_next)
    TextView tvItemNext;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.ll_item_hint)
    LinearLayout llItemHint;
    @BindView(R2.id.ll_item_bottom)
    LinearLayout llItemBottom;


    private OrderInvoicingCarAdapter mAdapter;
    private List<String> orderIdList = new ArrayList<>(); //选择中的订单
    private boolean isCheckAll = true;
    private double totalPrice;
    private int mPage;
    private int countPage;

    private int type;

    public static Intent getIntent(Context context, int type) {
        return new Intent(context, OrderInvoicingCarActivity.class)
                .putExtra("type", type);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_order_invoicing_car;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("按订单开票");

        type = intent.getIntExtra("type", 1);

        mAdapter = new OrderInvoicingCarAdapter();
        mAdapter.setOnLoadMoreListener(this, rvContent);
        rvContent.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(this));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        rvContent.setAdapter(mAdapter);


        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.ll_item_bg || view.getId() == R.id.cb_select) {
                    mAdapter.setItemState(position);
                    getCountSelectData();
                    if (mAdapter.getData().size() != mAdapter.getSelectItem().size()) {
                        cbAll.setChecked(false);
                        isCheckAll = true;
                    } else {
                        cbAll.setChecked(true);
                        isCheckAll = false;
                    }
                }
            }
        });

        initRxbus();
    }

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

    private void getCountSelectData() {
        List<OrderInvoicingCarBean.DataBeanX.DataBean> selectItem = mAdapter.getSelectItem();
        tvNumber.setText(String.valueOf(selectItem.size()));
        totalPrice = 0;
        orderIdList.clear();
        if (selectItem != null && selectItem.size() > 0) {
            for (int i = 0; i < selectItem.size(); i++) {
                totalPrice = totalPrice + selectItem.get(i).getOrderRealAmount();
                orderIdList.add(String.valueOf(selectItem.get(i).getId()));
            }
        }
        tvPrice.setText(String.valueOf(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));

        if (selectItem.size() > 0) {
            tvItemNext.setBackgroundResource(R.drawable.shape_rv_bg_shallow_dark_yellow_circle);
            tvItemNext.setEnabled(true);
        } else {
            tvItemNext.setBackgroundResource(R.drawable.shape_rv_bg_shallow_dark_yellow_circle2);
            tvItemNext.setEnabled(false);
        }
    }

    private void setAllSelect(int type) {
        List<OrderInvoicingCarBean.DataBeanX.DataBean> data = mAdapter.getData();
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                data.get(i).setSelectType(type);
                mAdapter.notifyItemChanged(i);
            }
        }
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        switch (requestType) {
            case 0:
                processData((OrderInvoicingCarBean) result);
                break;
        }
    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        mSimpleRefreshLayout.onRefreshComplete();
    }

    @OnClick({R2.id.tv_item_hint, R2.id.cb_all, R2.id.tv_item_next})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_item_hint) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "按订单开票")
                    .withString("url", InvoiceApi.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 27)
                    .navigation();
        } else if (id == R.id.cb_all) {

            if (isCheckAll) {
                setAllSelect(1);
                cbAll.setChecked(true);
            } else {
                setAllSelect(0);
                cbAll.setChecked(false);
            }
            isCheckAll = !isCheckAll;
            getCountSelectData();

        } else if (id == R.id.tv_item_next) {
            String ids = orderIdList.toString().replace("[", "").replace("]", "").replaceAll(" ", "");

            Invoiceing invoiceing = new Invoiceing();
            invoiceing.setIds(ids);
            invoiceing.setAmount(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            invoiceing.setType(type);
            String jsonString = JSON.toJSONString(invoiceing);
            startActivity(OrderInvoicingCarDetailsActivity.getIntent(mActivity, jsonString));
        }
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        onRefresh();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        orderData(mPage);
//        tvItemNext.setBackgroundResource(R.drawable.shape_rv_bg_shallow_dark_yellow_circle2);
//        tvItemNext.setEnabled(false);
//        tvNumber.setText("0");
//        tvPrice.setText("0.0");
    }


    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("multiStatus", "6");
        mapData.put("type", type);  //"订单类型 1--租车；2--旅游; 3--会员订单")
        mapData.put("invoiceStatus", "0");  //"开票状态，0未开票，1已开票
        mPresenter.getData(RvFrameConfig.VEHICLE_ORDER, 0, InvoiceApi.HTTP_URL_ORDER_LIST, OrderInvoicingCarBean.class, mapData, headMap, page == 1 ? true : false);
    }


    /**
     * 处理请求数据
     *
     * @param bean
     */
    private void processData(OrderInvoicingCarBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getTotalPage();
            mAdapter.setNewData(bean.getData().getData());
            mSimpleRefreshLayout.onRefreshComplete();
            if (bean.getData().getTotalCount() == 0) {
                llItemHint.setVisibility(View.GONE);
                llItemBottom.setVisibility(View.GONE);
                ivNoorderHint.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
            } else {
                llItemHint.setVisibility(View.VISIBLE);
                llItemBottom.setVisibility(View.VISIBLE);
                ivNoorderHint.setVisibility(View.GONE);
            }
        } else {
            mAdapter.addData(bean.getData().getData());
            mAdapter.loadMoreComplete();
        };
        getCountSelectData();
        if (mAdapter.getData().size() != mAdapter.getSelectItem().size()) {
            cbAll.setChecked(false);
            isCheckAll = true;
        } else {
            cbAll.setChecked(true);
            isCheckAll = false;
        }
    }

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

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
