package com.casic.dcms.fragment.department;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
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.FragmentDeptCaseBinding;
import com.casic.dcms.model.dept.TodoCaseModel;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.view.department.DeptTodoDetailActivity;
import com.casic.dcms.vm.DeptCaseViewModel;
import com.pengxh.androidx.lite.adapter.NormalRecyclerAdapter;
import com.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseFragment;
import com.pengxh.androidx.lite.hub.StringHub;
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 DeptCaseTodoFragment extends AndroidxBaseFragment<FragmentDeptCaseBinding> {

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

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        handleViewModel = new ViewModelProvider(this).get(DeptCaseViewModel.class);
        handleViewModel.deptTodoCaseListModel.observe(this, new Observer<TodoCaseModel>() {
            @Override
            public void onChanged(TodoCaseModel resultBean) {
                if (resultBean.getCode() == 200) {
                    List<TodoCaseModel.DataModel.RowsModel> dataRows = resultBean.getData().getRows();
                    if (isRefresh) {
                        adapter.setRefreshData(dataRows);
                        viewBinding.refreshLayout.finishRefresh();
                        isRefresh = false;
                    } else if (isLoadMore) {
                        if (dataRows.size() == 0) {
                            StringHub.show(requireContext(), "到底了，别拉了");
                        }
                        adapter.setLoadMoreData(dataRows);
                        viewBinding.refreshLayout.finishLoadMore();
                        isLoadMore = false;
                    } else {
                        dataBeans = dataRows;
                        weakReferenceHandler.sendEmptyMessage(20210630);
                    }
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        pageIndex = 1;
        obtainDeptStatusCaseList();
    }

    private void obtainDeptStatusCaseList() {
        handleViewModel.obtainDeptStatusCaseList(pageIndex, "todo");
    }

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

    private final Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 20210630) {
                if (dataBeans.size() == 0) {
                    viewBinding.emptyView.show(false, "您暂时没有待办案卷", null, "刷新", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pageIndex = 1;
                            obtainDeptStatusCaseList();
                        }
                    });
                } else {
                    viewBinding.emptyView.hide();
                    adapter = new NormalRecyclerAdapter<TodoCaseModel.DataModel.RowsModel>(R.layout.item_case_rv_l, dataBeans) {
                        @Override
                        public void convertView(ViewHolder viewHolder, int position, TodoCaseModel.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, 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<TodoCaseModel.DataModel.RowsModel>() {
                        @Override
                        public void onItemClicked(int position, TodoCaseModel.DataModel.RowsModel rowsModel) {
                            Intent intent = new Intent(requireContext(), DeptTodoDetailActivity.class);
                            intent.putExtra("title", LocaleConstant.DEPT_PAGE_TITLES[0]);
                            intent.putExtra("id", rowsModel.getId());
                            startActivity(intent);
                        }
                    });
                }
            }
            return true;
        }
    };
}
