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 androidx.recyclerview.widget.RecyclerView;

import com.casic.dcms.R;
import com.casic.dcms.adapter.CaseHandleAdapter;
import com.casic.dcms.base.BaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseHandleBean;
import com.casic.dcms.mvp.presenter.CaseHandleListPresenterImpl;
import com.casic.dcms.mvp.view.ICaseHandleListView;
import com.casic.dcms.ui.CaseHandleDetailActivity;
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 OvertimeCaseFragment extends BaseFragment implements ICaseHandleListView {

    private static final String TAG = "OvertimeCaseFragment";
    private Context context;
    @BindView(R.id.emptyView)
    QMUIEmptyView emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.caseRecyclerView)
    RecyclerView caseRecyclerView;

    private int pageIndex = 1;
    private List<CaseHandleBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private CaseHandleListPresenterImpl caseHandleListPresenter;
    private CaseHandleAdapter adapter;
    private static WeakReferenceHandler weakReferenceHandler;

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

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

    @Override
    protected void initData() {
        caseHandleListPresenter = new CaseHandleListPresenterImpl(this);
        /**
         * isOvertime	否	String	是否超时,null-所有案卷,1-超时案卷
         * isEmergent	否	String	是否紧急,null-所有案卷,1-紧急案卷
         */
        caseHandleListPresenter.onReadyRetrofitRequest("1", null, 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;
                caseHandleListPresenter.onReadyRetrofitRequest("1", null, Constant.PAGE_LIMIT, pageIndex);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                caseHandleListPresenter.onReadyRetrofitRequest("1", null, Constant.PAGE_LIMIT, 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 WeakReference<OvertimeCaseFragment> reference;

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

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

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

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