package com.rv.rvmine.fragment;

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

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.weight.ToastView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.home.rv.module.ApiConfig;
import com.rv.rvmine.R;
import com.rv.rvmine.R2;
import com.rv.rvmine.adapter.MyReleaseVideoAdapter;
import com.rv.rvmine.bean.MyReleaseBean;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;

/**
 * 短视频
 */
public class MyReleaseVideoFragment extends BaseFragment<CommonPresenter> implements SimpleRefreshLayout.OnSimpleRefreshListener {

    @BindView(R2.id.rv_content)
    RecyclerView rvContent;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.ll_delete)
    LinearLayout llDelete;
    private int countPage;
    private int mPage;

    private MyReleaseVideoAdapter mAdapter;
    private List<MyReleaseBean.DataBeanX.DataBean> delteMsgs;

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

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

    public void changeShowNormal() {
        if (this.isShowDelete) {
            changeShowDelete();
        }
    }

    @Override
    public void changeShowDelete() {
        super.changeShowDelete();
        if (this.isShowDelete) {
            llDelete.setVisibility(View.VISIBLE);
        } else {
            llDelete.setVisibility(View.GONE);
            mAdapter.clear();
        }
        mAdapter.changeViewShowState(this.isShowDelete);
    }

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

        mAdapter = new MyReleaseVideoAdapter();

        final 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();
                }
            }
        });

        llDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAdapter.getSelectLists().size() == 0) {
                    ToastView.getInstance(getContext()).showToastContent("暂无选中的视频");
                    return;
                }
                delteMsgs = mAdapter.getSelectLists();
                deleteData();
            }
        });

        rvContent.setLayoutManager(staggeredGridLayoutManager);
        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) {
                MyReleaseBean.DataBeanX.DataBean item = (MyReleaseBean.DataBeanX.DataBean) adapter.getItem(position);
                if (item != null) {
                    if (isShowDelete) {
                        mAdapter.changeBeanStatus(item);
                        mAdapter.notifyItemChanged(position);
                    } else {

//                    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();
                    }
                }
            }
        });

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


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

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        switch (requestType) {
            case 0:
                processData((MyReleaseBean) result);
                break;
            case 2:
                Iterator<MyReleaseBean.DataBeanX.DataBean> iterator = delteMsgs.iterator();
                while (iterator.hasNext()) {
                    MyReleaseBean.DataBeanX.DataBean bean = iterator.next();
                    if (mAdapter.getData().contains(bean)) {
                        int indexOf = mAdapter.getData().lastIndexOf(bean);
                        mAdapter.removeSelect(bean);
                        mAdapter.remove(indexOf);
                        mAdapter.notifyItemChanged(indexOf);
                    }
                }
                break;
        }
    }

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

    private void deleteData() {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> header = new LinkedHashMap<>();
            header.put("Authorization", OkGoUtil.getToken());

            Map<String, Object> map = new LinkedHashMap<>();
            StringBuilder builder = new StringBuilder();
            for (MyReleaseBean.DataBeanX.DataBean bean : delteMsgs) {
                builder.append(bean.getMsgId()).append(",");
            }
            map.put("ids", builder.toString().substring(0, builder.lastIndexOf(",")));
            mPresenter.getData(RvFrameConfig.HOST, 2, ApiConfig.RVENTHUSIAST_MSG_DELETES, BaseBean.class, map, header, true);
        }
    }

    private void processData(MyReleaseBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getPageSize();
            mAdapter.setNewData(bean.getData().getData());
            if (bean.getData().getTotalCount() == 0) {
                mAdapter.setEmptyView(getEmptyView(rvContent, -1, "暂无发布的数据"));
                mAdapter.notifyDataSetChanged();
            }
        } else {
            mAdapter.addData(bean.getData().getData());
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onRefresh() {
        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);
        map.put("type", "4");
        mPresenter.getData(RvFrameConfig.HOST, 0, ApiConfig.RVENTHUSIAST_GETBYUSERID_LIST, MyReleaseBean.class, map, headMap, page == 1 ? true : false);
    }

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