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

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

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

import com.casic.dcms.adapter.DeptAuthorizeOrAdjustAdapter;
import com.casic.dcms.base.AndroidxBaseFragment;
import com.casic.dcms.bean.AuthorizeOrAdjustBean;
import com.casic.dcms.databinding.FragmentDeptCaseBinding;
import com.casic.dcms.mvp.presenter.impl.DeptAdjustPresenterImpl;
import com.casic.dcms.mvp.view.IDeptAuthorizeOrAdjustView;
import com.casic.dcms.ui.DeptAdjustDetailActivity;
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 DeptCaseAdjustFragment extends AndroidxBaseFragment<FragmentDeptCaseBinding> implements IDeptAuthorizeOrAdjustView {

    private Context context;
    private int pageIndex = 1;
    private boolean isRefresh, isLoadMore = false;
    private List<AuthorizeOrAdjustBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private static WeakReferenceHandler weakReferenceHandler;
    private DeptAuthorizeOrAdjustAdapter adapter;
    private DeptAdjustPresenterImpl adjustPresenter;

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

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

    public static void sendEmptyMessage(int what) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendEmptyMessage(what);
    }

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

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

        @Override
        public void handleMessage(Message msg) {
            DeptCaseAdjustFragment fragment = reference.get();
            if (msg.what == Constant.DEPT_DONE) {
                fragment.isRefresh = true;
                //刷新之后页码重置
                fragment.pageIndex = 1;
                fragment.adjustPresenter.onReadyRetrofitRequest(fragment.pageIndex);
            } else if (msg.what == 2021062107) {
                if (fragment.isRefresh || fragment.isLoadMore) {
                    fragment.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (fragment.dataBeans.size() == 0) {
                        fragment.viewBinding.emptyView.show("您暂时没有待办案卷", null);
                    } else {
                        fragment.viewBinding.emptyView.hide();
                        fragment.adapter = new DeptAuthorizeOrAdjustAdapter(fragment.context, fragment.dataBeans);
                        fragment.viewBinding.caseRecyclerView.setLayoutManager(new LinearLayoutManager(fragment.context));
                        fragment.viewBinding.caseRecyclerView.addItemDecoration(new DividerItemDecoration(fragment.context, DividerItemDecoration.VERTICAL));
                        fragment.viewBinding.caseRecyclerView.setAdapter(fragment.adapter);
                        fragment.adapter.setOnItemClickListener(new DeptAuthorizeOrAdjustAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                Intent intent = new Intent(fragment.context, DeptAdjustDetailActivity.class);
                                intent.putExtra("id", fragment.dataBeans.get(position).getId());
                                fragment.startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void obtainResult(AuthorizeOrAdjustBean resultBean) {
        if (resultBean.isSuccess()) {
            List<AuthorizeOrAdjustBean.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(2021062107);
        }
    }

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