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.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);
        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 AbSpacesItemDecoration(23));// 分割线。
        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();
            }
        });

    }

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


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

}
