package com.xxfc.discovery.fragment;

import android.graphics.Rect;
import android.os.Bundle;
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.url.Constance;
import com.frame.rv.config.RvFrameConfig;
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.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryIMTokenBean;
import com.xxfc.discovery.bean.DiscoveryRecommendBean;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.xxrv.video.activity.TriListActivity;
import com.xxrv.video.bean.circle.DiscoveryDataBean;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;

/**
 * 推荐
 */
public class RecommendFragment extends BaseFragment<DiscoveryPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {

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

    private DiscoveryRecommendAdapter mRecommendAdapter;
    private int countPage;
    private int mPage;

    private DiscoveryRecommendBean.DataBeanX.DataBean itemDatabean;

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

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

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        Display display = _mActivity.getWindowManager().getDefaultDisplay();
        mRecommendAdapter = new DiscoveryRecommendAdapter(display);

        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.addItemDecoration(new AbSpacesItemDecoration(30, 10));// 分割线。
        rvContent.setAdapter(mRecommendAdapter);
        mRecommendAdapter.bindToRecyclerView(rvContent);
        mRecommendAdapter.setEnableLoadMore(true);
        mRecommendAdapter.disableLoadMoreIfNotFullPage();

        mRecommendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int 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));
                    }
                }
            }
        });

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


    private void isLike() {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, 2, DiscoveryApi.DISCOVERY_IM_LOGIN, DiscoveryIMTokenBean.class, headMap, headMap, true);
        }
    }


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

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

    /**
     * 请求数据
     *
     * @param page
     */
    private void geDataList(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, 0, DiscoveryApi.DISCOVERY_HOTMSG_LIST, DiscoveryRecommendBean.class, map, headMap, page == 1 ? false : false);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        switch (requestType) {
            case 0:
                processData((DiscoveryRecommendBean) result);
                break;
            case 2:
                DiscoveryIMTokenBean intokenBean = (DiscoveryIMTokenBean) result;
                setIMData(intokenBean);
                break;
            case 3:
                onFresh();
                break;
            case 4:
                onFresh();
                break;
        }
    }

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

    private void setIMData(DiscoveryIMTokenBean bean) {
        if ("0".equals(itemDatabean.getIsPraise())) {//0：未点赞 1：已点赞
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", bean.getData());
            map.put("messageId", itemDatabean.getMsgId());
            mPresenter.postData(3, DiscoveryApi.DISCOVERY_PRAISE_ADD, BaseBean.class, map, true);
        } else {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", bean.getData());
            map.put("messageId", itemDatabean.getMsgId());
            mPresenter.postData(4, DiscoveryApi.DISCOVERY_PRAISE_DELETE, BaseBean.class, map, true);
        }
    }


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

    @Override
    public void onLoadMoreRequested() {
        if (mPage >= countPage) {
            mRecommendAdapter.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;
        }
    }
}
