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

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.OvertimeCaseAdapter;
import com.casic.dcms.base.AndroidxBaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.OvertimeCaseBean;
import com.casic.dcms.databinding.FragmentOvertimeCaseBinding;
import com.casic.dcms.mvp.presenter.impl.OvertimeCaseListPresenterImpl;
import com.casic.dcms.mvp.view.IOvertimeCaseListView;
import com.casic.dcms.ui.CaseTodoDetailActivity;
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 CaseTodoFragment extends AndroidxBaseFragment<FragmentOvertimeCaseBinding> implements IOvertimeCaseListView {

    private static final String TAG = "CaseTodoFragment";
    private Context context;
    private int pageIndex = 1;
    private OvertimeCaseListPresenterImpl overtimeCaseListPresenter;
    private List<OvertimeCaseBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private OvertimeCaseAdapter adapter;
    private static WeakReferenceHandler weakReferenceHandler;

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

    @Override
    protected void initData() {
        overtimeCaseListPresenter = new OvertimeCaseListPresenterImpl(this);
        //isSupervise	否	string	是否督办,0-未督办，1-已督办
        overtimeCaseListPresenter.onReadyRetrofitRequest("0", 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;
                overtimeCaseListPresenter.onReadyRetrofitRequest("0", pageIndex);
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                overtimeCaseListPresenter.onReadyRetrofitRequest("0", pageIndex);
            }
        });
    }

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

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

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

        @Override
        public void handleMessage(Message msg) {
            CaseTodoFragment caseTodoFragment = reference.get();
            if (msg.what == Constant.CASE_OVERTIME_OK) {
                Log.d(TAG, "超时督办成功，更新列表");
                caseTodoFragment.isRefresh = true;
                //刷新之后页码重置
                caseTodoFragment.pageIndex = 1;
                caseTodoFragment.overtimeCaseListPresenter.onReadyRetrofitRequest("0", caseTodoFragment.pageIndex);
            } else if (msg.what == 202104283) {
                if (caseTodoFragment.isRefresh || caseTodoFragment.isLoadMore) {
                    caseTodoFragment.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (caseTodoFragment.dataBeans.size() == 0) {
                        caseTodoFragment.viewBinding.emptyView.show("没有紧急案卷", null);
                    } else {
                        caseTodoFragment.viewBinding.emptyView.hide();
                        caseTodoFragment.adapter = new OvertimeCaseAdapter(caseTodoFragment.context, caseTodoFragment.dataBeans);
                        caseTodoFragment.viewBinding.caseRecyclerView.setLayoutManager(new LinearLayoutManager(caseTodoFragment.context));
                        caseTodoFragment.viewBinding.caseRecyclerView.addItemDecoration(new DividerItemDecoration(caseTodoFragment.context, DividerItemDecoration.VERTICAL));
                        caseTodoFragment.viewBinding.caseRecyclerView.setAdapter(caseTodoFragment.adapter);
                        caseTodoFragment.adapter.setOnItemClickListener(new OvertimeCaseAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                Intent intent = new Intent(caseTodoFragment.context, CaseTodoDetailActivity.class);
                                intent.putExtra("title", "超时督办");
                                intent.putExtra("id", caseTodoFragment.dataBeans.get(position).getId());
                                caseTodoFragment.startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void obtainOvertimeCaseList(OvertimeCaseBean resultBean) {
//        Log.d(TAG, "obtainUrgentCaseList: " + new Gson().toJson(resultBean));
        if (resultBean.isSuccess()) {
            List<OvertimeCaseBean.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(202104283);
        }
    }

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