package com.casic.dcms.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
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.CaseListResultAdapter;
import com.casic.dcms.base.BaseActivity;
import com.casic.dcms.bean.CaseListResultBean;
import com.casic.dcms.mvp.presenter.CaseListPresenterImpl;
import com.casic.dcms.mvp.view.ICaseListView;
import com.casic.dcms.utils.ToastHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
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 CaseListResultActivity extends BaseActivity implements ICaseListView {

    private static final String TAG = "CaseListResultActivity";
    @BindView(R.id.caseTopLayout)
    QMUITopBarLayout caseTopLayout;
    @BindView(R.id.emptyView)
    QMUIEmptyView emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.caseRecyclerView)
    RecyclerView caseRecyclerView;

    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, isLoadMore = false;
    private WeakReferenceHandler weakReferenceHandler;
    private QMUITipDialog searchDialog;

    @Override
    public int initLayoutView() {
        return R.layout.activity_case_list;
    }

    @Override
    protected void setupTopBarLayout() {
        caseTopLayout.setTitle("查询结果").setTextColor(ContextCompat.getColor(this, R.color.white));
        caseTopLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.mainThemeColor));
        caseTopLayout.addLeftImageButton(R.drawable.ic_left_white, 1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        searchDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("查询中，请稍后")
                .create();
        caseListPresenter = new CaseListPresenterImpl(this);
        weakReferenceHandler = new WeakReferenceHandler(this);
        typeCode = getIntent().getStringExtra("typeCode");
        typeDetailCode = getIntent().getStringExtra("typeDetailCode");
        caseState = getIntent().getStringExtra("caseState");
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        eorc = getIntent().getStringExtra("eorc");
        //加载第一页
        caseListPresenter.onReadyRetrofitRequest(typeCode, typeDetailCode, caseState, startTime,
                endTime, eorc, pageIndex);
    }

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

    /**
     * 弱应用Handler，防止内存泄漏
     */
    private static class WeakReferenceHandler extends Handler {
        private 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.emptyView.show("抱歉，没有查到符合您规定条件的案卷", null);
                    } else {
                        resultActivity.emptyView.hide();
                        resultActivity.adapter = new CaseListResultAdapter(resultActivity, resultActivity.dataBeans);
                        resultActivity.caseRecyclerView.setLayoutManager(new LinearLayoutManager(resultActivity));
                        resultActivity.caseRecyclerView.addItemDecoration(new DividerItemDecoration(resultActivity, DividerItemDecoration.VERTICAL));
                        resultActivity.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() {
        searchDialog.show();
    }

    @Override
    public void hideProgress() {
        searchDialog.dismiss();
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (caseListPresenter != null) {
            caseListPresenter.disposeRetrofitRequest();
        }
    }
}
