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

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 com.casic.dcms.adapter.CaseVerifyResultAdapter;
import com.casic.dcms.base.AndroidxBaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseVerifyBean;
import com.casic.dcms.databinding.FragmentVerifyCaseBinding;
import com.casic.dcms.mvp.presenter.impl.CaseVerifyPresenterImpl;
import com.casic.dcms.mvp.view.ICaseVerifyView;
import com.casic.dcms.ui.CaseVerifyDetailActivity;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.ToastHelper;
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;

public class CaseVerifyFragment extends AndroidxBaseFragment<FragmentVerifyCaseBinding> implements ICaseVerifyView {

    private static final String TAG = "CaseVerifyFragment";
    private Context context;
    private CaseVerifyPresenterImpl caseVerifyPresenter;
    private int pageIndex = 1;
    private CaseVerifyResultAdapter adapter;
    /**
     * 临时存储网络请求到的数据
     */
    private List<CaseVerifyBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private static WeakReferenceHandler weakReferenceHandler;

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

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

        weakReferenceHandler = new WeakReferenceHandler(this);
    }

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

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

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

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

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

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

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