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

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.bus.Observer;
import com.frame.base.bus.PaymentFailedEvent;
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.inter.OnViewHolder;
import com.ruiwenliu.wrapper.util.TimeManager;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.component.utils.DateUtils;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.ruiwenliu.wrapper.bean.MultiItemBean;
import com.ruiwenliu.wrapper.base.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.CarRentalPriceBean;
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.CheckPriceDialog;
import com.rv.home.rv.module.ui.main.home.dialog.SelectAttributeDialog;
import com.yuyife.okgo.OkGoUtil;

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

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

/**
 * Created :Auser
 * Date: 2019/5/16.
 * Desc:租车列表
 */
public class CarRentalListActivity extends BaseStatusActivity<CommonPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.ll_head_menu)
    LinearLayout llHeadMenu;
    @BindView(R2.id.tv_get_date)
    TextView tvGetDate;
    @BindView(R2.id.tv_out_date)
    TextView tvOutDate;
    @BindView(R2.id.tv_get_address)
    TextView tvGetAddress;
    @BindView(R2.id.tv_out_address)
    TextView tvOutAddress;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;

    public CarRentalListAdapter mAdapter;
    private int countPage;
    private int mPage;
    private double mLat;
    private double mLon;
    private double outLongitude;
    private double outLatitude;
    private boolean mBool;
    private int selectType;
    private CarAttributePw mCarPw;
    private CarAttributeListBean attributeListBean;
    List<Integer> listScreeningId;//获取筛选的ID
    private OrderDataBean dataBean;
    private String begDate;
    private String endDate;
    private long copyDay;//租车天数
    private CheckPriceDialog checkPriceDialog;

    public static Intent getIntent(Context context, double lat, double lon, double outLatitude, double outLongitude, boolean bool, OrderDataBean bean, String startTime, String endTime) {
        return new Intent(context, CarRentalListActivity.class)
                .putExtra("lat", lat)
                .putExtra("lon", lon)
                .putExtra("outLatitude", outLatitude)
                .putExtra("outLongitude", outLongitude)
                .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));
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        begDate = intent.getStringExtra("startTime");
        endDate = intent.getStringExtra("endTime");
        dataBean = (OrderDataBean) intent.getSerializableExtra("bean");
        listScreeningId = new ArrayList<>();
        mLat = intent.getDoubleExtra("lat", 0);
        mLon = intent.getDoubleExtra("lon", 0);
        outLatitude = intent.getDoubleExtra("outLatitude", 0);
        outLongitude = intent.getDoubleExtra("outLongitude", 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));
            }
        });

        tvGetDate.setText("取" + DateUtils.formatDate66(begDate));
        tvOutDate.setText("还" + DateUtils.formatDate66(endDate));
        tvGetAddress.setText(dataBean.getStartAddr());
        tvOutAddress.setText(dataBean.getEndAddr());

        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 ("1".equals(bean.getHasVehicle())) {
                    if (dataBean != null) {
                        dataBean.setModelId(bean.getVehicleModel().getId());
                        dataBean.setStartCompanyId(bean.getCompany().getId());

                    }
                    startActivity(CarDetailActivity.getIntent(mActivity, dataBean, bean, begDate, endDate));
                }
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CarTypeListBean.DataBeanX.DataBean bean = mAdapter.getItem(position);
                if (view.getId() == R.id.tv_item_loook_price) {
                    if (checkPriceDialog == null) {
                        checkPriceDialog = new CheckPriceDialog(mActivity);
                    }
                    getCheckPrice(bean.getVehicleModel().getId());
                }
            }
        });

        initRxbus();
    }

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

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


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


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

                break;
            case 1:
                processData((CarTypeListBean) result);
                break;
            case 2:
                checkPrice((CarRentalPriceBean) result);
                break;
        }
    }

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


    private void initData(CarAttributeListBean data) {
        attributeListBean = data;
//         .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.ll_item_select_date, R2.id.ll_item_get_address, R2.id.ll_item_out_address, R2.id.ll_item_filter})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_select_date) {
            //选择时间
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CALENDAR)
                    .withString("begDate", begDate)
                    .withString("endDate", endDate)
                    .navigation(mActivity, 109);

        } else if (id == R.id.ll_item_get_address) {

            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat", mLat)
                    .withDouble("mLon", mLon)
                    .withString("cityName", dataBean.getStartCityName())
                    .withInt("shopType", 1)
                    .navigation(mActivity, 110);

//            startActivityForResult(SelectShopActivity.getIntent(mActivity, 1, "", dataBean.getStartCityName(), mLat, mLon), 110);

//            //取车地址
//            startActivityForResult(SelectLocationActivity.getIntent(mActivity, 1, dataBean.getStartCityName(), dataBean.getStartCity(),mLat, mLon, "", 1), 110);

        } else if (id == R.id.ll_item_out_address) {
            //还车地址
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat", mLat)
                    .withDouble("mLon", mLon)
                    .withString("cityName", dataBean.getEndCityName())
                    .withInt("shopType", 2)
                    .navigation(mActivity, 110);

//            startActivityForResult(SelectShopActivity.getIntent(mActivity, 2, "", dataBean.getEndCityName(), outLatitude, outLongitude), 110);
//            startActivityForResult(SelectLocationActivity.getIntent(mActivity, 2, dataBean.getStartCityName(),dataBean.getEndCity(), outLatitude, outLongitude, "", 1), 110);
        } else if (id == R.id.ll_item_filter) {
            if (attributeListBean == null) {
                return;
            }
            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);
        }
    }

    /**
     * 获取价格日历
     *
     * @param id
     */
    private void getCheckPrice(int id) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("start", begDate);
        map.put("end", endDate);
        mPresenter.getData(RvFrameConfig.HOST, 2, ApiConfig.HTTP_URL_CALENDAR_PRICE + id, CarRentalPriceBean.class, map, headMap, true);
    }


    /**
     * 获取车辆属性列表
     */
    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("parkBranchCompanyId", dataBean.getStartCompanyId());
        map.put("startCompanyId", dataBean.getStartCompanyId());
        map.put("endCompanyId", dataBean.getEndCompanyId());
        try {
            map.put("startDateTamp", TimeManager.dateToStamp(begDate));
            map.put("endDateTamp", TimeManager.dateToStamp(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }

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


    /**
     * 设置价格日历
     *
     * @param result
     */
    private void checkPrice(CarRentalPriceBean result) {
        if (checkPriceDialog != null) {
            checkPriceDialog.setNewData(result.getData());
            checkPriceDialog.show();
        }
    }


    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, "暂无房车，请更改取车公司或时间"));
                mAdapter.notifyDataSetChanged();
            }

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


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


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200 && requestCode == 109) {
            begDate = data.getStringExtra("begDate");
            endDate = data.getStringExtra("endDate");
            copyDay = getCountDay(begDate, endDate);  //天数
            tvGetDate.setText("取" + DateUtils.formatDate66(begDate));
            tvOutDate.setText("还" + DateUtils.formatDate66(endDate));
            dataBean.setDayNum(Integer.valueOf(copyDay + ""));
            dataBean.setStartTime(DateUtils.StringToTimeMillis2(begDate));
            dataBean.setEndTime(DateUtils.StringToTimeMillis2(endDate));
            onFresh();

        } else if (requestCode == 110 && resultCode == RESULT_OK) {

            double lat = data.getDoubleExtra("latitude", 0);
            double lon = data.getDoubleExtra("longitude", 0);
            int type = data.getIntExtra("type", 1);
            String requestData = data.getStringExtra("location");
            String company = data.getStringExtra("company");
            int companyId = data.getIntExtra("company_id", 1);
            int cityId = data.getIntExtra("id", 0);
            String cityName = data.getStringExtra("location");
            setRequestData(type, requestData, lat, lon, company, cityId, companyId, cityName);
        }
    }

    /**
     * 计算天数
     *
     * @param endDate2
     * @param begDate2
     * @return
     */
    private long getCountDay(String begDate2, String endDate2) {
        long second = DateUtils.compareDateSecond3(endDate2, begDate2);   //两个时间相差的秒数
        long day = (long) second / 86400;       //天数
        long remainder = (long) second % 86400;  //余数  秒

        if (day == 0) {               //不够24小时也算一天
            day = day + 1;
        } else if (remainder > 14400) {    //4小时内天数不增加，否则加一
            day = day + 1;
        }
        return day;
    }


    private void setRequestData(int type, String requestData, double lat, double lon, String compangy, int cityId, int companyId, String cityName) {
        if (type == 1) {
            tvGetAddress.setText(compangy);
            dataBean.setStartAddr(compangy);
            dataBean.setStartCity(cityId);
            dataBean.setStartCityName(cityName);
            dataBean.setStartCompanyId(companyId);
        } else if (type == 2) {
            tvOutAddress.setText(compangy);
            dataBean.setEndAddr(compangy);
            dataBean.setEndCity(cityId);
            dataBean.setEndCityName(cityName);
            dataBean.setEndCompanyId(companyId);
        }
        onFresh();
    }

    @Override
    public void onRefresh() {
        onFresh();
    }

    /**
     * 获取通用空布局
     *
     * @param mRecyclerView
     * @param imageId
     * @param empty
     * @return
     */
    protected View getEmptyView(RecyclerView mRecyclerView, final int imageId, final String empty) {
        return getHelperView(mRecyclerView, R.layout.select_shop_empty, new OnViewHolder() {
            @Override
            public void helper(ViewHolder helper) {
                if (imageId != -1) {
                    helper.setImageResource(com.ruiwenliu.wrapper.R.id.iv_flag, imageId);
                }
                helper.setText(com.ruiwenliu.wrapper.R.id.tv_tip, empty);


            }
        });
    }
}
