package com.rv.tourism.other;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.tools.android.IntentUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ruiwenliu.wrapper.browse.ActivityImageBrowseUrl;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.tourism.R;
import com.rv.tourism.R2;
import com.rv.tourism.TourismFragment;
import com.rv.tourism.adapter.AllPopularAdapter;
import com.rv.tourism.adapter.RecommendedRouteAdapter;
import com.rv.tourism.api.TourismApi;
import com.rv.tourism.bean.BeanPopularBrigadeAll;
import com.rv.tourism.bean.BeanTourAround;
import com.rv.tourism.bean.BeanTourismBanner;
import com.rv.tourism.presenter.TourismPresenter;
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.List;

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

/**
 * 热门游列表
 */
@Route(path = Constance.ACTIVITY_URL_POPULARTOURLIST)
public class PopularTourListActivity extends BaseStatusActivity<TourismPresenter> {

    @BindView(R2.id.travel_banner)
    Banner travelBanner;
    @BindView(R2.id.rv_recommended_route)
    RecyclerView rvRecommendedRoute;
    @BindView(R2.id.rv_popular_more)
    RecyclerView rvPopularMore;
    @BindView(R2.id.ll_layout_popular_more)
    LinearLayout llLayoutPopularMore;

    private RecommendedRouteAdapter mRecommendedRouteAdapter;
    private AllPopularAdapter mAllPopularAdapter;
    private int mPage;
    private int countPage;
    @Autowired()
    String id;
    @Autowired()
    String name;

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

    public static Intent getIntent(Context context, String name, String id) {
        return new Intent(context, PopularTourListActivity.class)
                .putExtra("name", name)
                .putExtra("id", id);
    }


    @Override
    protected int setLayout() {
        return R.layout.activity_popular_tour_list;
    }

    @Override
    protected void initView(Bundle savedInstanceState, final TitleView titleView, Intent intent) {
        name = intent.getStringExtra("name");
        titleView.setTitle(name);
        titleView.setDividerDrawable(getResources().getDrawable(R.drawable.common_icon_rig_gray));
        id = intent.getStringExtra("id");


        mRecommendedRouteAdapter = new RecommendedRouteAdapter();
        rvRecommendedRoute.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
//        rvTourAround.addItemDecoration(new AbSpacesItemDecoration(5));// 分割线。
        rvRecommendedRoute.setAdapter(mRecommendedRouteAdapter);


        //全部热门旅游
        mAllPopularAdapter = new AllPopularAdapter();
        rvPopularMore.setLayoutManager(new GridLayoutManager(mActivity, 3));
        rvPopularMore.addItemDecoration(new AbSpacesItemDecoration2(20,10));// 分割线。
//        rvPopularMore.setNestedScrollingEnabled(false);
        rvPopularMore.setAdapter(mAllPopularAdapter);

        titleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llLayoutPopularMore.setVisibility(View.VISIBLE);
            }
        });


        mAllPopularAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BeanPopularBrigadeAll.DataBeanX.DataBean item = (BeanPopularBrigadeAll.DataBeanX.DataBean) adapter.getItem(position);
                id = item.getId();
                titleView.setTitle(item.getName());
                mRecommendedRouteAdapter.getData().clear();
                loadBannerData();
                loadPopularTourListData();
                llLayoutPopularMore.setVisibility(View.GONE);
            }
        });

        mRecommendedRouteAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BeanTourAround.DataBeanX.DataBean item = (BeanTourAround.DataBeanX.DataBean) adapter.getItem(position);
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_TRAVELDETAILS)
                        .withString("id",item.getId())
                        .withString("name",item.getName())
                        .withString("content",item.getContent())
                        .withString("url",item.getCover())
                        .withDouble("price",Double.valueOf(item.getPrice()))
                        .navigation();
            }
        });

        mRecommendedRouteAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mPage >= countPage) {
                    mRecommendedRouteAdapter.loadMoreEnd();
                } else {
                    mPage++;
                    getLoadPopularTourListData(mPage);
                }
            }
        },rvRecommendedRoute);

    }

    @OnClick(R2.id.travel_hot_more_close)
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.travel_hot_more_close) {
            llLayoutPopularMore.setVisibility(View.GONE);
        }
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        loadBannerData();
        loadPopularBrigadeData();
        loadPopularTourListData();
    }

    /**
     * 获取轮播图
     */
    private void loadBannerData() {
        mPresenter.getData(0, TourismApi.QUERY_BANNER_HOT + "/" + id, BeanTourismBanner.class, false);
    }

    /**
     * 获取热门
     */
    private void loadPopularBrigadeData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("hot", "0");
        map.put("page", "1");
        map.put("limit", "50");
        mPresenter.getData(2, TourismApi.QUERY_HOT_LIST, BeanPopularBrigadeAll.class, map, false);
    }


    private void loadPopularTourListData() {
        mPage = 1;
        getLoadPopularTourListData(mPage);
    }

    private void getLoadPopularTourListData(int page) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("tagId", id);
        map.put("query", "");
        map.put("page", page);
        map.put("limit", "10");
        map.put("latitudel", "22.954205");
        map.put("longitude", "113.879421");
        mPresenter.getData(1, TourismApi.QUERY_RIM_LIST, BeanTourAround.class, map, false);
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                BannerData((BeanTourismBanner) result);
                break;
            case 1:
                PopularTourList((BeanTourAround) result);
                break;
            case 2:
                popularBrigade((BeanPopularBrigadeAll) result);
                break;
        }
    }

    private void popularBrigade(BeanPopularBrigadeAll result) {
        mAllPopularAdapter.addData(result.getData().getData());
    }

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

    private void PopularTourList(BeanTourAround bean) {
        if (mPage == 1) {
            if (bean.getData().getTotalCount() == 0) {
//                mTourAroundAdapter.setEmptyView(getEmptyView(recyclerView, -1, mActivity.getString(R.string.rv_driving_data_null)));
                return;
            }

            countPage = bean.getData().getTotalPage();
            mRecommendedRouteAdapter.addNewData(bean);
            mRecommendedRouteAdapter.loadMoreComplete();
        } else {
            mRecommendedRouteAdapter.addData(bean.getData().getData());
            mRecommendedRouteAdapter.loadMoreComplete();
        }
    }

    /**
     * 设置轮番图
     */
    private void setBanner() {
        travelBanner.isAutoPlay(true)
                .setBannerTitles(titles)
                .setImages(images)
                .setDelayTime(3000)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {

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

                        Bundle bundle = new Bundle();
                        bundle.putInt(ActivityImageBrowseUrl.KEY_BACKGROUND, R.color.colorPrimary);
                        bundle.putStringArrayList(ActivityImageBrowseUrl.KEY_IMAGE, (ArrayList<String>) images);
                        IntentUtil.startActivity(mActivity, ActivityImageBrowseUrl.class, bundle);

                    }
                })
                .start();

        travelBanner.updateBannerStyle(BannerConfig.CIRCLE_INDICATOR);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

//    @Override
//    public void onLoadMoreRequested() {
//        if (mPage >= countPage) {
//            mRecommendedRouteAdapter.loadMoreEnd();
//        } else {
//            mPage++;
//            getLoadPopularTourListData(mPage);
//        }
//    }


    public class AbSpacesItemDecoration2 extends RecyclerView.ItemDecoration {

        private int left;
        private int right;

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

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int childCount = parent.getChildCount();
            if (childCount  % 3==1){
                outRect.left = left;
                outRect.right = right;
                outRect.bottom = right;
                outRect.top = right;
            }else if (childCount % 3 == 2){
                outRect.left = right;
                outRect.right = right;
                outRect.bottom = right;
                outRect.top = right;
            }else if (childCount % 3 ==0){
                outRect.left = right;
                outRect.right = left;
                outRect.bottom = right;
                outRect.top = right;
            }
        }
    }

}
