package com.casic.dcms.ui;

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.CaseListResultAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.CaseListResultBean;
import com.casic.dcms.databinding.ActivityCaseListBinding;
import com.casic.dcms.mvp.presenter.impl.CaseListPresenterImpl;
import com.casic.dcms.mvp.view.ICaseListView;
import com.casic.dcms.utils.OtherUtils;
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 CaseListResultActivity extends AndroidxBaseActivity<ActivityCaseListBinding> implements ICaseListView {

    private CaseListPresenterImpl caseListPresenter;
    private CaseListResultAdapter adapter;
    private String typeCode;
    private String typeDetailCode;
    private String caseState;
    private String startTime;
    private String endTime;
    private String eorc;
    private int pageIndex = 1;

    /**
     * 临时存储网络请求到的数据
     */
    private List<CaseListResultBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh = false;
    private boolean isLoadMore = false;
    private WeakReferenceHandler weakReferenceHandler;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("查询结果");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        caseListPresenter = new CaseListPresenterImpl(this);
        weakReferenceHandler = new WeakReferenceHandler(this);
        eorc = getIntent().getStringExtra("eorc");
        typeCode = getIntent().getStringExtra("typeCode");
        typeDetailCode = getIntent().getStringExtra("typeDetailCode");
        caseState = getIntent().getStringExtra("caseState");
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        //加载第一页
        caseListPresenter.onReadyRetrofitRequest(
                eorc, typeCode, typeDetailCode, caseState, startTime,
                endTime, "0", pageIndex
        );
    }

    @Override
    protected void initEvent() {
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                pageIndex = 1;
                caseListPresenter.onReadyRetrofitRequest(eorc, typeCode, typeDetailCode, caseState,
                        startTime, endTime, "0", pageIndex);
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                caseListPresenter.onReadyRetrofitRequest(eorc, typeCode, typeDetailCode, caseState, startTime,
                        endTime, "0", pageIndex);
            }
        });
    }

    /**
     * 弱应用Handler，防止内存泄漏
     */
    private static class WeakReferenceHandler extends Handler {

        private final WeakReference<CaseListResultActivity> reference;

        private WeakReferenceHandler(CaseListResultActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            CaseListResultActivity resultActivity = reference.get();
            if (msg.what == 20210425) {
                if (resultActivity.isRefresh || resultActivity.isLoadMore) {
                    resultActivity.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (resultActivity.dataBeans.size() == 0) {
                        resultActivity.viewBinding.emptyView.show("抱歉，没有查到符合您规定条件的案卷", null);
                    } else {
                        resultActivity.viewBinding.emptyView.hide();
                        resultActivity.adapter = new CaseListResultAdapter(resultActivity, resultActivity.dataBeans);
                        resultActivity.viewBinding.caseRecyclerView.setLayoutManager(new LinearLayoutManager(resultActivity));
                        resultActivity.viewBinding.caseRecyclerView.addItemDecoration(new DividerItemDecoration(resultActivity, DividerItemDecoration.VERTICAL));
                        resultActivity.viewBinding.caseRecyclerView.setAdapter(resultActivity.adapter);
                        resultActivity.adapter.setOnItemClickListener(new CaseListResultAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                Intent intent = new Intent(resultActivity, CaseDetailActivity.class);
                                intent.putExtra("id", resultActivity.dataBeans.get(position).getId());
                                resultActivity.startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(this, "案卷查询中，请稍后");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @Override
    public void obtainCaseListData(CaseListResultBean resultBean) {
        if (resultBean.getCode() == 200) {
            List<CaseListResultBean.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;
            }
            //更新RecyclerView
            weakReferenceHandler.sendEmptyMessage(20210425);
        }
    }

    @Override
    protected void onDestroy() {
        caseListPresenter.disposeRetrofitRequest();
        super.onDestroy();
    }
}