package com.xxfc.discovery.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Display;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.adapter.DiscoveryRecommendAdapter;
import com.xxfc.discovery.adapter.DiscoveryShortVideoAdapter;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryRecommendBean;
import com.xxfc.discovery.event.PostPatEvent;
import com.xxfc.discovery.event.PostVideoEvent;
import com.xxfc.discovery.other.ShortVideoActivity;
import com.xxfc.discovery.presenter.DiscoveryPresenter;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.schedulers.Schedulers;

/**
 * 短视频
 */
public class ShortVideoFragment extends BaseFragment<DiscoveryPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {

    @BindView(R2.id.rv_content)
    RecyclerView rvContent;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;

    private DiscoveryShortVideoAdapter mAdapter;
    private int countPage;
    private int mPage;


    public static ShortVideoFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        ShortVideoFragment fragment = new ShortVideoFragment();
        fragment.setArguments(bundl);
        return fragment;
    }

    @Override
    public int getViewLayout() {
        return R.layout.fragment_short_video;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        initRxbus();
        mAdapter = new DiscoveryShortVideoAdapter();


        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvContent.setItemAnimator(null);
        rvContent.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();
                }
            }
        });

        rvContent.setLayoutManager(staggeredGridLayoutManager);

//        rvContent.setLayoutManager(new GridLayoutManager(_mActivity, 2));
        rvContent.addItemDecoration(new AbSpacesItemDecoration(20, 10));// 分割线。
        rvContent.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(rvContent);
        mAdapter.setEnableLoadMore(true);
        mAdapter.disableLoadMoreIfNotFullPage();

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                DiscoveryRecommendBean.DataBeanX.DataBean data = (DiscoveryRecommendBean.DataBeanX.DataBean) adapter.getData();
                DiscoveryRecommendBean.DataBeanX.DataBean item = (DiscoveryRecommendBean.DataBeanX.DataBean) adapter.getItem(position);
                if (item != null) {
                    startActivity(ShortVideoActivity.getIntent(_mActivity, item));
                }
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (rvContent != null) {
                    rvContent.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mPage >= countPage) {
                                mAdapter.loadMoreEnd();
                            } else {
                                mPage++;
                                geDataList(mPage);
                            }
                        }
                    }, 200);
                }
            }
        }, rvContent);

    }

    private void initRxbus() {
        RxBus.tObservable(PostVideoEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PostVideoEvent>(disposable) {
                    @Override
                    public void onNext(PostVideoEvent event) {
                        onFresh();
                    }
                });
    }


    @Override
    protected void loadData(Bundle savedInstanceState) {
        onFresh();
    }

    /**
     * 刷新
     */
    private void onFresh() {
        mPage = 1;
        geDataList(mPage);
    }

    /**
     * 请求数据
     *
     * @param page
     */
    private void geDataList(int page) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", page);
        map.put("type", 4);
        mPresenter.postData(0, DiscoveryApi.DISCOVERY_UNAUTH_LIST, DiscoveryRecommendBean.class, map, page == 1 ? false : false);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        processData((DiscoveryRecommendBean) result);
    }

    private void processData(DiscoveryRecommendBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getTotalPage();
            mAdapter.setNewData(bean.getData().getList());
            if (bean.getData().getTotalCount() == 0) {
//                mAdapter.setEmptyView(getEmptyView(rvContent, -1, "暂无拍拍数据"));
//                mAdapter.notifyDataSetChanged();
            }
        } else {
            mAdapter.addData(bean.getData().getList());
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onLoadMoreRequested() {
        if (mPage >= countPage) {
            mAdapter.loadMoreEnd();
        } else {
            mPage++;
            geDataList(mPage);
        }
    }

    @Override
    public void onRefresh() {
        onFresh();
    }


    public class AbSpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int left;
        private int right;

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

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            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;
        }
    }
}
