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

import com.casic.dcms.R;
import com.casic.dcms.adapter.CaseVerifiedResultAdapter;
import com.casic.dcms.base.BaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseVerifiedBean;
import com.casic.dcms.mvp.presenter.CaseVerifiedPresenterImpl;
import com.casic.dcms.mvp.view.ICaseVerifiedView;
import com.casic.dcms.ui.CaseVerifiedDetailActivity;
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 CaseVerifiedFragment extends BaseFragment implements ICaseVerifiedView {

    private static final String TAG = "CaseHandledFragment";
    private Context context;
    @BindView(R.id.emptyView)
    QMUIEmptyView emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.caseRecyclerView)
    RecyclerView caseRecyclerView;
    private CaseVerifiedPresenterImpl caseVerifiedPresenter;
    private int pageIndex = 1;
    private CaseVerifiedResultAdapter adapter;
    /**
     * 临时存储网络请求到的数据
     */
    private List<CaseVerifiedBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private static WeakReferenceHandler weakReferenceHandler;

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

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

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

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

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

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

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