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

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.CaseHandledAdapter;
import com.casic.dcms.base.AndroidxBaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseHandledBean;
import com.casic.dcms.databinding.FragmentHandleCaseBinding;
import com.casic.dcms.mvp.presenter.impl.CaseListHandledPresenterImpl;
import com.casic.dcms.mvp.view.ICaseListHandledView;
import com.casic.dcms.ui.CaseHandledDetailActivity;
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 CaseHandledFragment extends AndroidxBaseFragment<FragmentHandleCaseBinding> implements ICaseListHandledView {

    private static final String TAG = "CaseHandledFragment";
    private Context context;
    private int pageIndex = 1;
    private CaseListHandledPresenterImpl caseHandledListPresenter;
    private boolean isRefresh, isLoadMore = false;
    private List<CaseHandledBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private CaseHandledAdapter adapter;
    private static WeakReferenceHandler weakReferenceHandler;

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

    @Override
    protected void initData() {
        caseHandledListPresenter = new CaseListHandledPresenterImpl(this);
        caseHandledListPresenter.onReadyRetrofitRequest(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;
                caseHandledListPresenter.onReadyRetrofitRequest(pageIndex);
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                caseHandledListPresenter.onReadyRetrofitRequest(pageIndex);
            }
        });
    }

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

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

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

        @Override
        public void handleMessage(Message msg) {
            CaseHandledFragment handledFragment = reference.get();
            if (msg.what == Constant.CASE_HANDLE_OK) {
                Log.d(TAG, "案卷处理成功，更新列表");
                handledFragment.isRefresh = true;
                //刷新之后页码重置
                handledFragment.pageIndex = 1;
                handledFragment.caseHandledListPresenter.onReadyRetrofitRequest(handledFragment.pageIndex);
            } else if (msg.what == 202104288) {
                if (handledFragment.isRefresh || handledFragment.isLoadMore) {
                    handledFragment.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (handledFragment.dataBeans.size() == 0) {
                        handledFragment.viewBinding.emptyView.show("没有案卷需要处理", null);
                    } else {
                        handledFragment.viewBinding.emptyView.hide();
                        handledFragment.adapter = new CaseHandledAdapter(handledFragment.context, handledFragment.dataBeans);
                        handledFragment.viewBinding.caseRecyclerView.setLayoutManager(new LinearLayoutManager(handledFragment.context));
                        handledFragment.viewBinding.caseRecyclerView.addItemDecoration(new DividerItemDecoration(handledFragment.context, DividerItemDecoration.VERTICAL));
                        handledFragment.viewBinding.caseRecyclerView.setAdapter(handledFragment.adapter);
                        handledFragment.adapter.setOnItemClickListener(new CaseHandledAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                Intent intent = new Intent(handledFragment.context, CaseHandledDetailActivity.class);
                                intent.putExtra("id", handledFragment.dataBeans.get(position).getId());
                                handledFragment.startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void obtainCaseHandledList(CaseHandledBean resultBean) {
        if (resultBean.isSuccess()) {
            List<CaseHandledBean.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(202104288);
        }
    }

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