package com.casic.dcms.fragment.dept;

import android.content.Intent;
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.TodoCaseModel;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.view.dept.DeptTodoDetailActivity;
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.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 DeptCaseTodoFragment extends AndroidxBaseFragment<FragmentDeptCaseBinding> {

    private WeakReferenceHandler weakReferenceHandler;
    private DeptCaseViewModel deptCaseViewModel;
    private NormalRecyclerAdapter<TodoCaseModel.DataModel.RowsModel> adapter;
    private List<TodoCaseModel.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.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.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(20210630);
                    }
                }
            }
        });
        getDeptStatusCaseList();
    }

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

    @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 == 20210630) {
                if (dataBeans.size() == 0) {
                    getBinding().emptyView.show(null, "您暂时没有待办案卷");
                } else {
                    getBinding().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, item.getDescription())
                                    .setText(R.id.casePlaceView, "发生地点：" + item.getFieldintro())
                                    .setText(R.id.caseTimeView, "上报时间：" + item.getReportTime());
                        }
                    };
                    getBinding().recyclerView.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;
        }
    };
}
