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

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.inter.ImInitListenter;
import com.ruiwenliu.wrapper.util.GpsManager;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.listener.SwitchFragment;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.refresh.IFooterWrapper;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.DisplayUtil;
import com.rv.component.utils.LogUtil;
import com.rv.component.utils.MyUtils;
import com.rv.component.utils.ObservableScrollView;
import com.rv.component.utils.RvCache;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.main.home.adapter.HotCarTypeAdapter;
import com.rv.home.rv.module.ui.main.home.adapter.RVEnthusiastAdapter;
import com.rv.home.rv.module.ui.main.home.adapter.RVTourListAdapter;
import com.rv.home.rv.module.ui.main.home.adapter.RVTourListLabelAdapter;
import com.rv.home.rv.module.ui.main.home.adapter.SelectedEventsAdapter;
import com.rv.home.rv.module.ui.main.home.bean.BeanHomeBanner;
import com.rv.home.rv.module.ui.main.home.bean.CityPickerBean;
import com.rv.home.rv.module.ui.main.home.bean.HomeHotGoodListBean;
import com.rv.home.rv.module.ui.main.home.bean.HomePopularBrigade;
import com.rv.home.rv.module.ui.main.home.bean.HomeRecommendBean;
import com.rv.home.rv.module.ui.main.home.bean.ListsBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.bean.SelectedActivitiesBean;
import com.rv.home.rv.module.ui.main.home.bean.ShopListBean;
import com.rv.home.rv.module.ui.main.home.presenter.HomePresenter;
import com.xxrv.video.activity.TriListActivity;
import com.xxrv.video.bean.circle.DiscoveryDataBean;
import com.yuyife.banner.Banner;
import com.yuyife.banner.BannerConfig;
import com.yuyife.banner.listener.OnBannerListener;
import com.yuyife.banner.loader.ImageLoader;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements ObservableScrollView.ScrollViewListener, SimpleRefreshLayout.OnSimpleRefreshListener, GpsManager.GpsChangeListener {
    @BindView(R2.id.ll_layout_home_renting_a_car)
    LinearLayout llLayoutRentingACar;
    @BindView(R2.id.ll_layout_home_rv_tour)
    LinearLayout llLayoutRvTour;
    @BindView(R2.id.home_banner)
    Banner mineBanner;
    @BindView(R2.id.tv_item_home_rv_tour)
    TextView tvItemRvTour;
    @BindView(R2.id.tv_item_home_renting_a_car)
    TextView tvItemRentingACar;
    @BindView(R2.id.tv_home_get_address)
    TextView headTvGetShop;
    @BindView(R2.id.tv_home_out_address)
    TextView headTvOutShop;
    @BindView(R2.id.tv_home_get_time)
    TextView tvGetTime;
    @BindView(R2.id.tv_home_get_week)
    TextView tvGetWeek;
    @BindView(R2.id.tv_home_day)
    TextView tvDay;
    @BindView(R2.id.tv_home_out_time)
    TextView tvOutTime;
    @BindView(R2.id.tv_home_out_week)
    TextView tvOutWeek;
    @BindView(R2.id.recyclerView_home_content)
    RecyclerView recyclerViewContent;
    @BindView(R2.id.recyclerView_home_activity)
    RecyclerView recyclerViewActivity;
    @BindView(R2.id.recyclerView_home_rvtourlist)
    RecyclerView recyclerViewRvtourlist;
    @BindView(R2.id.recyclerView_home_rvtourlist_title)
    RecyclerView recyclerViewRvtourlistTitle;
    @BindView(R2.id.recyclerView_home_rv_enthusiast)
    RecyclerView recyclerViewRvEnthusiast;
    @BindView(R2.id.tv_home_travel_city_text)
    TextView travelCityText;
    @BindView(R2.id.tv_home_travel_city_layout)
    LinearLayout travelCityLayout;
    @BindView(R2.id.tv_home_search_input)
    TextView searchInput;
    @BindView(R2.id.iv_home_travel_server_image)
    ImageView travelServerImage;
    @BindView(R2.id.tv_home_rv_city)
    TextView tvRvCity;
    @BindView(R2.id.tv_home_rv_hot_label1)
    TextView tvRvHotLabel1;
    @BindView(R2.id.tv_home_rv_hot_label2)
    TextView tvRvHotLabel2;
    @BindView(R2.id.tv_home_rv_hot_label3)
    TextView tvRvHotLabel3;
    @BindView(R2.id.tv_home_hot_rvtour)
    TextView tvHotRvtour;
    @BindView(R2.id.tv_home_hot_entertainment_camp)
    TextView tvHotEntertainmentCamp;
    @BindView(R2.id.tv_home_hot_car_rental)
    TextView tvHotCarRental;
    @BindView(R2.id.tv_home_see_more_popular)
    TextView tvSeeMorePopular;
    @BindView(R2.id.rl_home_item_layout)
    RelativeLayout rlItemLayout;
    @BindView(R2.id.os_scrollview_home)
    ObservableScrollView scrollview;
    @BindView(R2.id.ll_home_item_title)
    LinearLayout llItemTitle;
    @BindView(R2.id.ll_home_item_top)
    LinearLayout llItemTop;
    @BindView(R2.id.ll_home_item_search)
    LinearLayout llItemSearch;
    @BindView(R2.id.refresh_home)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.ll_home_item_hot_rvtour)
    LinearLayout llItemHotRvtour;
    @BindView(R2.id.ll_home_item_hot_entertainment_camp)
    LinearLayout llItemHotEntertainmentCamp;
    @BindView(R2.id.ll_home_item_hot_car_rental)
    LinearLayout llItemHotCarRental;
    @BindView(R2.id.tv_home_hot_rvtour_hint)
    TextView tvHotRvtourHint;
    @BindView(R2.id.tv_home_hot_entertainment_hint)
    TextView tvHotEntertainmentHint;
    @BindView(R2.id.tv_home_hot_car_rental_hint)
    TextView tvHotCarRentalHint;
    @BindView(R2.id.iv_home_travel_city_text_hint)
    ImageView ivTravelCityTextHint;
    @BindView(R2.id.iv_home_search_input_hint)
    ImageView ivSearchInputHint;
    Unbinder unbinder1;


    private ArrayList<String> images = new ArrayList<>();    //图片(默认采用网络地址)
    private List<String> titles = new ArrayList<>();         //图片标题
    private final int TYPE_REQUEST_CITY = 1;//城市列表
    private final int REQUEST_GET_CODE = 10001;  // 取车地址选择请求码
    private final int REQUEST_RETURN_CODE = 10002;  // 换车地址选择请求码


    private String nowCity = "";
    private int getSwitchType;//取车开关类型
    private int outSwitchType;//还车开关类型
    private double latLatitude = 0;
    private double lonLongitude;
    private LatLng mLatLng;//当前城市经纬度

    private String getCompanyName;
    private String outCompanyName;
    private int getCompanyId; // 取车公司id
    private int outCompanyId; // 取车公司id;
    private double getLatitude;
    private double getLongitude;
    private double outLatitude = 0;
    private double outLongitude;
    private int getCityId;//取车城市ID
    private int outCityId;//还车城市ID
    private String getCityName;
    private String outCityName;
    private int vVTourCityId;// 房车游城市ID
    private int mTravelCityId;// 头城市ID
    private OrderDataBean dataBean;
    private long copyDay = 2;//租车天数
    private LocationManager locationManager;
    private GeoCoder geoCoder;

    private List<HomePopularBrigade.DataBean> hotData; //热门标签
    private double rvTourLatitude = 0;
    private double rvTourLongitude;

    private double travelCityLatitude = 0;//头城市
    private double travelCityLongitude = 0;

    private String begDate = "";
    private String endDate = "";

    private String hotType = "2";

    private HotCarTypeAdapter mAdapter;
    private SelectedEventsAdapter mActivityAdapter;
    private RVEnthusiastAdapter mRvEnthusiast;
    private RVTourListAdapter mRvTourAdapter;
    private RVTourListLabelAdapter mRvTourLabelAdapter;

    private int height;

    private int countPage;
    private int mPage;

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


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

    @Override
    protected void initView(Bundle savedInstanceState) {
        GpsManager.getInstance(_mActivity).bindGpsListener(this);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        permissionProcess();
        setBanner();
        Drawable drawable = getResources().getDrawable(R.drawable.icon_day_times);
        drawable.setBounds(0, 0, DisplayUtil.dip2px(getContext(), 25), DisplayUtil.dip2px(getContext(), 5));
        tvDay.setCompoundDrawables(null, null, null, drawable);

        setDefaultTime();
        llItemHotRvtour.setSelected(true);
        tvItemRvTour.setSelected(true);
        hotType = "2";
        tvHotRvtourHint.setTextColor(getResources().getColor(R.color.colorWrite));
        tvHotRvtour.setTextColor(getResources().getColor(R.color.colorWrite));
        tvHotRvtour.getPaint().setFakeBoldText(true);

        ViewTreeObserver observer = rlItemLayout.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rlItemLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = rlItemLayout.getHeight() - 120;
                rlItemLayout.getWidth();
                scrollview.setScrollViewListener(HomeFragment.this);
            }
        });

        mAdapter = new HotCarTypeAdapter();
        recyclerViewContent.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerViewContent.addItemDecoration(new AbSpacesItemDecoration(10));// 分割线。
        recyclerViewContent.setNestedScrollingEnabled(false);
        recyclerViewContent.setAdapter(mAdapter);

        //精选活动
        mActivityAdapter = new SelectedEventsAdapter();
        recyclerViewActivity.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerViewActivity.addItemDecoration(new AbSpacesItemDecoration(10));// 分割线。
        recyclerViewActivity.setNestedScrollingEnabled(false);
        recyclerViewActivity.setAdapter(mActivityAdapter);
        mActivityAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SelectedActivitiesBean.SelectedActivityItem item = (SelectedActivitiesBean.SelectedActivityItem) adapter.getItem(position);
                mPresenter.saveOnclick("3", String.valueOf(item.getId()));
                if (item != null && !TextUtils.isEmpty(item.getUrl()) && !TextUtils.isEmpty(item.getName())) {
                    mPresenter.toTarget(getActivity(), item.getUrl(), item.getName(),String.valueOf(item.getId()));
                }
            }
        });

        //房车发烧友
        mRvEnthusiast = new RVEnthusiastAdapter();
        final StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

        recyclerViewRvEnthusiast.setItemAnimator(null);
        recyclerViewRvEnthusiast.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int[] first = new int[2];
                staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(first);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
                    recyclerView.invalidateItemDecorations();
                }
            }
        });

        recyclerViewRvEnthusiast.setLayoutManager(staggeredGridLayoutManager);
        recyclerViewRvEnthusiast.addItemDecoration(new AbSpacesItemDecoration2(20, 10));// 分割线。
        recyclerViewRvEnthusiast.setNestedScrollingEnabled(false);
        recyclerViewRvEnthusiast.setAdapter(mRvEnthusiast);

        mRvEnthusiast.bindToRecyclerView(recyclerViewRvEnthusiast);
        mRvEnthusiast.setEnableLoadMore(true);
        mRvEnthusiast.disableLoadMoreIfNotFullPage();

        mRvEnthusiast.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (recyclerViewRvEnthusiast != null) {
                    recyclerViewRvEnthusiast.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mPage >= countPage) {
                                mRvEnthusiast.loadMoreEnd();
                            } else {
                                mPage++;
                                loadDisCovery(mPage);
                            }
                        }
                    }, 200);
                }
            }
        }, recyclerViewRvEnthusiast);


//        recyclerViewRvEnthusiast.setLayoutManager(new GridLayoutManager(getContext(), 2));
//        recyclerViewRvEnthusiast.addItemDecoration(new AbSpacesItemDecoration(10));// 分割线。
//        recyclerViewRvEnthusiast.addItemDecoration(new flow(10));
//        recyclerViewRvEnthusiast.setNestedScrollingEnabled(false);
//        recyclerViewRvEnthusiast.setAdapter(mRvEnthusiast);

        //房车游榜单
        mRvTourAdapter = new RVTourListAdapter();
        recyclerViewRvtourlist.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerViewRvtourlist.addItemDecoration(new AbSpacesItemDecoration(10));
        recyclerViewRvtourlist.setNestedScrollingEnabled(false);
        recyclerViewRvtourlist.setAdapter(mRvTourAdapter);

        //  //房车游榜单 标注
        mRvTourLabelAdapter = new RVTourListLabelAdapter();
        recyclerViewRvtourlistTitle.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerViewRvtourlistTitle.addItemDecoration(new AbSpacesItemDecoration(20));
        recyclerViewRvtourlistTitle.setNestedScrollingEnabled(false);
        recyclerViewRvtourlistTitle.setAdapter(mRvTourLabelAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HomeHotGoodListBean.DataBean data = (HomeHotGoodListBean.DataBean) adapter.getItem(position);
                if ("2".equals(hotType)) {
                    //热门旅行
                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_TRAVELDETAILS)
                            .withString("id", data.getId())
                            .withString("name", data.getName())
                            .withString("content", data.getName1())
                            .withString("url", data.getImgUrl())
                            .withDouble("price", Double.valueOf(data.getPrice()))
                            .navigation();
                } else if ("3".equals(hotType)) {
                    //娱乐营地
                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_CAMPDETAIL)
                            .withString("id", data.getId())
                            .withString("longitude", data.getLongitude())
                            .withString("latitude", data.getLatitude())
                            .navigation();
                } else if ("4".equals(hotType)) {
                    //优质车型
                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_DETAILCARPURCHASE)
                            .withString("carId", data.getId())
                            .withString("icon", data.getIcon())
                            .withString("name", data.getName())
                            .withString("keyword", data.getName1())
                            .withInt("score", 0)
                            .withDouble("buyPrice", Double.valueOf(data.getPrice()))
                            .navigation();

                }
            }
        });

        mRvTourLabelAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mRvTourLabelAdapter.setSelectPosition(position);
                recyclerViewRvtourlist.scrollToPosition(position);
            }
        });

        mRvTourAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mRvTourLabelAdapter.setSelectPosition(position);
                recyclerViewRvtourlistTitle.scrollToPosition(position);
                HomePopularBrigade.DataBean beanHot = (HomePopularBrigade.DataBean) adapter.getItem(position);
                ARouter.getInstance().build(Constance.ACTIVITY_URL_POPULARTOURLIST).withString("name", beanHot.getName()).withString("id", beanHot.getId()).navigation();
            }
        });


        //房车发烧友
        mRvEnthusiast.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DiscoveryDataBean item = (DiscoveryDataBean) adapter.getItem(position);
                if (item != null) {
                    if ("2".equals(item.getBody().getType())) {
                        ARouter.getInstance()
                                .build(Constance.ACTIVITY_URL_DETAILPAT)
                                .withString("id", item.getMsgId())
                                .withString("title", item.getBody().getText())
                                .withString("iconUrl", item.getBody().getImages().get(0).getOurl())
                                .withString("userName", item.getNickname())
                                .withString("userUrl", item.getPicUrl())
                                .navigation();
                    } else if ("4".equals(item.getBody().getType())) {
                        List<DiscoveryDataBean> data = new ArrayList<>();
                        data.add(item);
                        startActivity(TriListActivity.getIntent(_mActivity, 0, 0, data, false));
                    }
                }
            }
        });
    }

    /**
     * 设置默认时间
     */
    private void setDefaultTime() {
        String time = DateUtils.formatDate28(DateUtils.timestampToString1(DateUtils.getCurTimeMillis()), 2);
        String hh = DateUtils.formatDate21(time);
        String mm = DateUtils.formatDate22(time);
        String begTime = "";
        if (Double.valueOf(mm) > 30) {   //判断当前分钟是否已经超过30，如果超过了取整加30分钟
            begTime = DateUtils.formatDate19(hh + ":30");
        } else {
            begTime = hh + ":30";
        }

        if (DateUtils.formatDate20(begTime) > DateUtils.formatDate20("22:30")) {   //如果当前时间大于 22：30，日期往后加一，时间改成早上8：00
            begDate = MyUtils.getFetureDate(1) + " " + "08:30";
            endDate = MyUtils.getFetureDate(3) + " " + "08:30";
        } else {
            begDate = MyUtils.getFetureDate(0) + " " + begTime;
            endDate = MyUtils.getFetureDate(2) + " " + begTime;
        }

        tvGetTime.setText(DateUtils.formatDate66(begDate));
        tvGetWeek.setText("周" + MyUtils.getWeek(DateUtils.formatDate16(begDate)));

        tvOutTime.setText(DateUtils.formatDate66(endDate));
        tvOutWeek.setText("周" + MyUtils.getWeek(DateUtils.formatDate16(endDate)));

        copyDay = getCountDay(begDate, endDate);
        tvDay.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
    }


    @Override
    public void onRefresh() {

        loadBannerData();
        hotData();
        recommendGood(hotType);
        getSelectedActivities();
        onFreshLoadDisCovery();
    }

    @Override
    public void gpsChange(boolean b) {
        if (b) {
            initGps();
            initCity();
        }
    }

    public class AbSpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public AbSpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            //注释这两行是为了上下间距相同
//        if(parent.getChildAdapterPosition(view)==0){
            outRect.top = space;
        }
    }

    public class AbSpacesItemDecoration2 extends RecyclerView.ItemDecoration {

        private int left;
        private int right;

        public AbSpacesItemDecoration2(int left, int right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();

            if (lp.getSpanIndex() % 2 == 0) {
                outRect.left = left;
                outRect.right = right;
            } else {
                outRect.left = right;
                outRect.right = left;
            }
            outRect.top = left;
        }
    }

    public class flow extends RecyclerView.ItemDecoration {

        private int space;

        public flow(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            if (parent.getChildAdapterPosition(view) % 2 == 0) {
                outRect.top = 40;
            } else {
                outRect.top = space;
            }

            outRect.bottom = space;

            outRect.left = space;
            outRect.right = space;
        }
    }

    private void getSelectedActivities() {

        Map<String, Object> header = new HashMap<>();
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            header.put("Authorization", OkGoUtil.getToken());
        }
        mPresenter.getDataHead(RvFrameConfig.HOST, 4, ApiConfig.HTTP_URL_SELECTED_ACTIVITIES, SelectedActivitiesBean.class, header, false);
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {
        loadBannerData();
        hotData();
        recommendGood(hotType);
        getSelectedActivities();
        onFreshLoadDisCovery();
    }

    /**
     * 刷新
     */
    private void onFreshLoadDisCovery() {
        mPage = 1;
        loadDisCovery(mPage);
    }

    /**
     * 房车发烧友
     */
    private void loadDisCovery(int page) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", page);
        mPresenter.postData(RvFrameConfig.HOST, 5, ApiConfig.RVENTHUSIAST_HOTMSG_LIST, HomeRecommendBean.class, map, headMap, false);
    }

    /**
     * 获取轮播图
     */
    private void loadBannerData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "0");
        mPresenter.getData(3, ApiConfig.HTTP_URL_FIND_BANNERLIST, BeanHomeBanner.class, map, false);
    }


    /**
     * 推荐商品   type 2-旅游 ；3-营地
     */
    private void recommendGood(String type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", type);
        map.put("limit ", "4");
        mPresenter.getData(2, ApiConfig.QUERY_HOT_GOODLIST, HomeHotGoodListBean.class, map, false);
    }

    /**
     * 热门旅游
     */
    private void hotData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("hot", "1");
        map.put("page", "1");
        map.put("limit", "50");
        mPresenter.getData(1, ApiConfig.QUERY_HOT_LIST, HomePopularBrigade.class, map, false);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        mSimpleRefreshLayout.setPullDownEnable(true);
        switch (requestType) {
            case 0:
                processData((ShopListBean) result);
                break;
            case 1:
                setHotData((HomePopularBrigade) result);
                break;
            case 2:
                setRecommendGood((HomeHotGoodListBean) result);
                break;
            case 3:
                bannerData((BeanHomeBanner) result);
                break;
            case 4:
                SelectedActivitiesBean bean = (SelectedActivitiesBean) result;
                if (bean != null && bean.getData() != null && bean.getData().size() > 0) {
                    mActivityAdapter.setNewData(bean.getData());
                }
                break;
            case 5:
                setRecommend((HomeRecommendBean) result);
                break;
        }
    }

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

    private void setRecommend(HomeRecommendBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getPageSize();
            mRvEnthusiast.setNewData(bean.getData().getList());
            if (bean.getData().getTotalCount() == 0) {
//                mRvEnthusiast.setEmptyView(getEmptyView(rvContent, -1, "暂无推荐数据"));
                mRvEnthusiast.notifyDataSetChanged();
            }
        } else {
            mRvEnthusiast.addData(bean.getData().getList());
            mRvEnthusiast.loadMoreComplete();
        }
    }

    private void setRecommendGood(HomeHotGoodListBean data) {
        mAdapter.setType(hotType);
        mAdapter.setNewData(data.getData());
    }

    private void setHotData(HomePopularBrigade data) {
        hotData = data.getData();
        if (data != null && hotData.size() > 2) {
            tvRvHotLabel1.setText(hotData.get(0).getName());
            tvRvHotLabel2.setText(hotData.get(1).getName());
            tvRvHotLabel3.setText(hotData.get(2).getName());
        }

        mRvTourAdapter.setNewData(hotData);
        mRvTourLabelAdapter.setNewData(hotData);
    }


    @OnClick({R2.id.tv_home_travel_city_layout, R2.id.ll_home_item_search, R2.id.tv_item_home_rv_tour, R2.id.tv_item_home_renting_a_car,
            R2.id.tv_home_get_address, R2.id.tv_home_out_address, R2.id.ll_home_item_select_data, R2.id.tv_home_select_car,
            R2.id.ll_home_item_rv_city, R2.id.tv_home_book_now, R2.id.ll_home_item_rv_hot_label1, R2.id.ll_home_item_rv_hot_label2, R2.id.ll_home_item_rv_hot_label3,
            R2.id.ll_home_item_hot_rvtour, R2.id.ll_home_item_hot_entertainment_camp, R2.id.ll_home_item_hot_car_rental, R2.id.tv_home_see_more_popular,
            R2.id.ll_home_item_top, R2.id.iv_home_travel_server_image, R2.id.tv_home_car_rental_guide, R2.id.ll_home_item_activity_all, R2.id.ll_rent, R2.id.ll_return, R2.id.cardview})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_home_travel_city_layout) {
            //选择城市
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 4)
                    .withString("mNowCity", travelCityText.getText().toString())
                    .withInt("mCityId", mTravelCityId)
                    .navigation(getActivity(), TYPE_REQUEST_CITY);

        } else if (id == R.id.ll_home_item_search) {
            //搜索

            String city = tvRvCity.getText().toString().trim();
            if (!TextUtils.isEmpty(city)) {
                String hint = city.substring(city.length() - 1);
                if ("市".equals(hint)) {  //判断后面是否是带市结尾的，去掉
                    city = city.substring(0, city.length() - 1);
                }
            }

            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_TRAVELSEARCH)
                    .withDouble("latLatitude", 0)
                    .withDouble("lonLongitude", 0)
                    .withString("city", city)
                    .navigation();

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

            tvItemRvTour.setSelected(true);
            tvItemRentingACar.setSelected(false);
            llLayoutRentingACar.setVisibility(View.VISIBLE);
            llLayoutRvTour.setVisibility(View.GONE);
        } else if (id == R.id.tv_item_home_renting_a_car) {

            tvItemRvTour.setSelected(false);
            tvItemRentingACar.setSelected(true);
            llLayoutRentingACar.setVisibility(View.GONE);
            llLayoutRvTour.setVisibility(View.VISIBLE);
        } else if (id == R.id.tv_home_get_address || id == R.id.ll_rent) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat", latLatitude)
                    .withDouble("mLon", lonLongitude)
                    .withString("cityName", TextUtils.isEmpty(getCityName) ? nowCity : getCityName)
                    .withInt("shopType", 1)
                    .navigation(_mActivity, TYPE_REQUEST_CITY);
//            startActivityForResult(SelectShopActivity.getIntent(getActivity(), 1, "", , latLatitude, lonLongitude), TYPE_REQUEST_CITY);
        } else if (id == R.id.ll_return || id == R.id.tv_home_out_address) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat", latLatitude)
                    .withDouble("mLon", lonLongitude)
                    .withString("cityName", TextUtils.isEmpty(outCityName) ? nowCity : outCityName)
                    .withInt("shopType", 2)
                    .navigation(_mActivity, TYPE_REQUEST_CITY);
//            startActivityForResult(SelectShopActivity.getIntent(getActivity(), 2, "", TextUtils.isEmpty(outCityName) ? nowCity : outCityName, latLatitude, lonLongitude), TYPE_REQUEST_CITY);
        } else if (id == R.id.ll_home_item_select_data) {
            //选择日期
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CALENDAR)
                    .withString("begDate", begDate)
                    .withString("endDate", endDate)
                    .navigation(_mActivity, 108);

        } else if (id == R.id.tv_home_select_car) {
            //租房车 立即选车
            if (copyDay < 1) {
                showToast(getContext().getString(R.string.rv_day_toast));
                return;
            }

            if (TextUtil.isEmpty(headTvGetShop.getText().toString().trim()) || TextUtil.isEmpty(headTvOutShop.getText().toString().trim())) {
                showToast("请选择取/还车地址");
                return;
            }

            sendData(getCityName,
                    getCompanyName,
                    outCityName,
                    outCompanyName,
                    begDate, endDate, copyDay,
                    begDate,
                    endDate
            );
        } else if (id == R.id.ll_home_item_rv_city) {
            //房车游选择城市
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 3)
                    .withString("mNowCity", tvRvCity.getText().toString())
                    .withInt("mCityId", vVTourCityId)
                    .navigation(getActivity(), TYPE_REQUEST_CITY);


        } else if (id == R.id.tv_home_book_now) {
            //房车游 立即预定

            geoCoder.geocode(new GeoCodeOption()
                    .city(tvRvCity.getText().toString())
                    .address(tvRvCity.getText().toString()));


            String city = tvRvCity.getText().toString().trim();
            if (!TextUtils.isEmpty(city)) {
                String hint = city.substring(city.length() - 1);
                if ("市".equals(hint)) {  //判断后面是否是带市结尾的，去掉
                    city = city.substring(0, city.length() - 1);
                }
            }

            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_TRAVELSEARCH)
                    .withDouble("latLatitude", 0)
                    .withDouble("lonLongitude", 0)
                    .withString("city", city)
                    .navigation();

        } else if (id == R.id.ll_home_item_rv_hot_label1) {
            //热门标签1
            if (hotData != null && hotData.size() > 0) {
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_POPULARTOURLIST)
                        .withString("name", hotData.get(0).getName())
                        .withString("id", hotData.get(0).getId())
                        .navigation();
            }

        } else if (id == R.id.ll_home_item_rv_hot_label2) {
            //热门标签2
            if (hotData != null && hotData.size() > 1) {
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_POPULARTOURLIST)
                        .withString("name", hotData.get(1).getName())
                        .withString("id", hotData.get(1).getId())
                        .navigation();
            }

        } else if (id == R.id.ll_home_item_rv_hot_label3) {
            //热门标签3
            if (hotData != null && hotData.size() > 2) {
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_POPULARTOURLIST)
                        .withString("name", hotData.get(2).getName())
                        .withString("id", hotData.get(2).getId())
                        .navigation();
            }

        } else if (id == R.id.ll_home_item_hot_rvtour) {
            //热门旅行

            llItemHotRvtour.setSelected(true);
            llItemHotEntertainmentCamp.setSelected(false);
            llItemHotCarRental.setSelected(false);
            tvHotRvtourHint.setTextColor(getResources().getColor(R.color.colorWrite));
            tvHotRvtour.setTextColor(getResources().getColor(R.color.colorWrite));
            tvHotEntertainmentHint.setTextColor(getResources().getColor(R.color.textGray));
            tvHotEntertainmentCamp.setTextColor(getResources().getColor(R.color.textGray));
            tvHotCarRentalHint.setTextColor(getResources().getColor(R.color.textGray));
            tvHotCarRental.setTextColor(getResources().getColor(R.color.textGray));

            tvHotRvtour.getPaint().setFakeBoldText(true);
            tvHotEntertainmentCamp.getPaint().setFakeBoldText(false);
            tvHotCarRental.getPaint().setFakeBoldText(false);
            tvSeeMorePopular.setText("更多热门旅行线路");
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
            recommendGood("2");
            hotType = "2";

        } else if (id == R.id.ll_home_item_hot_entertainment_camp) {
            //娱乐营地
            llItemHotRvtour.setSelected(false);
            llItemHotEntertainmentCamp.setSelected(true);
            llItemHotCarRental.setSelected(false);
            tvHotRvtourHint.setTextColor(getResources().getColor(R.color.textGray));
            tvHotRvtour.setTextColor(getResources().getColor(R.color.textGray));
            tvHotEntertainmentHint.setTextColor(getResources().getColor(R.color.colorWrite));
            tvHotEntertainmentCamp.setTextColor(getResources().getColor(R.color.colorWrite));
            tvHotCarRentalHint.setTextColor(getResources().getColor(R.color.textGray));
            tvHotCarRental.setTextColor(getResources().getColor(R.color.textGray));

            tvHotRvtour.getPaint().setFakeBoldText(false);
            tvHotEntertainmentCamp.getPaint().setFakeBoldText(true);
            tvHotCarRental.getPaint().setFakeBoldText(false);
            tvSeeMorePopular.setText("更多娱乐营地");
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
            recommendGood("3");
            hotType = "3";
        } else if (id == R.id.ll_home_item_hot_car_rental) {
            //购房车
            llItemHotRvtour.setSelected(false);
            llItemHotEntertainmentCamp.setSelected(false);
            llItemHotCarRental.setSelected(true);
            tvHotRvtourHint.setTextColor(getResources().getColor(R.color.textGray));
            tvHotRvtour.setTextColor(getResources().getColor(R.color.textGray));
            tvHotEntertainmentHint.setTextColor(getResources().getColor(R.color.textGray));
            tvHotEntertainmentCamp.setTextColor(getResources().getColor(R.color.textGray));
            tvHotCarRentalHint.setTextColor(getResources().getColor(R.color.colorWrite));
            tvHotCarRental.setTextColor(getResources().getColor(R.color.colorWrite));

            tvHotRvtour.getPaint().setFakeBoldText(false);
            tvHotEntertainmentCamp.getPaint().setFakeBoldText(false);
            tvHotCarRental.getPaint().setFakeBoldText(true);

            tvSeeMorePopular.setText("更多优质车型");
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
            recommendGood("4");
            hotType = "4";

        } else if (id == R.id.tv_home_see_more_popular) {
            //查看更多热门
            if ("2".equals(hotType)) {
                //热门旅行
                SwitchFragment.sChangeFragment.changge(1);

            } else if ("3".equals(hotType)) {
                //娱乐营地
                SwitchFragment.sChangeFragment.changge(2);

            } else if ("4".equals(hotType)) {
                //优质车型
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CARPURCHASELIST)
                        .navigation();
            }
        } else if (id == R.id.ll_home_item_top) {
            scrollview.fullScroll(View.FOCUS_UP);
        } else if (id == R.id.iv_home_travel_server_image) {
            if (isLogin()) {

                if (_mActivity instanceof ImInitListenter && !((ImInitListenter) _mActivity).isBindService()) {
                    showToast("Im初始化中...");
                    return;
                }

                ComponentName name = new ComponentName(getActivity(), "com.rv.im.CustomerListActivity");
                Intent intent = new Intent();
                intent.putExtra("login_user_id", Cookie.getStringValue(getContext(), SPConstance.USER_JSON_IMUSERID));
                intent.setComponent(name);
                startActivity(intent);
            }
        } else if (id == R.id.tv_home_car_rental_guide) {
            //租车指南
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "租车指南")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 1)
                    .navigation();

        } else if (id == R.id.ll_home_item_activity_all) {
            showToast("亲，该功能还在开发中。。。");
        } else if (id == R.id.cardview) {
            return;
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            startActivity(LoginRvActivity.getIntent(_mActivity, 0));
            return false;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (CODE_REQUEST_POISITION == requestCode) {
            permissionProcess();
            return;
        }

        List<Fragment> fragments = getChildFragmentManager().getFragments();
        ArrayList<HomeFragment> list = new ArrayList<>();
        if (fragments == null || fragments.isEmpty()) {
            list.add(HomeFragment.getInstance(0));
        } else {
            for (Fragment fragment : fragments) {
                if (fragment instanceof HomeFragment) {
                    list.add((HomeFragment) fragment);
                }
            }
        }

        if (resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", 1);
            String requestData = data.getStringExtra("location");
            switch (requestCode) {
                case TYPE_REQUEST_CITY://城市列表
                    if (type == 1) {
                        getCompanyName = data.getStringExtra("company");
                        getCompanyId = data.getIntExtra("company_id", 1);
                        getCityName = requestData;
                        getCityId = data.getIntExtra("id", 0);
                        StringBuffer buffer = new StringBuffer();
                        if (!TextUtils.isEmpty(getCompanyName)) {
                            buffer.append(getCompanyName);
                        }
                        if (!TextUtils.isEmpty(getCityName)) {
                            buffer.append("(").append(getCityName).append(")");
                        }
                        if (headTvGetShop != null) {
                            if (buffer.length() > 0) {
                                headTvGetShop.setText(buffer.toString());
                            } else {
                                headTvGetShop.setText("");
                            }
                        }
                        getLatitude = data.getDoubleExtra("latitude", 0);
                        getLongitude = data.getDoubleExtra("longitude", 0);
                        setRequestData(type, requestData, getLatitude, getLongitude);
                    } else if (type == 2) {
                        outCompanyName = data.getStringExtra("company");
                        outCompanyId = data.getIntExtra("company_id", 1);
                        outCityName = requestData;
                        outCityId = data.getIntExtra("id", 0);
                        StringBuffer buffer = new StringBuffer();
                        if (!TextUtils.isEmpty(outCompanyName)) {
                            buffer.append(outCompanyName);
                        }
                        if (!TextUtils.isEmpty(outCityName)) {
                            buffer.append("(").append(outCityName).append(")");
                        }
                        if (headTvOutShop != null) {
                            if (buffer.length() > 0) {
                                headTvOutShop.setText(buffer.toString());
                            } else {
                                headTvOutShop.setText("");
                            }
                        }
                        outLatitude = data.getDoubleExtra("latitude", 0);
                        outLongitude = data.getDoubleExtra("longitude", 0);
                        setRequestData(type, requestData, outLatitude, outLongitude);
                    } else if (type == 3) {
                        if (tvRvCity != null) {
                            tvRvCity.setText("");
                        }
                        vVTourCityId = data.getIntExtra("id", 0);
                        setRequestData(type, requestData, 0, 0);
                    } else if (type == 4) {
                        if (travelCityText != null) {
                            travelCityText.setText("");
                        }
                        mTravelCityId = data.getIntExtra("id", 0);
                        getCityId = outCityId = mTravelCityId;
                        getCityName = outCityName = requestData;
                        vVTourCityId = mTravelCityId;
                        setRequestData(type, requestData, 0, 0);
                    }
                    break;
            }
        } else if (resultCode == 200 && requestCode == 108) {
            begDate = data.getStringExtra("begDate");
            endDate = data.getStringExtra("endDate");

            copyDay = getCountDay(begDate, endDate);  //天数

//            copyDay = DateUtils.compareDateDay(endDate, begDate) + 1;
            if (tvGetTime != null) {
                tvGetTime.setText(DateUtils.formatDate66(begDate));
            }
            if (tvOutTime != null) {
                tvOutTime.setText(DateUtils.formatDate66(endDate));
            }
            if (tvGetWeek != null) {
                tvGetWeek.setText("周" + MyUtils.getWeek(begDate));
            }
            if (tvOutWeek != null) {
                tvOutWeek.setText("周" + MyUtils.getWeek(endDate));
            }
            if (tvDay != null) {
                tvDay.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
            }
        }
    }

    /**
     * 计算天数
     *
     * @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;
    }


    /**
     * 设置返回结果参数
     *
     * @param type
     * @param data
     * @param lat
     * @param lon
     */
    private void setRequestData(int type, String data, double lat, double lon) {
        switch (type) {
            case 1:
//                tvGet.setText(data);
                break;
            case 2:
//                tvOut.setText(data);
                break;
            case 3:
                rvTourLatitude = lat;
                rvTourLongitude = lon;
                if (tvRvCity != null && !TextUtils.isEmpty(data)) {
                    tvRvCity.setText(data);
                }
                break;
            case 4:
                if (travelCityText != null && !TextUtils.isEmpty(data))
                    travelCityText.setText(data);
//                headTvGetCity.setText(data);
//                headTvOutCity.setText(data);
                if (tvRvCity != null && !TextUtils.isEmpty(data)) {
                    tvRvCity.setText(data);
                }
                getShopList(false);
//                geoCoder.geocode(new GeoCodeOption()
//                        .city(data)
//                        .address(data));
                break;
        }
    }

    private List<BeanHomeBanner.DataBean> listsBanners = new ArrayList<>();

    private void bannerData(BeanHomeBanner data) {
        if (data != null) {
            listsBanners.clear();
            titles.clear();
            images.clear();
            listsBanners.addAll(data.getData());
            for (int i = 0; i < data.getData().size(); i++) {
                images.add(data.getData().get(i).getCover());
                titles.add("");
            }
        }
        setBanner();

    }


    private void setBanner() {
        mineBanner.isAutoPlay(true)
                .setBannerTitles(titles)
                .setImages(images)
                .setDelayTime(3000)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {

                        GlideManager.getInstance(context).loadImage2(path, imageView);
                    }
                })
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {

                        LogUtil.d("position=" + position);

                        if (listsBanners.size() > 0) {
                            BeanHomeBanner.DataBean bean = listsBanners.get(position);
                            mPresenter.saveOnclick("2", bean.getId());
                            if (bean != null && !TextUtils.isEmpty(bean.getUrl())) {
                                mPresenter.toTarget(getActivity(), bean.getUrl(), bean.getTitle(),bean.getId());
                            }
                        }

                       /* if (localImages != null && localImages.size() > 0) {
                            Bundle bundle = new Bundle();
                            bundle.putInt(ActivityImageBrowseInt.KEY_BACKGROUND, R.color.colorPrimary);
                            bundle.putIntegerArrayList(ActivityImageBrowseInt.KEY_IMAGE, (ArrayList<Integer>) localImages);
                            IntentUtil.startActivity(_mActivity, ActivityImageBrowseInt.class, bundle);
                        }*/

                    }
                })
                .start();

        mineBanner.updateBannerStyle(BannerConfig.CIRCLE_INDICATOR);
    }

    /**
     * 处理最近门店请求结果
     *
     * @param bean
     */
    private void processData(ShopListBean bean) {
        if (bean.getData() != null && bean.getData().getTotalCount() > 0) {
            if (headTvGetShop != null) {
                getCompanyName = bean.getData().getData().get(0).getName();
                StringBuffer buffer = new StringBuffer();
                if (!TextUtils.isEmpty(getCompanyName)) {
                    buffer.append(getCompanyName);
                }
                if (!TextUtils.isEmpty(getCityName)) {
                    buffer.append("(").append(getCityName).append(")");
                }

                if (buffer != null && buffer.length() > 0) {
                    headTvGetShop.setText(buffer.toString());
                } else {
                    headTvGetShop.setText("");
                }
                headTvGetShop.setTextColor(_mActivity.getResources().getColor(R.color.colorMain));
                getLatitude = bean.getData().getData().get(0).getLatitude();
                getLongitude = bean.getData().getData().get(0).getLongitude();
                getCompanyId = bean.getData().getData().get(0).getId();
            }

            if (headTvOutShop != null) {

                outCompanyName = bean.getData().getData().get(0).getName();
                StringBuffer buffer = new StringBuffer();
                if (!TextUtils.isEmpty(outCompanyName)) {
                    buffer.append(outCompanyName);
                }
                if (!TextUtils.isEmpty(outCityName)) {
                    buffer.append("(").append(outCityName).append(")");
                }
                if (buffer != null && buffer.length() > 0) {
                    headTvOutShop.setText(buffer.toString());
                } else {
                    headTvOutShop.setText("");
                }
                headTvOutShop.setTextColor(_mActivity.getResources().getColor(R.color.colorMain));
                outLatitude = bean.getData().getData().get(0).getLatitude();
                outLongitude = bean.getData().getData().get(0).getLongitude();
                outCompanyId = bean.getData().getData().get(0).getId();
            }
        } else {
            getCompanyName = "";
            headTvGetShop.setText(getCompanyName);
            getLatitude = 0;
            getLongitude = 0;
            outCompanyName = "";
            headTvOutShop.setText(outCompanyName);
            outLatitude = 0;
            outLongitude = 0;
        }

    }

    /**
     * 获取门店列表
     */
    private void getShopList(boolean type) {
        int addrCity = 0;
        if (type) {
            String json = UtilsManager.getInstance().getJson(getContext(), "city.json");
            CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);
            for (CityPickerBean.CityBean cityBean : bean.getCity()) {
                for (ListsBean lsBean : cityBean.getLists()) {
                    if (!TextUtils.isEmpty(nowCity)) {
                        if (nowCity.equals(lsBean.getName())) {
                            addrCity = lsBean.getId();
                        }
                    }
                }
            }
        } else {
            addrCity = mTravelCityId;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", 1);
        map.put("limit", 1);
        map.put("addrCity", String.valueOf(addrCity));
        mPresenter.getData(RvFrameConfig.VEHICLE_POST, 0, ApiConfig.HTTP_URL_SHOP_LIST, ShopListBean.class, map, false);
    }

    /**
     * 传参
     *
     * @param starCity
     * @param starAddress
     * @param endCity
     * @param endAddress
     * @param getTime
     * @param outTime
     * @param day
     * @param startTime
     * @param endTime
     */
    private void sendData(String starCity, String starAddress, String endCity, String endAddress, String getTime, String outTime, long day, String startTime, String endTime) {
        if (dataBean == null) {
            dataBean = new OrderDataBean();
        }
        if (getCityId > 0) {
            dataBean.setStartCity(getCityId);
        }
        if (outCityId > 0) {
            dataBean.setEndCity(outCityId);
        } else {
            String json = UtilsManager.getInstance().getJson(getContext(), "city.json");
            CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);
            for (CityPickerBean.CityBean cityBean : bean.getCity()) {
                for (ListsBean lsBean : cityBean.getLists()) {
                    if (!TextUtils.isEmpty(starCity) && starCity.equals(lsBean.getName())) {
                        dataBean.setStartCity(lsBean.getId());
                    }

                    if (!TextUtils.isEmpty(endCity) && endCity.equals(lsBean.getName())) {
                        dataBean.setEndCity(lsBean.getId());
                    }
                }
            }
        }
        dataBean.setDayNum(Integer.valueOf(day + ""));
        dataBean.setStartCityName(starCity);
        dataBean.setStartAddr(starAddress);
        dataBean.setStartTime(DateUtils.StringToTimeMillis2(getTime));
        dataBean.setEndTime(DateUtils.StringToTimeMillis2(outTime));
        dataBean.setEndCityName(endCity);
        dataBean.setEndCompanyId(outCompanyId);
        dataBean.setEndAddr(endAddress);
        dataBean.setDriverType(2);
        dataBean.setStartCompanyId(getCompanyId);
        startActivity(CarRentalListActivity.getIntent(getContext(), latLatitude, lonLongitude, outLatitude, outLongitude, false, dataBean, startTime, endTime));
    }


    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= height) {
            Log.i("homeFragment", "onScrollChanged: " + y);
            Log.i("homeFragment", "height: " + height);
            float scale = (float) y / height;
            float alpha = (255 * scale);
            llItemTop.setVisibility(View.GONE);
            //只是layout背景透明(仿知乎滑动效果)
            llItemSearch.setBackground(getResources().getDrawable(R.drawable.shape_rv_textview_home_translucent));
            travelCityText.setTextColor(getResources().getColor(R.color.colorWrite));

            travelServerImage.setImageResource(R.drawable.rv_rentingcar_icon_service_white);
            ivTravelCityTextHint.setImageResource(R.drawable.rv_common_icon_up_arrow2);
            ivSearchInputHint.setImageResource(R.drawable.rv_common_icon_search2);
            searchInput.setHintTextColor(getResources().getColor(R.color.colorWrite));
            if (y <= 3) {
                llItemTitle.setBackgroundColor(Color.argb(0, 0, 0, 0));
            } else {
                llItemTitle.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
            }
        } else {
            llItemTop.setVisibility(View.VISIBLE);
            llItemSearch.setBackground(getResources().getDrawable(R.drawable.shape_rv_textview_home_search));
            travelServerImage.setImageResource(R.drawable.rentingcar_icon_service_orangeorange);
            travelCityText.setTextColor(getResources().getColor(R.color.colorMain));
            ivTravelCityTextHint.setImageResource(R.drawable.rv_common_icon_up_arrow);
            ivSearchInputHint.setImageResource(R.drawable.rv_common_icon_search);
            searchInput.setHintTextColor(getResources().getColor(R.color.text_Gray));
            llItemTitle.setBackgroundColor(Color.argb(255, 255, 255, 255));
        }
    }

    /**
     * 定位权限处理
     */
    @SuppressLint("CheckResult")
    private void permissionProcess() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(getActivity()).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(aBoolean -> {
                if (aBoolean == true) {
                    initGps();
                    initCity();
                } else {
                    new AlertDialog.Builder(_mActivity).setTitle("需要定位权限")
                            .setMessage("位置权限已关闭，开启以便滴房车正常使用")
                            .setNegativeButton("取消", (dialogInterface, i) -> {
                                _mActivity.finish();
                                dialogInterface.dismiss();
                            })
                            .setPositiveButton("设置", (dialogInterface, i) -> {
                                Intent in = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                        .setData(Uri.fromParts("package", _mActivity.getPackageName(), null));
                                startActivityForResult(in, CODE_REQUEST_POISITION);
                                dialogInterface.dismiss();
                            }).setCancelable(false).show();
                }
            });
        } else {
            initGps();
            initCity();
        }
    }

    private void initCity() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                } else {
                    rvTourLatitude = result.getLocation().latitude;
                    rvTourLongitude = result.getLocation().longitude;
                }
                //获取地理编码结果
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                } else {
                    rvTourLatitude = result.getLocation().latitude;
                    rvTourLongitude = result.getLocation().longitude;
                }
            }
        });
    }

    /**
     * 初始化定位
     */
    public void initGps() {
        locationManager = new LocationManager(getContext());
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                //以下只列举部分获取经纬度相关（常用）的结果信息
                //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

                //获取定位精度，默认值为0.0f
                float radius = location.getRadius();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                String coorType = location.getCoorType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
                int errorCode = location.getLocType();
//                setGpsContent("count=:",String.valueOf(count));
//                setGpsContent("latitude:",String.valueOf(location.getLatitude()));
//                setGpsContent("longitude:",String.valueOf(location.getLongitude()));
//                setGpsContent("城市:",location.getCity());
//                setGpsContent("街道:",location.getAddrStr());
//                setGpsContent("当前位置:",location.getLocationDescribe());
                latLatitude = location.getLatitude();
                lonLongitude = location.getLongitude();
                mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                getCityId = 0;
                outCityId = 0;
                getCityName = outCityName = location.getCity();
                tvRvCity.setText(location.getCity());
                travelCityText.setText(location.getCity());
                rvTourLatitude = latLatitude;
                rvTourLongitude = lonLongitude;
                getCityName = outCityName = nowCity = location.getCity();
                locationManager.stopLocation();
                getShopList(true);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        GpsManager.getInstance(_mActivity).unbindGpsListener(this);
    }

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