package com.casic.dcms.view;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
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.ActivityMaintainRecordBinding;
import com.casic.dcms.model.MaintainRecordBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.vm.BridgeViewModel;
import com.casic.dcms.widgets.RangeDateActionSheet;
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.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 MaintainRecordActivity extends AndroidxBaseActivity<ActivityMaintainRecordBinding> {

    private final Context context = MaintainRecordActivity.this;
    private BridgeViewModel bridgeViewModel;
    private List<MaintainRecordBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private WeakReferenceHandler weakReferenceHandler;
    private NormalRecyclerAdapter<MaintainRecordBean.DataBean.RowsBean> adapter;
    private int pageIndex = 1;
    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() {
        bridgeViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "查询记录中，请稍后");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        bridgeViewModel = new ViewModelProvider(this).get(BridgeViewModel.class);
        bridgeViewModel.recordModel.observe(this, new Observer<MaintainRecordBean>() {
            @Override
            public void onChanged(MaintainRecordBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<MaintainRecordBean.DataBean.RowsBean> 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(20210622);
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        pageIndex = 1;
        obtainMaintainRecord("", "");
    }

    @Override
    protected void initEvent() {
        viewBinding.calendarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new RangeDateActionSheet.Builder().setContext(context).setOnActionSheetListener(new RangeDateActionSheet.OnDateRangeSelectedListener() {
                    @Override
                    public void onDateRangeSelected(String startDate, String endDate) {
                        viewBinding.dateView.setText(startDate + "~" + endDate);

                        pageIndex = 1;
                        obtainMaintainRecord(startDate, endDate);
                    }
                }).build().show();
            }
        });
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                pageIndex = 1;
                obtainMaintainRecord("", "");
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                obtainMaintainRecord("", "");
            }
        });
    }

    private void obtainMaintainRecord(String start, String end) {
        bridgeViewModel.obtainMaintainRecord(start, end, pageIndex);
    }

    private final Handler.Callback callback = msg -> {
        if (msg.what == 20210622) {
            if (dataBeans.size() == 0) {
                viewBinding.emptyView.show(false, "抱歉，没有查到相关养护记录", null, "刷新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pageIndex = 1;
                        obtainMaintainRecord("", "");
                    }
                });
            } else {
                viewBinding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<MaintainRecordBean.DataBean.RowsBean>(R.layout.item_maintain_rv_l, dataBeans) {
                    @Override
                    public void convertView(ViewHolder viewHolder, int position, MaintainRecordBean.DataBean.RowsBean item) {
                        String description = item.getDescription();
                        if (TextUtils.isEmpty(description)) {
                            viewHolder.setVisibility(R.id.descriptionImageView, View.GONE);
                        } else {
                            viewHolder.setVisibility(R.id.descriptionImageView, View.VISIBLE);
                            viewHolder.setOnClickListener(R.id.descriptionImageView, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    StringHub.show(context, description);
                                }
                            });
                        }
                        viewHolder.setText(R.id.bridgeNameView, item.getBridgeName())
                                .setText(R.id.maintainContentView, item.getContent())
                                .setText(R.id.maintainTimeView, item.getMaintainTimeStr());
                    }
                };
                viewBinding.recordRecyclerView.setAdapter(adapter);
            }
        }
        return true;
    };
}