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

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
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.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.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;

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.TimeManager;
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.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.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.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
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 {


    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;



    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 int copyDay = 2;//租车天数
    private Map<String, Integer> mapGetTime;
    private Map<String, Integer> mapOutTime;
    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 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) {
        permissionProcess();
        setBanner();
        initTime(tvGetTime, tvOutTime);
        tvDay.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
        tvItemRvTour.setSelected(true);
        tvHotRvtour.setTextColor(getResources().getColor(R.color.text_Main));
        tvHotRvtour.getPaint().setFakeBoldText(true);

        ViewTreeObserver observer = rlItemLayout.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rlItemLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = rlItemLayout.getHeight();
                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.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())
                            .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();
    }


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

    private void getData() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            list.add("https://xxtest.upyuns.com/image/app/ENRq748FQTq86R8R77J88YEWhnPeZ3.png");
        }
        mActivityAdapter.setNewData(list);
        mRvEnthusiast.setNewData(list);
    }

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

    /**
     * 推荐商品   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) {
        switch (requestType) {
            case 0:
                processData((ShopListBean) result);
                break;
            case 1:
                setHotData((HomePopularBrigade) result);
                break;
            case 2:
                setRecommendGood((HomeHotGoodListBean) result);
                break;
        }

    }

    private void setRecommendGood(HomeHotGoodListBean data) {
        mAdapter.getData().clear();
        mAdapter.addData(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_get_time, R2.id.ll_item_alsotime, 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.tv_car_rental_guide})
    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",latLatitude)
                    .withDouble("lonLongitude",lonLongitude)
                    .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, latLatitude, lonLongitude, nowCity), 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, outLatitude, outLongitude, nowCity), TYPE_REQUEST_ADDRESS);
        } else if (id == R.id.ll_item_get_time) {

            if (mapGetTime == null) {
                return;
            }
            showDatePicker(mapGetTime.get("year"), mapGetTime.get("month"), mapGetTime.get("day"), mapGetTime.get("hour"), mapGetTime.get("minute"), tvGetTime, tvGetWeek, mapGetTime, tvDay);

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

            if (mapOutTime == null) {
                return;
            }
            showDatePicker(mapOutTime.get("year"), mapOutTime.get("month"), mapOutTime.get("day"), mapOutTime.get("hour"), mapOutTime.get("minute"), tvOutTime, tvOutWeek, mapOutTime, tvDay);

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

            if (mapGetTime.size() > 0 && mapOutTime.size() > 0) {
                String getTime = String.format("%1$s-%2$s-%3$s", mapGetTime.get("year"), mapGetTime.get("month") < 10 ? "0" + mapGetTime.get("month") : mapGetTime.get("month"), mapGetTime.get("day") < 10 ? "0" + mapGetTime.get("day") : mapGetTime.get("day"));
                String outTime = String.format("%1$s-%2$s-%3$s", mapOutTime.get("year"), mapOutTime.get("month") < 10 ? "0" + mapOutTime.get("month") : mapOutTime.get("month"), mapOutTime.get("day") < 10 ? "0" + mapOutTime.get("day") : mapOutTime.get("day"));
                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(),
                        getTime, outTime, 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) {
            //立即预定
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_TRAVELSEARCH)
                    .withDouble("latLatitude",latLatitude)
                    .withDouble("lonLongitude",lonLongitude)
                    .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) {
            //热门旅行
            tvHotRvtour.setTextColor(getResources().getColor(R.color.text_Main));
            tvHotEntertainmentCamp.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) {
            //娱乐营地
            tvHotRvtour.setTextColor(getResources().getColor(R.color.textGray));
            tvHotEntertainmentCamp.setTextColor(getResources().getColor(R.color.text_Main));
            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) {
            //优质车型
            tvHotRvtour.setTextColor(getResources().getColor(R.color.textGray));
            tvHotEntertainmentCamp.setTextColor(getResources().getColor(R.color.textGray));
            tvHotCarRental.setTextColor(getResources().getColor(R.color.text_Main));

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

            tvSeeMorePopular.setText("更多优质车型");
            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){
            showToast("亲，该功能还在开发中。。。");
        }else if (id == R.id.tv_car_rental_guide){
            //租车指南
            startActivity(WebActivity.getIntent(_mActivity, _mActivity.getString(R.string.rv_contract_agreement), ApiConfig.HTTP_URL_CAR_TYPE_NOTICE));
        }
    }


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


    /**
     * 设置返回结果参数
     *
     * @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);

                geoCoder.geocode(new GeoCodeOption()
                        .city(data)
                        .address(data));
                break;
        }
    }


    private ArrayList<String> images = new ArrayList<>();    //图片(默认采用网络地址)
    private List<String> titles = new ArrayList<>();         //图片标题
    private List<Integer> localImages = new ArrayList<>();   //图片(本地资源)

    private void setBanner() {
        titles.clear();
        images.clear();
        localImages.clear();

        localImages.add(R.drawable.aa_image_banner);
        localImages.add(R.drawable.aa_image_banner);

        mineBanner.setImages(localImages);
        for (int i = 0; i < localImages.size(); i++) {
            titles.add("");
        }
        mineBanner.isAutoPlay(true)
                .setBannerTitles(titles)
                .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) {
                       /* 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().getTotalCount() > 0) {
            if (headTvGetShop != null && TextUtils.isEmpty(headTvGetShop.getText().toString().trim())) {
                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 && TextUtils.isEmpty(headTvOutShop.getText().toString().trim())) {
                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();
            }
        }

    }

    /**
     * 获取门店列表
     */
    private void getShopList(double lat, double lon) {
        int addrCity = 0;
        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();
                }
            }
        }
        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, int 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(day);
        dataBean.setStartCityName(starCity);
        dataBean.setStartAddr(starAddress);
        try {
            dataBean.setStartTime(TimeManager.dateToStamp(getTime));
            dataBean.setEndTime(TimeManager.dateToStamp(outTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dataBean.setEndCityName(endCity);
        dataBean.setEndAddr(endAddress);
        dataBean.setDriverType(2);
        startActivity(CarRentalListActivity.getIntent(getContext(), latLatitude, lonLongitude, 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);
            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));
            llItemTitle.setBackgroundColor(Color.argb(255, 255, 255, 255));
        }
    }


    /**
     * 初始化时间进程
     */
    private void initTime(TextView tvGetTime, TextView tvOutTime) {
        Calendar cal = Calendar.getInstance();
        if (mapGetTime == null) {
            mapGetTime = new LinkedHashMap<>();
        }
        mapGetTime.put("year", cal.get(Calendar.YEAR));
        mapGetTime.put("month", cal.get(Calendar.MONTH) + 1);
        mapGetTime.put("day", cal.get(Calendar.DAY_OF_MONTH));
        mapGetTime.put("hour", cal.get(Calendar.HOUR));
        mapGetTime.put("minute", cal.get(Calendar.MINUTE));
        if (mapOutTime == null) {
            mapOutTime = new LinkedHashMap<>();
        }
        String[] timeGroup = TimeManager.getAfterDay(2).split("-");
        mapOutTime.put("year", Integer.valueOf(timeGroup[0]));
        mapOutTime.put("month", Integer.valueOf(timeGroup[1]));
        mapOutTime.put("day", Integer.valueOf(timeGroup[2]));
        mapOutTime.put("hour", cal.get(Calendar.HOUR));
        mapOutTime.put("minute", cal.get(Calendar.MINUTE));
        tvGetTime.setText(String.format("%1$s-%2$s-%3$s %4$s:%5$s", mapGetTime.get("year"), mapGetTime.get("month"), mapGetTime.get("day"), mapGetTime.get("hour"), mapGetTime.get("minute")));
        tvOutTime.setText(String.format("%1$s-%2$s-%3$s %4$s:%5$s", mapOutTime.get("year"), mapOutTime.get("month"), mapOutTime.get("day"), mapOutTime.get("hour"), mapOutTime.get("minute")));
    }

    /**
     * 展示日历弹窗
     *
     * @param newYear
     * @param newMonth
     * @param newDay
     * @param tvTime
     */
    private void showDatePicker(int newYear, int newMonth, int newDay, final int newHour, final int newMinute, final TextView tvTime, final TextView tvWeek, final Map<String, Integer> map, final TextView day) {
        if (tvTime == null) {
            return;
        }
        //实例化日期选择器悬浮窗
        //参数1：上下文对象
        //参数2：监听事件
        //参数3：初始化年份
        //参数4：初始化月份
        //参数5：初始化日期
        new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                map.clear();
                map.put("year", year);
                map.put("month", month + 1);
                map.put("day", dayOfMonth);
                tvTime.setText("");
                tvWeek.setText("");
                String tvMonth = month < 10 ? "0" + month : "" + month;
                String tvDays = month < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
                tvTime.append("" + year + "-" + tvMonth + "-" + tvDays + " ");
                showTimeDialog(newHour, newMinute, tvTime, map);
                getTimeDay(day);
            }
        }, newYear, newMonth - 1,
                newDay).show();

    }

    /**
     * 获取进程天数
     *
     * @param day
     */
    private void getTimeDay(TextView day) {
        if (mapGetTime != null && mapOutTime != null) {
            copyDay = TimeManager.getDays(String.format("%1$s-%2$s-%3$s", mapGetTime.get("year"), mapGetTime.get("month"), mapGetTime.get("day"))
                    , String.format("%1$s-%2$s-%3$s", mapOutTime.get("year"), mapOutTime.get("month"), mapOutTime.get("day")));

            day.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
        }

    }

    /**
     * 展示时间弹窗
     * //实例化时间选择器
     * //参数1：上下文对象
     * //参数2：监听事件
     * //参数3：初始化小时
     * //参数4：初始化分钟
     * //参数5：是否24小时制
     */
    private void showTimeDialog(int hour, int minute, final TextView tvTime, final Map<String, Integer> map) {
        new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
            //实现监听方法
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {
                map.put("hour", i);
                map.put("minute", i1);

                //设置文本显示内容
                tvTime.append("" + i + ":" + i1);
//                tvTime.append(String.format("%1$s:%2$s", i,i1));

            }
        }, hour, minute, true).show();//记得使用show才能显示！
    }

    /**
     * 定位权限处理
     */
    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;
                }
                //获取地理编码结果
            }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        geoCoder.destroy();
    }
}
