package com.casic.dcms.ui.fragment.check;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.casic.dcms.R;
import com.casic.dcms.adapter.CaseCheckResultAdapter;
import com.casic.dcms.base.BaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseCheckBean;
import com.casic.dcms.mvp.presenter.CaseCheckPresenterImpl;
import com.casic.dcms.mvp.view.ICaseCheckView;
import com.casic.dcms.ui.CaseCheckDetailActivity;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.ToastHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CaseCheckFragment extends BaseFragment implements ICaseCheckView {

    private static final String TAG = "CaseCheckFragment";
    private Context context;
    @BindView(R.id.emptyView)
    QMUIEmptyView emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.caseRecyclerView)
    RecyclerView caseRecyclerView;
    private CaseCheckPresenterImpl caseCheckPresenter;
    private int pageIndex = 1;
    private CaseCheckResultAdapter adapter;
    /**
     * 临时存储网络请求到的数据
     */
    private List<CaseCheckBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private static WeakReferenceHandler weakReferenceHandler;

    @Override
    protected int initLayoutView() {
        return R.layout.fragment_check_case_check;
    }

    @Override
    protected void setupTopBarLayout() {
        context = getContext();
    }

    @Override
    protected void initData() {
        caseCheckPresenter = new CaseCheckPresenterImpl(this);
        caseCheckPresenter.onReadyRetrofitRequest(Constant.PAGE_LIMIT, pageIndex);

        weakReferenceHandler = new WeakReferenceHandler(this);
    }

    @Override
    protected void initEvent() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                pageIndex = 1;
                caseCheckPresenter.onReadyRetrofitRequest(Constant.PAGE_LIMIT, pageIndex);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                caseCheckPresenter.onReadyRetrofitRequest(Constant.PAGE_LIMIT, pageIndex);
            }
        });
    }

    /**
     * 供{@link com.casic.dcms.ui.CaseCheckDetailActivity#obtainCaseHandleResult(ActionResultBean)}调用
     */
    public static void sendEmptyMessage(int what) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendEmptyMessage(what);
    }

    private static class WeakReferenceHandler extends Handler {
        private WeakReference<CaseCheckFragment> reference;

        private WeakReferenceHandler(CaseCheckFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            CaseCheckFragment checkFragment = reference.get();
            if (msg.what == Constant.CASE_CHECK_OK) {
                Log.d(TAG, "核查成功，更新列表");
                checkFragment.isRefresh = true;
                //刷新之后页码重置
                checkFragment.pageIndex = 1;
                checkFragment.caseCheckPresenter.onReadyRetrofitRequest(Constant.PAGE_LIMIT, checkFragment.pageIndex);
            } else if (msg.what == 202104251) {
                if (checkFragment.isRefresh || checkFragment.isLoadMore) {
                    checkFragment.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (checkFragment.dataBeans.size() == 0) {
                        checkFragment.emptyView.show("您暂时没有待办案卷", null);
                    } else {
                        checkFragment.emptyView.hide();
                        checkFragment.adapter = new CaseCheckResultAdapter(checkFragment.context, checkFragment.dataBeans);
                        checkFragment.caseRecyclerView.setLayoutManager(new LinearLayoutManager(checkFragment.context));
                        checkFragment.caseRecyclerView.addItemDecoration(new DividerItemDecoration(checkFragment.context, DividerItemDecoration.VERTICAL));
                        checkFragment.caseRecyclerView.setAdapter(checkFragment.adapter);
                        checkFragment.adapter.setOnItemClickListener(new CaseCheckResultAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                Intent intent = new Intent(checkFragment.context, CaseCheckDetailActivity.class);
                                intent.putExtra("id", checkFragment.dataBeans.get(position).getId());
                                checkFragment.startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void obtainCheckListResult(CaseCheckBean resultBean) {
        if (resultBean.isSuccess()) {
            List<CaseCheckBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
            if (isRefresh) {
                dataBeans.clear();//下拉刷新必须先清空之前的List，不然会出现数据重复的问题
                dataBeans = dataRows;
                refreshLayout.finishRefresh();
                isRefresh = false;
            } else if (isLoadMore) {
                if (dataRows.size() == 0) {
                    ToastHelper.showToast("到底了，别拉了", ToastHelper.INFO);
                }
                dataBeans.addAll(dataRows);
                refreshLayout.finishLoadMore();
                isLoadMore = false;
            } else {
                dataBeans = dataRows;
            }
            weakReferenceHandler.sendEmptyMessage(202104251);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (caseCheckPresenter != null) {
            caseCheckPresenter.disposeRetrofitRequest();
        }
    }
}
