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

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

import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.inter.ImInitListenter;
import com.ruiwenliu.wrapper.util.GpsManager;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.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.Cookie;
import com.rv.component.utils.DisplayUtil;
import com.rv.component.utils.LogUtil;
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.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.HomeHotGoodListBean;
import com.rv.home.rv.module.ui.main.home.bean.HomePopularBrigade;
import com.rv.home.rv.module.ui.main.home.bean.HomeRecommendBean;
import com.rv.home.rv.module.ui.main.home.bean.SelectedActivitiesBean;
import com.rv.home.rv.module.ui.main.home.presenter.HomePresenter;
import com.xxrv.video.activity.TriListActivity;
import com.xxrv.video.bean.circle.DiscoveryDataBean;
import com.yuyife.banner.Banner;
import com.yuyife.banner.BannerConfig;
import com.yuyife.banner.loader.ImageLoader;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements ObservableScrollView.ScrollViewListener, SimpleRefreshLayout.OnSimpleRefreshListener, GpsManager.GpsChangeListener {

    @BindView(R2.id.home_banner)
    Banner mineBanner;
    @BindView(R2.id.ll_indicator)
    LinearLayout llIndicator;
    @BindView(R2.id.ry_home_hot_travel)
    RecyclerView ryHomeHotTravel;
    @BindView(R2.id.ry_home_camp)
    RecyclerView ryHomeCamp;
    @BindView(R2.id.recyclerView_home_activity)
    RecyclerView recyclerViewActivity;
    @BindView(R2.id.recyclerView_home_rvtourlist)
    RecyclerView recyclerViewRvtourlist;
    @BindView(R2.id.recyclerView_home_rvtourlist_title)
    RecyclerView recyclerViewRvtourlistTitle;
    @BindView(R2.id.recyclerView_home_rv_enthusiast)
    RecyclerView recyclerViewRvEnthusiast;
    @BindView(R2.id.tv_home_travel_city_text)
    TextView travelCityText;
    @BindView(R2.id.tv_home_travel_city_layout)
    LinearLayout travelCityLayout;
    @BindView(R2.id.tv_home_search_input)
    TextView searchInput;
    @BindView(R2.id.iv_home_travel_server_image)
    ImageView travelServerImage;
    @BindView(R2.id.os_scrollview_home)
    ObservableScrollView scrollview;
    @BindView(R2.id.ll_home_item_title)
    LinearLayout llItemTitle;
    @BindView(R2.id.ll_home_item_top)
    LinearLayout llItemTop;
    @BindView(R2.id.ll_home_item_search)
    LinearLayout llItemSearch;
    @BindView(R2.id.refresh_home)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.iv_home_travel_city_text_hint)
    ImageView ivTravelCityTextHint;
    @BindView(R2.id.iv_home_search_input_hint)
    ImageView ivSearchInputHint;
    @BindView(R2.id.ll_car_recent)
    LinearLayout llCarRecent;
    @BindView(R2.id.ll_car_travel)
    LinearLayout llCarTravel;
    @BindView(R2.id.ll_car_camp)
    LinearLayout llCarCamp;
    @BindView(R2.id.ll_member)
    LinearLayout llMemeber;
    @BindView(R2.id.ll_car_buy)
    LinearLayout llCarBuy;

    private ArrayList<String> images = new ArrayList<>();    //图片(默认采用网络地址)
    private List<String> titles = new ArrayList<>();         //图片标题
    private final int TYPE_REQUEST_CITY = 1;//城市列表
    private final int REQUEST_RECENT_CODE = 10000;

    private LocationManager locationManager;

    private HotCarTypeAdapter mHotTravelAdapter;
    private HotCarTypeAdapter mCampAdapter;
    private SelectedEventsAdapter mActivityAdapter;
    private RVEnthusiastAdapter mRvEnthusiast;
    private RVTourListAdapter mRvTourAdapter;
    private RVTourListLabelAdapter mRvTourLabelAdapter;

    private int countPage;
    private int mPage;

    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) {
        GpsManager.getInstance(_mActivity).bindGpsListener(this);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        permissionProcess();
        setBanner();
        Drawable drawable = getResources().getDrawable(R.drawable.icon_day_times);
        drawable.setBounds(0, 0, DisplayUtil.dip2px(getContext(), 25), DisplayUtil.dip2px(getContext(), 5));

        mHotTravelAdapter = new HotCarTypeAdapter();
        ryHomeHotTravel.setLayoutManager(new GridLayoutManager(getContext(), 2));
        ryHomeHotTravel.addItemDecoration(new AbSpacesItemDecoration(10, DisplayUtil.dip2px(_mActivity, 8)));// 分割线。
        ryHomeHotTravel.setNestedScrollingEnabled(false);
        ryHomeHotTravel.setAdapter(mHotTravelAdapter);

        mCampAdapter = new HotCarTypeAdapter();
        ryHomeCamp.setLayoutManager(new GridLayoutManager(getContext(), 2));
        ryHomeCamp.addItemDecoration(new AbSpacesItemDecoration(10, DisplayUtil.dip2px(_mActivity, 8)));// 分割线。
        ryHomeCamp.setNestedScrollingEnabled(false);
        ryHomeCamp.setAdapter(mCampAdapter);

        //精选活动
        mActivityAdapter = new SelectedEventsAdapter();
        recyclerViewActivity.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerViewActivity.addItemDecoration(new AbSpacesItemDecoration1(20));// 分割线。
        recyclerViewActivity.setNestedScrollingEnabled(false);
        recyclerViewActivity.setAdapter(mActivityAdapter);
        mActivityAdapter.setOnItemClickListener((adapter, view, position) -> {
            SelectedActivitiesBean.SelectedActivityItem item = (SelectedActivitiesBean.SelectedActivityItem) adapter.getItem(position);
            mPresenter.saveOnclick("3", String.valueOf(item.getId()));
            if (item != null && !TextUtils.isEmpty(item.getUrl()) && !TextUtils.isEmpty(item.getName())) {
                mPresenter.toTarget(getActivity(), item.getUrl(), item.getName(), String.valueOf(item.getId()));
            }
        });

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

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

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

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

        mRvEnthusiast.setOnLoadMoreListener(() -> {
            if (recyclerViewRvEnthusiast != null) {
                recyclerViewRvEnthusiast.postDelayed(() -> {
                    if (mPage >= countPage) {
                        mRvEnthusiast.loadMoreEnd();
                    } else {
                        mPage++;
                        loadDisCovery(mPage);
                    }
                }, 200);
            }
        }, recyclerViewRvEnthusiast);


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

        //  //房车游榜单 标注
        mRvTourLabelAdapter = new RVTourListLabelAdapter();
        recyclerViewRvtourlistTitle.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerViewRvtourlistTitle.addItemDecoration(new AbSpacesItemDecoration1(DisplayUtil.dip2px(_mActivity, 10)));
        recyclerViewRvtourlistTitle.setNestedScrollingEnabled(false);

        height = _mActivity.getWindowManager().getDefaultDisplay().getHeight();
        scrollview.setScrollViewListener(HomeFragment.this);


        mHotTravelAdapter.setOnItemClickListener((adapter, view, position) -> {
            HomeHotGoodListBean.DataBean data = (HomeHotGoodListBean.DataBean) adapter.getItem(position);
            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();
        });

        mCampAdapter.setOnItemClickListener((adapter, view, position) -> {
            HomeHotGoodListBean.DataBean data = (HomeHotGoodListBean.DataBean) adapter.getItem(position);
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CAMPDETAIL)
                    .withString("id", data.getId())
                    .withString("longitude", data.getLongitude())
                    .withString("latitude", data.getLatitude())
                    .navigation();
        });

        mRvTourLabelAdapter.setOnItemClickListener((adapter, view, position) -> {
            mRvTourLabelAdapter.setSelectPosition(position);
            recyclerViewRvtourlist.scrollToPosition(position);
        });

        mRvTourAdapter.setOnItemClickListener((adapter, view, position) -> {
            mRvTourLabelAdapter.setSelectPosition(position);
            recyclerViewRvtourlistTitle.scrollToPosition(position);
            HomePopularBrigade.DataBean beanHot = (HomePopularBrigade.DataBean) adapter.getItem(position);
            ARouter.getInstance().build(Constance.ACTIVITY_URL_POPULARTOURLIST).withString("name", beanHot.getName()).withString("id", beanHot.getId()).navigation();
        });


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

    @Override
    public void onRefresh() {

        loadBannerData();
        hotData();
        recommendGood(2);
        recommendGood(3);
        getSelectedActivities();
        onFreshLoadDisCovery();
    }

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

    public class AbSpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int sh;
        private int sv;

        public AbSpacesItemDecoration(int sh, int sv) {
            this.sh = sh;
            this.sv = sv;
        }

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

            if (sh != 0) {
                if (position % 2 == 0) {
                    outRect.right = sh;
                } else {
                    outRect.left = sh;
                }
            }

            if (sv != 0) {
                if (position <= 1) {
                    outRect.bottom = sv;
                } else {
                    outRect.top = sv;
                }
            }
        }
    }

    public class AbSpacesItemDecoration1 extends RecyclerView.ItemDecoration {
        private int sh;

        public AbSpacesItemDecoration1(int sh) {
            this.sh = sh;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if (sh != 0) {
                int position = parent.getChildAdapterPosition(view);
                if (position != 0)
                    outRect.left = sh;
            }
        }
    }

    public class AbSpacesItemDecoration2 extends RecyclerView.ItemDecoration {

        private int left;
        private int right;

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

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

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

    private void getSelectedActivities() {

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

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

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

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

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


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

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

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

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

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

    private void setRecommendGood(HomeHotGoodListBean data, int hotType) {
        if (hotType == 2) {
//            hotTravelView.setData(data.getData());
            mHotTravelAdapter.setType(String.valueOf(hotType));
            mHotTravelAdapter.setNewData(data.getData());
        } else if (hotType == 3) {
            mCampAdapter.setType(String.valueOf(hotType));
            mCampAdapter.setNewData(data.getData());
        }
    }

    private void setHotData(HomePopularBrigade data) {

        mRvTourAdapter.setNewData(data.getData());
        mRvTourLabelAdapter.setNewData(data.getData());
    }

    @OnClick({R2.id.tv_home_travel_city_layout, R2.id.ll_home_item_search,
            R2.id.ll_home_item_top, R2.id.iv_home_travel_server_image, R2.id.ll_home_item_activity_all, R2.id.tv_camp_more
            , R2.id.tv_hot_travel_more, R2.id.ll_car_recent, R2.id.ll_car_buy, R2.id.ll_car_camp, R2.id.ll_member, R2.id.ll_car_travel})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_home_travel_city_layout) {
            //选择城市
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 4)
                    .withString("mNowCity", travelCityText.getText().toString())
                    .navigation(getActivity(), TYPE_REQUEST_CITY);

        } else if (id == R.id.ll_car_travel) {
            SwitchFragment.sChangeFragment.changge(1);
        } else if (id == R.id.ll_car_camp) {
            SwitchFragment.sChangeFragment.changge(2);
        } else if (id == R.id.ll_member) {
            ComponentName name = new ComponentName(getContext(), "com.rv.member.MemberCenterActivity");
            Intent intent = new Intent();
            intent.setComponent(name);
            startActivity(intent);
        } else if (id == R.id.ll_car_buy) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CARPURCHASELIST)
                    .navigation();
        } else if (id == R.id.ll_home_item_search) {
            //搜索
            String city = travelCityText.getText().toString().trim();
            if (!TextUtils.isEmpty(city)) {
                String hint = city.substring(city.length() - 1);
                if ("市".equals(hint)) {  //判断后面是否是带市结尾的，去掉
                    city = city.substring(0, city.length() - 1);
                }
            }

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

        } else if (id == R.id.tv_hot_travel_more) {
            //查看更多热门
            SwitchFragment.sChangeFragment.changge(1);
        } else if (id == R.id.tv_camp_more) {
            SwitchFragment.sChangeFragment.changge(2);
        } else if (id == R.id.ll_home_item_top) {
            scrollview.fullScroll(View.FOCUS_UP);
        } else if (id == R.id.iv_home_travel_server_image) {
            if (mPresenter.isLogin(_mActivity)) {

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

                ComponentName name = new ComponentName(getActivity(), "com.rv.im.CustomerListActivity");
                Intent intent = new Intent();
                intent.putExtra("login_user_id", Cookie.getStringValue(getContext(), SPConstance.USER_JSON_IMUSERID));
                intent.setComponent(name);
                startActivity(intent);
            }
        } else if (id == R.id.ll_home_item_activity_all) {
            showToast("亲，该功能还在开发中。。。");
        } else if (id == R.id.ll_car_recent) {
            startActivityForResult(CarRentActivity.getIntent(_mActivity, travelCityText.getText().toString().trim()), REQUEST_RECENT_CODE);
        }
    }

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

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

        if (resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", 1);
            String requestData = data.getStringExtra("location");
            switch (requestCode) {
                case TYPE_REQUEST_CITY://城市列表
                    if (type == 4) {
                        if (!TextUtils.isEmpty(requestData))
                            travelCityText.setText(requestData);
                    }
                    break;
                case REQUEST_RECENT_CODE: // 租车返回信息

                    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)
                .isHome(true)
                .setDelayTime(3000)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {

                        GlideManager.getInstance(context).loadRoundImage2(path, imageView, 6);
                    }
                })
                .setOnBannerListener(position -> {

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

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

        mineBanner.updateBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mineBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                indicatorChange(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void indicatorChange(int position) {
        if (llIndicator == null) return;
        llIndicator.removeAllViews();
        for (int i = 0; i < images.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            LinearLayout.LayoutParams params = null;
            if (position == i) {
                params = new LinearLayout.LayoutParams(DisplayUtil.dip2px(getContext(), 15), DisplayUtil.dip2px(getContext(), 7));
            } else {
                params = new LinearLayout.LayoutParams(DisplayUtil.dip2px(getContext(), 7), DisplayUtil.dip2px(getContext(), 7));
            }
            params.leftMargin = DisplayUtil.dip2px(getContext(), 3);
            params.rightMargin = DisplayUtil.dip2px(getContext(), 3);
            if (i == position) {
                imageView.setImageResource(R.drawable.icon_show);
            } else {
                imageView.setImageResource(R.drawable.icon_unshow);
            }
            llIndicator.addView(imageView, params);
        }
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= height) {
            llItemTop.setVisibility(View.GONE);
        } else {
            llItemTop.setVisibility(View.VISIBLE);
        }
    }

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

    /**
     * 初始化定位
     */
    public void initGps() {
        if (locationManager == null) {
            locationManager = new LocationManager(getContext());
        }
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (location != null) {
                    if (!TextUtils.isEmpty(location.getCity())) {
                        travelCityText.setText(location.getCity());
                    }
                }
                locationManager.stopLocation();
            }
        });
    }

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

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