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

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.Switch;
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.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
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.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.LogUtil;
import com.rv.component.utils.MyUtils;
import com.rv.component.utils.ObservableScrollView;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.WebActivity;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
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.ListsBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.bean.ShopListBean;
import com.yuyife.banner.Banner;
import com.yuyife.banner.BannerConfig;
import com.yuyife.banner.listener.OnBannerListener;
import com.yuyife.banner.loader.ImageLoader;

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;
import io.reactivex.functions.Consumer;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment<CommonPresenter> implements ObservableScrollView.ScrollViewListener, SimpleRefreshLayout.OnSimpleRefreshListener {
    Unbinder unbinder;
    @BindView(R2.id.ll_layout_renting_a_car)
    LinearLayout llLayoutRentingACar;
    @BindView(R2.id.ll_layout_rv_tour)
    LinearLayout llLayoutRvTour;
    @BindView(R2.id.mine_banner)
    Banner mineBanner;
    @BindView(R2.id.tv_item_rv_tour)
    TextView tvItemRvTour;
    @BindView(R2.id.tv_item_renting_a_car)
    TextView tvItemRentingACar;
    @BindView(R2.id.tv_get_city)
    TextView headTvGetCity;
    @BindView(R2.id.tv_get_address)
    TextView headTvGetShop;
    @BindView(R2.id.switch_get)
    Switch switchGet;
    @BindView(R2.id.tv_out_city)
    TextView headTvOutCity;
    @BindView(R2.id.tv_out_address)
    TextView headTvOutShop;
    @BindView(R2.id.switch_out)
    Switch switchOut;
    @BindView(R2.id.tv_get_time)
    TextView tvGetTime;
    @BindView(R2.id.tv_get_week)
    TextView tvGetWeek;
    @BindView(R2.id.tv_day)
    TextView tvDay;
    @BindView(R2.id.tv_out_time)
    TextView tvOutTime;
    @BindView(R2.id.tv_out_week)
    TextView tvOutWeek;
    @BindView(R2.id.recyclerView_content)
    RecyclerView recyclerViewContent;
    @BindView(R2.id.recyclerView_activity)
    RecyclerView recyclerViewActivity;
    @BindView(R2.id.recyclerView_rvtourlist)
    RecyclerView recyclerViewRvtourlist;
    @BindView(R2.id.recyclerView_rvtourlist_title)
    RecyclerView recyclerViewRvtourlistTitle;
    //    @BindView(R2.id.recyclerView_rv_enthusiast)
//    RecyclerView recyclerViewRvEnthusiast;
    @BindView(R2.id.travel_city_text)
    TextView travelCityText;
    @BindView(R2.id.travel_city_layout)
    LinearLayout travelCityLayout;
    @BindView(R2.id.search_input)
    TextView searchInput;
    @BindView(R2.id.travel_server_image)
    ImageView travelServerImage;
    @BindView(R2.id.tv_rv_city)
    TextView tvRvCity;
    @BindView(R2.id.tv_book_now)
    TextView tvBookNow;
    @BindView(R2.id.tv_rv_hot_label1)
    TextView tvRvHotLabel1;
    @BindView(R2.id.tv_rv_hot_label2)
    TextView tvRvHotLabel2;
    @BindView(R2.id.tv_rv_hot_label3)
    TextView tvRvHotLabel3;
    @BindView(R2.id.tv_hot_rvtour)
    TextView tvHotRvtour;
    @BindView(R2.id.tv_hot_entertainment_camp)
    TextView tvHotEntertainmentCamp;
    @BindView(R2.id.tv_hot_car_rental)
    TextView tvHotCarRental;
    @BindView(R2.id.tv_see_more_popular)
    TextView tvSeeMorePopular;
    @BindView(R2.id.rl_item_layout)
    RelativeLayout rlItemLayout;
    @BindView(R2.id.scrollview)
    ObservableScrollView scrollview;
    @BindView(R2.id.ll_item_title)
    LinearLayout llItemTitle;
    @BindView(R2.id.ll_item_top)
    LinearLayout llItemTop;
    @BindView(R2.id.ll_item_search)
    LinearLayout llItemSearch;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.ll_item_hot_rvtour)
    LinearLayout llItemHotRvtour;
    @BindView(R2.id.ll_item_hot_entertainment_camp)
    LinearLayout llItemHotEntertainmentCamp;
    @BindView(R2.id.ll_item_hot_car_rental)
    LinearLayout llItemHotCarRental;
    @BindView(R2.id.tv_hot_rvtour_hint)
    TextView tvHotRvtourHint;
    @BindView(R2.id.tv_hot_entertainment_hint)
    TextView tvHotEntertainmentHint;
    @BindView(R2.id.tv_hot_car_rental_hint)
    TextView tvHotCarRentalHint;
    @BindView(R2.id.iv_travel_city_text_hint)
    ImageView ivTravelCityTextHint;
    @BindView(R2.id.iv_search_input_hint)
    ImageView ivSearchInputHint;


    private ArrayList<String> images = new ArrayList<>();    //图片(默认采用网络地址)
    private List<String> titles = new ArrayList<>();         //图片标题
    Unbinder unbinder1;
    private final int TYPE_REQUEST_CITY = 1;//城市列表
    private final int TYPE_REQUEST_SHOP = 2;//门店列表
    private final int TYPE_REQUEST_ADDRESS = 3;//地址选择
    Unbinder unbinder2;

    Unbinder unbinder3;

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

    private double outLatitude = 0;
    private double outLongitude;
    private int getCityId;//取车城市ID
    private int outCityId;//还车城市ID
    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;

    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) {
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        permissionProcess();
        setBanner();
        tvDay.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
        tvGetTime.setText(DateUtils.formatDate8(DateUtils.getCurDateTime()));
        tvGetWeek.setText("周" + MyUtils.getWeek(DateUtils.getCurDate()));
        tvOutTime.setText(MyUtils.getFetureDate2(1));
        tvOutWeek.setText("周" + MyUtils.getWeek(MyUtils.getFetureDate(1)));

        begDate = DateUtils.formatDate8(DateUtils.getCurDateTime());
        endDate = MyUtils.getFetureDate2(1);

        copyDay = DateUtils.compareDateDay(MyUtils.getFetureDate(1), DateUtils.getCurDate()) + 1;

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

        //房车发烧友
//        mRvEnthusiast = new RVEnthusiastAdapter();
//        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);

        getData();

        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 ("1".equals(hotType)) {
                    //优质车型
                }
            }
        });

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder3 = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder3.unbind();
    }

    @Override
    public void onRefresh() {
        hotData();
        recommendGood("2");
    }


    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 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 getData() {
        List<Integer> list = new ArrayList<>();
        list.add(R.drawable.aaa1);
        list.add(R.drawable.aaa2);
        mActivityAdapter.setNewData(list);
//        mRvEnthusiast.setNewData(list);
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {
        loadBannerData();
        hotData();
        recommendGood("2");
    }

    /**
     * 获取轮播图
     */
    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();
        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;
        }

    }

    private void setRecommendGood(HomeHotGoodListBean data) {
        mAdapter.getData().clear();
        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.travel_city_layout, R2.id.ll_item_search, R2.id.tv_item_rv_tour, R2.id.tv_item_renting_a_car, R2.id.tv_get_city,
            R2.id.tv_out_city, R2.id.tv_get_address, R2.id.tv_out_address, R2.id.ll_item_select_data, R2.id.tv_select_car,
            R2.id.ll_item_rv_city, R2.id.tv_book_now, R2.id.ll_item_rv_hot_label1, R2.id.ll_item_rv_hot_label2, R2.id.ll_item_rv_hot_label3,
            R2.id.ll_item_hot_rvtour, R2.id.ll_item_hot_entertainment_camp, R2.id.ll_item_hot_car_rental, R2.id.tv_see_more_popular,
            R2.id.ll_item_top, R2.id.travel_server_image, R2.id.tv_car_rental_guide, R2.id.ll_item_activity_all})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.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_item_search) {
            //搜索
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_TRAVELSEARCH)
                    .withDouble("latLatitude", 0)
                    .withDouble("lonLongitude", 0)
                    .navigation();

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

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

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

            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 1)
                    .withString("mNowCity", headTvGetCity.getText().toString())
                    .withInt("mCityId", getCityId)
                    .navigation(getActivity(), TYPE_REQUEST_CITY);

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

            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 2)
                    .withString("mNowCity", headTvOutCity.getText().toString())
                    .withInt("mCityId", outCityId)
                    .navigation(getActivity(), TYPE_REQUEST_CITY);

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

            String getCity = headTvGetCity.getText().toString().trim();
//                                if (getSwitchType == 0) {
//                                    startActivityForResult(SelectShopActivity.getIntent(mActivity, 1,"",getCity.equals(nowCity) && mLatLng!=null?mLatLng.latitude:0,getCity.equals(nowCity)&& mLatLng!=null?mLatLng.longitude:0), TYPE_REQUEST_SHOP);
//                                } else {
            startActivityForResult(SelectLocationActivity.getIntent(getContext(), 1, getCity, 0, latLatitude, lonLongitude, nowCity, 0), TYPE_REQUEST_ADDRESS);
        } else if (id == R.id.tv_out_address) {
            String outCity = headTvOutCity.getText().toString().trim();
//                                if (outSwitchType == 0) {
//                                    startActivityForResult(SelectShopActivity.getIntent(mActivity, 2,"",outCity.equals(nowCity)&& mLatLng!=null?mLatLng.latitude:0,outCity.equals(nowCity)&& mLatLng!=null?mLatLng.longitude:0), TYPE_REQUEST_SHOP);
//                                } else {
            startActivityForResult(SelectLocationActivity.getIntent(getContext(), 2, outCity, 0, outLatitude, outLongitude, nowCity, 0), TYPE_REQUEST_ADDRESS);
        } else if (id == R.id.ll_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_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(headTvGetCity.getText().toString().trim(),
                    headTvGetShop.getText().toString().trim(),
                    headTvOutCity.getText().toString().trim(),
                    headTvOutShop.getText().toString().trim(),
                    begDate, endDate, copyDay,
                    tvGetTime.getText().toString().trim(),
                    tvOutTime.getText().toString().trim()
            );
        } else if (id == R.id.ll_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_book_now) {
            //房车游 立即预定

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

            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_TRAVELSEARCH)
                    .withDouble("latLatitude", rvTourLatitude)
                    .withDouble("lonLongitude", rvTourLongitude)
                    .withString("city", tvRvCity.getText().toString())
                    .navigation();

        } else if (id == R.id.ll_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_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_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_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("更多热门旅行线路");

            recommendGood("2");
            hotType = "2";

        } else if (id == R.id.ll_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("更多娱乐营地");

            recommendGood("3");
            hotType = "3";
        } else if (id == R.id.ll_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("更多优质车型");
            recommendGood("4");
            hotType = "1";
        } else if (id == R.id.tv_see_more_popular) {
            //查看更多热门
            if ("2".equals(hotType)) {
                //热门旅行
                SwitchFragment.sChangeFragment.changge(1);

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

            } else if ("1".equals(hotType)) {
                //优质车型
            }
        } else if (id == R.id.ll_item_top) {
            scrollview.fullScroll(View.FOCUS_UP);
        } else if (id == R.id.travel_server_image) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri uri = Uri.parse("tel:" + "4000369369");
            intent.setData(uri);
            startActivity(intent);
        } else if (id == R.id.tv_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_item_activity_all) {
            showToast("亲，该功能还在开发中。。。");
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", 1);
            String requestData = data.getStringExtra("location");
            switch (requestCode) {
                case TYPE_REQUEST_CITY://城市列表
                    if (type == 1) {
                        headTvGetShop.setText("");
                        getCityId = data.getIntExtra("id", 0);
                    } else if (type == 2) {
                        headTvOutShop.setText("");
                        outCityId = data.getIntExtra("id", 0);
                    } else if (type == 3) {
                        tvRvCity.setText("");
                        vVTourCityId = data.getIntExtra("id", 0);
                    } else if (type == 4) {
                        travelCityText.setText("");
                        mTravelCityId = data.getIntExtra("id", 0);
                        getCityId = mTravelCityId;
                        outCityId = mTravelCityId;
                        vVTourCityId = mTravelCityId;
                    }
                    setRequestData(type, requestData, headTvGetCity, headTvOutCity, 0, 0);

                    break;
                case TYPE_REQUEST_SHOP://门店
                    setRequestData(type, requestData, headTvGetShop, headTvOutShop, 0, 0);
                    break;
                case TYPE_REQUEST_ADDRESS://地址
                    double lat = data.getDoubleExtra("latitude", 0);
                    double lon = data.getDoubleExtra("longitude", 0);
                    setRequestData(type, requestData, headTvGetShop, headTvOutShop, lat, lon);
                    break;
            }
        } else if (resultCode == 200 && requestCode == 108) {
            begDate = data.getStringExtra("begDate");
            endDate = data.getStringExtra("endDate");
            copyDay = DateUtils.compareDateDay(endDate, begDate) + 1;
            if (tvGetTime != null) {
                tvGetTime.setText(begDate);
            }
            if (tvOutTime != null) {
                tvOutTime.setText(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 type
     * @param data
     * @param tvGet
     * @param tvOut
     * @param lat
     * @param lon
     */
    private void setRequestData(int type, String data, TextView tvGet, TextView tvOut, double lat, double lon) {
        if (tvGet == null) {
            return;
        }
        switch (type) {
            case 1:
                latLatitude = lat;
                lonLongitude = lon;
                tvGet.setText(data);
                break;
            case 2:
                outLatitude = lat;
                outLongitude = lon;
                tvOut.setText(data);
                break;
            case 3:
                rvTourLatitude = lat;
                rvTourLongitude = lon;
                tvRvCity.setText(data);
                break;
            case 4:
                travelCityText.setText(data);
                headTvGetCity.setText(data);
                headTvOutCity.setText(data);
                tvRvCity.setText(data);

                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);
                            ComponentName componentName = new ComponentName(getActivity(), "com.rv.share.WebViewActivity");
                            Intent intent = new Intent();
                            intent.setComponent(componentName);
                            intent.putExtra("url", bean.getUrl());
                            intent.putExtra("title", bean.getTitle());
                            startActivity(intent);
                        }

                       /* 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) {
                headTvGetShop.setText(bean.getData().getData().get(0).getName());
                headTvGetShop.setTextColor(_mActivity.getResources().getColor(R.color.colorMain));
                latLatitude = bean.getData().getData().get(0).getLatitude();
                lonLongitude = bean.getData().getData().get(0).getLongitude();
            }

            if (headTvOutShop != null) {
                headTvOutShop.setText(bean.getData().getData().get(0).getName());
                headTvOutShop.setTextColor(_mActivity.getResources().getColor(R.color.colorMain));
                outLatitude = bean.getData().getData().get(0).getLatitude();
                outLongitude = bean.getData().getData().get(0).getLongitude();
            }
        } else {
            headTvGetShop.setText("");
            latLatitude = 0;
            lonLongitude = 0;
            headTvOutShop.setText("");
            outLatitude = 0;
            outLongitude = 0;
        }

    }

    /**
     * 获取门店列表
     */
    private void getShopList(double lat, double lon, 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 (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("lat", lat);
        map.put("lon", lon);
        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 && outCityId > 0) {
            dataBean.setEndCity(outCityId);
            dataBean.setStartCity(getCityId);
        } 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 (starCity.equals(lsBean.getName())) {
                        dataBean.setStartCity(lsBean.getId());
                    }

                    if (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.setEndAddr(endAddress);
        dataBean.setDriverType(2);
        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));
        }
    }

    /**
     * 定位权限处理
     */
    private void permissionProcess() {

        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            new RxPermission(getActivity()).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        initGps();
                        initCity();
                    } else {
                        getActivity().finish();
                    }
                }
            });
        } 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 {
                    latLatitude = result.getLocation().latitude;
                    lonLongitude = result.getLocation().longitude;
                    outLatitude = result.getLocation().latitude;
                    outLongitude = result.getLocation().longitude;
                    rvTourLatitude = result.getLocation().latitude;
                    rvTourLongitude = result.getLocation().longitude;
                    getShopList(latLatitude, lonLongitude, false);
                }
                //获取地理编码结果
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                } else {
                    latLatitude = result.getLocation().latitude;
                    lonLongitude = result.getLocation().longitude;
                    outLatitude = result.getLocation().latitude;
                    outLongitude = result.getLocation().longitude;
                    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;
                headTvGetCity.setText(location.getCity());
                headTvOutCity.setText(location.getCity());
                tvRvCity.setText(location.getCity());
                travelCityText.setText(location.getCity());
                rvTourLatitude = latLatitude;
                rvTourLongitude = lonLongitude;
                nowCity = location.getCity();
                locationManager.stopLocation();
                getShopList(mLatLng.latitude, mLatLng.longitude, true);
            }
        });
    }

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