package com.casic.dcms.fragment.dept;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

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

import com.casic.dcms.R;
import com.casic.dcms.adapter.NormalRecyclerAdapter;
import com.casic.dcms.databinding.FragmentDeptCaseBinding;
import com.casic.dcms.model.dept.HandledCaseModel;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.view.CaseDetailActivity;
import com.casic.dcms.vm.DeptCaseViewModel;
import com.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseFragment;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
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 DeptCaseHandledFragment extends AndroidxBaseFragment<FragmentDeptCaseBinding> {

    private WeakReferenceHandler weakReferenceHandler;
    private DeptCaseViewModel deptCaseViewModel;
    private NormalRecyclerAdapter<HandledCaseModel.DataModel.RowsModel> adapter;
    private List<HandledCaseModel.DataModel.RowsModel> dataBeans = new ArrayList<>();
    private int page = 1;
    private boolean isRefresh, isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        deptCaseViewModel = new ViewModelProvider(this).get(DeptCaseViewModel.class);
        deptCaseViewModel.deptHandledCaseListModel.observe(this, new Observer<HandledCaseModel>() {
            @Override
            public void onChanged(HandledCaseModel resultBean) {
                if (resultBean.isSuccess()) {
                    List<HandledCaseModel.DataModel.RowsModel> dataRows = resultBean.getData().getRows();
                    if (isRefresh) {
                        adapter.refresh(dataRows);
                        getBinding().refreshLayout.finishRefresh();
                        isRefresh = false;
                    } else if (isLoadMore) {
                        if (dataRows.size() == 0) {
                            StringKit.show(requireContext(), "到底了，别拉了");
                        }
                        adapter.loadMore(dataRows);
                        getBinding().refreshLayout.finishLoadMore();
                        isLoadMore = false;
                    } else {
                        dataBeans = dataRows;
                        weakReferenceHandler.sendEmptyMessage(2021062104);
                    }
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        getDeptStatusCaseList();
    }

    private void getDeptStatusCaseList() {
        deptCaseViewModel.getDeptStatusCaseList(requireContext(), page, "handled");
    }

    @Override
    protected void initEvent() {
        getBinding().refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                page = 1;
                getDeptStatusCaseList();
            }
        });
        getBinding().refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                isLoadMore = true;
                page++;
                getDeptStatusCaseList();
            }
        });
    }

    private final Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 2021062104) {
                if (dataBeans.size() == 0) {
                    getBinding().emptyView.show(null, "您还没有处理任何案卷");
                } else {
                    getBinding().emptyView.hide();
                    adapter = new NormalRecyclerAdapter<HandledCaseModel.DataModel.RowsModel>(R.layout.item_case_rv_l, dataBeans) {
                        @Override
                        public void convertView(ViewHolder viewHolder, int position, HandledCaseModel.DataModel.RowsModel item) {
                            String fileIdVerify = item.getFileIdVerify();
                            if (!TextUtils.isEmpty(fileIdVerify)) {
                                String[] split = fileIdVerify.split(",");
                                String firstImage = split[0];
                                if (firstImage.endsWith(".jpg") || firstImage.contains(".jpeg") || firstImage.contains(".png")) {
                                    viewHolder.setImageResource(R.id.caseImageView, StringHelper.appendCompleteURL(firstImage));
                                }
                            }
                            viewHolder.setText(R.id.caseTitleView, item.getDescription())
                                    .setText(R.id.casePlaceView, "发生地点：" + item.getFieldintro())
                                    .setText(R.id.caseTimeView, "上报时间：" + item.getReportTime());
                        }
                    };
                    getBinding().recyclerView.setAdapter(adapter);
                    adapter.setOnItemClickedListener(new NormalRecyclerAdapter.OnItemClickedListener<HandledCaseModel.DataModel.RowsModel>() {
                        @Override
                        public void onItemClicked(int position, HandledCaseModel.DataModel.RowsModel rowsModel) {
                            ContextKit.navigatePageTo(requireContext(), CaseDetailActivity.class, rowsModel.getId());
                        }
                    });
                }
            }
            return true;
        }
    };
}
