package com.casic.dcms.view;

import android.content.Context;
import android.os.Handler;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityCaseListBinding;
import com.casic.dcms.model.CaseSearchResultBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.vm.CaseViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.pengxh.androidx.lite.adapter.NormalRecyclerAdapter;
import com.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.hub.ContextHub;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.pengxh.androidx.lite.vm.LoadState;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

public class CaseSearchResultActivity extends AndroidxBaseActivity<ActivityCaseListBinding> {

    private final Context context = this;
    private WeakReferenceHandler weakReferenceHandler;
    private CaseViewModel caseViewModel;
    private NormalRecyclerAdapter<CaseSearchResultBean.DataDTO.RowsDTO> 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<CaseSearchResultBean.DataDTO.RowsDTO> dataBeans = new ArrayList<>();
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

        viewBinding.titleBarLayout.titleView.setText("查询结果");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);

        eorc = getIntent().getStringExtra("eorc");
        typeCode = getIntent().getStringExtra("typeCode");
        typeDetailCode = getIntent().getStringExtra("typeDetailCode");
        caseState = getIntent().getStringExtra("caseState");
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        obtainSearchResult();
    }

    private void obtainSearchResult() {
        //加载第一页
        caseViewModel.searchCase(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;
                obtainSearchResult();
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                obtainSearchResult();
            }
        });

        caseViewModel.searchResultModel.observe(this, new Observer<CaseSearchResultBean>() {
            @Override
            public void onChanged(CaseSearchResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<CaseSearchResultBean.DataDTO.RowsDTO> dataRows = resultBean.getData().getRows();
                    if (isRefresh) {
                        adapter.setRefreshData(dataRows);
                        viewBinding.refreshLayout.finishRefresh();
                        isRefresh = false;
                    } else if (isLoadMore) {
                        if (dataRows.size() == 0) {
                            StringHub.show(context, "到底了，别拉了");
                        }
                        adapter.setLoadMoreData(dataRows);
                        viewBinding.refreshLayout.finishLoadMore();
                        isLoadMore = false;
                    } else {
                        dataBeans = dataRows;
                        weakReferenceHandler.sendEmptyMessage(20210425);
                    }
                }
            }
        });
        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (!isRefresh && !isLoadMore) {
                    if (loadState == LoadState.Loading) {
                        DialogHelper.showLoadingDialog(context, "案卷查询中，请稍后");
                    } else {
                        DialogHelper.dismissLoadingDialog();
                    }
                }
            }
        });
    }

    /**
     * 弱应用Handler，防止内存泄漏
     */
    private final Handler.Callback callback = msg -> {
        if (msg.what == 20210425) {
            if (dataBeans.size() == 0) {
                viewBinding.emptyView.show(false, "抱歉，没有查到符合您规定条件的案卷", null, "", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pageIndex = 1;
                        obtainSearchResult();
                    }
                });
            } else {
                viewBinding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<CaseSearchResultBean.DataDTO.RowsDTO>(R.layout.item_case_rv_l, dataBeans) {

                    @Override
                    public void convertView(ViewHolder viewHolder, int position, CaseSearchResultBean.DataDTO.RowsDTO item) {
                        viewHolder.setText(R.id.caseTitleView, StringHub.filterSpaceOrEnter(item.getDescription()))
                                .setText(R.id.casePlaceView, "发生地点：" + StringHub.filterSpaceOrEnter(item.getFieldintro()))
                                .setText(R.id.caseTimeView, "上报时间：" + item.getReportTime());
                    }
                };
                viewBinding.caseRecyclerView.setAdapter(adapter);
                adapter.setOnItemClickedListener(new NormalRecyclerAdapter.OnItemClickedListener<CaseSearchResultBean.DataDTO.RowsDTO>() {
                    @Override
                    public void onItemClicked(int position, CaseSearchResultBean.DataDTO.RowsDTO rowsDTO) {
                        ContextHub.navigatePageTo(context, CaseDetailActivity.class, rowsDTO.getId());
                    }
                });
            }
        }
        return true;
    };
}