package com.xxfc.discovery.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.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.rv.component.utils.DateUtils;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.adapter.DiscoveryAskAdapter;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryAskBean;
import com.xxfc.discovery.event.DiscoveryAddEvent;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.yuyife.okgo.OkGoUtil;
import java.util.LinkedHashMap;
import java.util.Map;

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

/**
 * 问答
 */
public class QuestionAndAnswerFragment extends BaseFragment<DiscoveryPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {

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

    private DiscoveryAskAdapter mAdapter;
    private int countPage;
    private int mPage;


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

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

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

        mAdapter = new DiscoveryAskAdapter();
        mAdapter.setOnLoadMoreListener(this, rvContent);
        rvContent.setLayoutManager(new LinearLayoutManager(_mActivity));
        rvContent.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DiscoveryAskBean.DataBeanX.DataBean item = (DiscoveryAskBean.DataBeanX.DataBean) adapter.getItem(position);
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_DETAILQUESTIONANDANSWER)
                        .withString("id",item.getId())
                        .navigation();
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                DiscoveryAskBean.DataBeanX.DataBean item = (DiscoveryAskBean.DataBeanX.DataBean) adapter.getItem(position);
                int id = view.getId();
                if (id == R.id.ll_item_like){
                       Map<String, Object> headMap = new LinkedHashMap<>();
                       if (OkGoUtil.getToken() != null) {
                           headMap.put("Authorization", OkGoUtil.getToken());
                           Map<String, Object> map = new LinkedHashMap<>();
                           map.put("questionId", item.getId());

                            if (item.isPraise()) {
                               mPresenter.postData(RvFrameConfig.HOST, 2, DiscoveryApi.DISCOVERY_IMPRAISE_DELETE, BaseBean.class, map, headMap, true);
                           }else {
                               map.put("time", DateUtils.getCurTimeMillis());
                               mPresenter.postData(RvFrameConfig.HOST, 1, DiscoveryApi.DISCOVERY_IMPRAISE_ADD, BaseBean.class, map, headMap, true);
                           }
                       }
                }
            }
        });
    }

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


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

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

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        switch (requestType){
            case 0:
                processData((DiscoveryAskBean) result);
                break;

            case 1:
                onFresh();
                break;

            case 2:
                onFresh();
                break;
        }
    }
    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        mSimpleRefreshLayout.onRefreshComplete();
    }

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

    /**
     * 问答请求
     *
     * @param page
     */
    private void geDataList(int page) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        Map<String, Object> map = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
        }
        map.put("page", page);
        mPresenter.getData( DiscoveryApi.HOST,0, DiscoveryApi.DISCOVERY_IMQUESTION_LIST, DiscoveryAskBean.class, map,headMap, page == 1 ? false : false);
    }

    private void processData(DiscoveryAskBean bean) {
        if (mPage == 1) {
            countPage = bean.getData().getTotalPage();
            mAdapter.setNewData(bean.getData().getData());
            if (bean.getData().getTotalCount() == 0) {
                mAdapter.setEmptyView(getEmptyView(rvContent, -1, _mActivity.getString(R.string.discovery_question_and_answer_null)));
                mAdapter.notifyDataSetChanged();
            }
        } else {
            mAdapter.addData(bean.getData().getData());
            mAdapter.loadMoreComplete();
        }
    }

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