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

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

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.bean.MultiItemBean;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.adapter.AttributeListAdapter;
import com.rv.home.rv.module.ui.main.home.adapter.CarRentalListAdapter;
import com.rv.home.rv.module.ui.main.home.bean.CarAttributeListBean;
import com.rv.home.rv.module.ui.main.home.bean.CarTypeListBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.dialog.CarAttributePw;
import com.rv.home.rv.module.ui.main.home.dialog.SelectAttributeDialog;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created :Auser
 * Date: 2019/5/16.
 * Desc:租车列表
 */
public class CarRentalListActivity extends BaseStatusActivity<CommonPresenter> implements BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R2.id.tv_brand)
    TextView tvBrand;
    @BindView(R2.id.iv_brand)
    ImageView ivBrand;
    @BindView(R2.id.tv_price)
    TextView tvPrice;
    @BindView(R2.id.iv_price)
    ImageView ivPrice;
    @BindView(R2.id.tv_seat)
    TextView tvSeat;
    @BindView(R2.id.iv_seat)
    ImageView ivSeat;
    @BindView(R2.id.tv_selected)
    TextView tvSelected;
    @BindView(R2.id.iv_selected)
    ImageView ivSelected;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.ll_head_menu)
    LinearLayout llHeadMenu;


    public CarRentalListAdapter mAdapter;
    private int countPage;
    private int mPage;
    private double mLat;
    private double mLon;
    private boolean mBool;
    private int selectType;
    private CarAttributePw mCarPw;
    private CarAttributeListBean attributeListBean;
    List<Integer> listScreeningId;//获取筛选的ID
    private OrderDataBean dataBean;

    private  List<CarAttributeListBean.DataBean.CataBean.ChildrenBean> childrenBeanList1;
    private  List<CarAttributeListBean.DataBean.CataBean.ChildrenBean> childrenBeanList2;
    private  List<CarAttributeListBean.DataBean.CataBean.ChildrenBean> childrenBeanList3;

    public static Intent getIntent(Context context, double lat, double lon, boolean bool, OrderDataBean bean, String startTime, String endTime) {
        return new Intent(context, CarRentalListActivity.class)
                .putExtra("lat", lat)
                .putExtra("lon", lon)
                .putExtra("bean", bean)
                .putExtra("bool", bool)
                .putExtra("startTime", startTime)
                .putExtra("endTime", endTime);

    }

    ;

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(mActivity.getString(R.string.rv_select_car));
        dataBean = (OrderDataBean) intent.getSerializableExtra("bean");
        listScreeningId = new ArrayList<>();
        mLat = intent.getDoubleExtra("lat", 0);
        mLon = intent.getDoubleExtra("lon", 0);
        mBool = intent.getBooleanExtra("bool", false);
        titleView.setImageResource(R.id.iv_title_right, R.drawable.rv_rentingcar_icon_plat);
        titleView.setChildClickListener(R.id.iv_title_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(ShopShowActivity.getIntent(mActivity, 0, 0));
            }
        });
        mAdapter = new CarRentalListAdapter();
        mAdapter.setOnLoadMoreListener(this, recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CarTypeListBean.DataBeanX.DataBean bean = mAdapter.getItem(position);
                if (dataBean != null) {
                    dataBean.setModelId(bean.getVehicleModel().getId());
                    dataBean.setStartCompanyId(bean.getCompany().getId());
                }
                startActivity(CarDetailActivity.getIntent(mActivity, dataBean, bean, getIntent().getStringExtra("startTime"), getIntent().getStringExtra("endTime")));
            }
        });


    }

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

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                initData((CarAttributeListBean) result);

                break;
            case 1:
                processData((CarTypeListBean) result);
                break;
        }
    }

    private void initData(CarAttributeListBean data) {
        childrenBeanList1 = new ArrayList<>();
        childrenBeanList2 = new ArrayList<>();
        childrenBeanList3 = new ArrayList<>();
        if (data != null) {
            List<CarAttributeListBean.DataBean.CataBean> cata = data.getData().getCata();
            if (cata != null && cata.size() > 1) {
                CarAttributeListBean.DataBean.CataBean.ChildrenBean childrenBean1 = new CarAttributeListBean.DataBean.CataBean.ChildrenBean();
                childrenBean1.setName("全部");
                childrenBean1.setShow(true);
                childrenBeanList1.add(childrenBean1);
                childrenBeanList1.addAll(cata.get(0).getChildren());

                CarAttributeListBean.DataBean.CataBean.ChildrenBean childrenBean2 = new CarAttributeListBean.DataBean.CataBean.ChildrenBean();
                childrenBean2.setName("全部");
                childrenBean2.setShow(true);
                childrenBeanList2.add(childrenBean2);
                childrenBeanList2.addAll(cata.get(1).getChildren());

                CarAttributeListBean.DataBean.CataBean.ChildrenBean childrenBean3 = new CarAttributeListBean.DataBean.CataBean.ChildrenBean();
                childrenBean3.setName("全部");
                childrenBean3.setShow(true);
                childrenBeanList3.add(childrenBean3);
                childrenBeanList3.addAll(cata.get(2).getChildren());
            }
        }
        attributeListBean = data;
        initAttr();
//         .get(0).getChildren();
    }

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

    @Override
    public void onDestroy() {
        if (mCarPw != null) {
            mCarPw.onDestroy();
        }
        super.onDestroy();
    }

    @OnClick({R2.id.rl_brand, R2.id.rl_price, R2.id.rl_seat, R2.id.rl_selected})
    public void onViewClicked(View view) {
        if (attributeListBean == null) {
            return;
        }

        if (view.getId() == R.id.rl_brand) {
            setMenuSelect(0, view, childrenBeanList1, tvBrand.getText().toString().trim());
        } else if (view.getId() == R.id.rl_price) {
            setMenuSelect(1, view, childrenBeanList2, tvPrice.getText().toString().trim());
        } else if (view.getId() == R.id.rl_seat) {
            setMenuSelect(2, view, childrenBeanList3, tvSeat.getText().toString().trim());
        } else if (view.getId() == R.id.rl_selected) {
            setMenuSelect(3, view, null, null);
            List<MultiItemBean> multiList = new ArrayList<>();
            for (CarAttributeListBean.DataBean.CataBean bean : attributeListBean.getData().getCata()) {
                multiList.add(bean);
                for (CarAttributeListBean.DataBean.CataBean.ChildrenBean childrenBean : bean.getChildren()) {
                    if (listScreeningId != null && listScreeningId.size() > 0) {
                        childrenBean.isSelect = listScreeningId.indexOf(childrenBean.getId()) > -1 ? 1 : 0;
                    }
                    multiList.add(childrenBean);
                }
            }
            showSelected(multiList);
        }
    }


    /**
     * 获取车辆属性列表
     */
    private void getCarAttrList() {
        mPresenter.postData(0, ApiConfig.HTTP_URL_CAR_ATTRIBUTE_LIST, CarAttributeListBean.class, true);
    }

    /**
     * 获取车辆列表
     */
    private void getCarList(int page) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", page);
        if (listScreeningId != null && listScreeningId.size() > 0) {
            map.put("catasStr", getIdGroup());
        }
        map.put("addrCity", dataBean.getStartCity());
        map.put("limit", 10);
        map.put("lat", mLat);
        map.put("lon", mLon);
        map.put("startDateTamp", dataBean.getStartTime());
        map.put("endDateTamp", dataBean.getEndTime());
        mPresenter.getData(RvFrameConfig.VEHICLE_POST, 1, ApiConfig.HTTP_URL_CAR_TYPE_LIST, CarTypeListBean.class, map, true);
    }

    /**
     * 获得筛选ID
     *
     * @return
     */
    private String getIdGroup() {
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < listScreeningId.size(); i++) {
            stringBuilder.append(String.valueOf(listScreeningId.get(i)));
            stringBuilder.append(",");
        }
        return stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
    }

    /**
     * 刷新
     */
    private void onFresh() {
        mPage = 1;
        getCarList(mPage);
    }

    private void processData(CarTypeListBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getTotalPage();
            mAdapter.setNewData(bean.getData().getData());
            if (bean.getData().getTotalCount() == 0) {
                mAdapter.setEmptyView(getEmptyView(recyclerView, -1, mActivity.getString(R.string.rv_car_type_data_null)));
                mAdapter.notifyDataSetChanged();
            }

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

    /**
     * 初始化筛选数据
     */
    private void initAttr() {
        if (attributeListBean != null && attributeListBean.getData().getCata().size() > 0) {
            tvBrand.setText(attributeListBean.getData().getCata().get(0).getName());
            tvPrice.setText(attributeListBean.getData().getCata().get(1).getName());
            tvSeat.setText(attributeListBean.getData().getCata().get(2).getName());
        }
    }


    private void setMenuSelect(int index, View view, List<CarAttributeListBean.DataBean.CataBean.ChildrenBean> list, String attrName) {
//        if(mCarPw!=null && mCarPw.isShowing()){
//            mCarPw.dismiss2();
//        }
        selectType = index;
//        setViewStyle(ivBrand, tvBrand, selectType == 0);
//        setViewStyle(ivPrice, tvPrice, selectType == 1);
//        setViewStyle(ivSeat, tvSeat, selectType == 2);
//        setViewStyle(ivSelected, tvSelected, selectType == 3);

        showPopupWindow(view, list, index, attrName);

    }

    /**
     * 设置view的样式
     */
    private void setViewStyle(ImageView imageView, TextView textView, boolean isTrue) {
        imageView.setSelected(isTrue);
        textView.setTextColor(ContextCompat.getColor(this, isTrue ? R.color.colorAuxiliaryYellow : R.color.textMain));
    }

    /**
     * 展示menu属性 窗体
     */
    private void showPopupWindow(final View view, List<CarAttributeListBean.DataBean.CataBean.ChildrenBean> list, final int type, String attrName) {
        if (list == null) {
            return;
        }
        if (mCarPw == null) {
            mCarPw = new CarAttributePw(mActivity) {
            };
        }
        mCarPw.setOnItemClick(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View views, int position) {
//                mCarPw.attributeAdapter.setSelectItem(position);
                CarAttributeListBean.DataBean.CataBean.ChildrenBean childrenBean = mCarPw.attributeAdapter.getItem(position);
                switch (type) {
                    case 0:
                        tvBrand.setText(childrenBean.getName());
                        break;
                    case 1:
                        tvPrice.setText(childrenBean.getName());
                        break;
                    case 2:
                        tvSeat.setText(childrenBean.getName());
                        break;
                }
                if (listScreeningId != null && listScreeningId.indexOf(childrenBean.getId()) == -1) {
                    listScreeningId.add(childrenBean.getId());
                }
                onFresh();
                mCarPw.dismiss();
            }
        });
        mCarPw.showPopupWindow(llHeadMenu);
        mCarPw.setNewData(list);
        mCarPw.attributeAdapter.setSelectItem(attrName);
    }

    /**
     * 显示筛选选弹窗
     */
    private void showSelected(final List<MultiItemBean> list) {

        new SelectAttributeDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                RecyclerView recyclerView = helper.getView(R.id.recyclerView);
                final AttributeListAdapter adapter = new AttributeListAdapter(list);
                recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 6));
                recyclerView.setAdapter(adapter);
                helper.setOnClickListener(R.id.tv_reset, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listScreeningId != null) {
                            listScreeningId.clear();
                            initAttr();
                            adapter.resetData();
                        }

                    }
                });
                helper.setOnClickListener(R.id.tv_ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listScreeningId != null) {
                            listScreeningId.clear();
                            listScreeningId = adapter.getSelectId(listScreeningId);
                            initAttr();
                            onFresh();
                            dismiss();
                        }

                    }
                });
                /**
                 * 设置每个Item的横排显示数量
                 *  注意：======对应GridLayoutManager设置
                 */
                adapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                        return list.get(position).getSpanSize();
                    }
                });
                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapters, View view, int position) {
                        adapter.setItemSelect(position);
                    }
                });
            }
        }.show();
    }


}
