package com.casic.dcms.fragment;

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

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.casic.dcms.adapter.LightResultAdapter;
import com.casic.dcms.databinding.FragmentLightListBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.LightListBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.vm.LightViewModel;
import com.casic.dcms.widgets.LightDetailDialog;
import com.pengxh.androidx.lite.base.AndroidxBaseFragment;
import com.pengxh.androidx.lite.hub.StringHub;
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;

//TODO 刷新加载待调试，可能有问题
public class LightOnListFragment extends AndroidxBaseFragment<FragmentLightListBinding> {

    private static final String TAG = "LightOnListFragment";
    private WeakReferenceHandler weakReferenceHandler;
    private LightViewModel lightViewModel;
    private LightResultAdapter adapter;
    private List<LightListBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private int pageIndex = 1;
    private boolean isRefresh, isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        lightViewModel = new ViewModelProvider(this).get(LightViewModel.class);
    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    public void onResume() {
        obtainLightList();
        super.onResume();
    }

    private void obtainLightList() {
        lightViewModel.obtainLightList(2 * LocaleConstant.PAGE_LIMIT, pageIndex);
    }

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

        lightViewModel.lightListModel.observe(this, new Observer<LightListBean>() {
            @Override
            public void onChanged(LightListBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<LightListBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
                    if (isRefresh) {
                        dataBeans.clear();//下拉刷新必须先清空之前的List，不然会出现数据重复的问题
                        dataBeans = dataRows;
                        viewBinding.refreshLayout.finishRefresh();
                        isRefresh = false;
                    } else if (isLoadMore) {
                        if (dataRows.size() == 0) {
                            StringHub.show(requireContext(), "到底了，别拉了");
                        }
                        dataBeans.addAll(dataRows);
                        viewBinding.refreshLayout.finishLoadMore();
                        isLoadMore = false;
                    } else {
                        dataBeans = dataRows;
                    }
                    weakReferenceHandler.sendEmptyMessage(20210623);
                }
            }
        });

        lightViewModel.lightControlModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    //开灯指令发下去之后，虽然返回成功，但仅仅表示app发送指令到后台成功，但是开没开灯无法确定，所以，只能延迟几秒再刷新列表
                    StringHub.show(requireContext(), "指令发送成功");
                    weakReferenceHandler.sendEmptyMessageDelayed(20210624, 3000);
                }
            }
        });
        lightViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(requireContext(), "处理中，请稍后...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }

    private final Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 20210623) {
                if (isRefresh || isLoadMore) {
                    adapter.notifyItemRangeInserted(adapter.getItemCount(), LocaleConstant.PAGE_LIMIT);
                } else {
                    //首次加载数据
                    if (dataBeans.size() == 0) {
                        viewBinding.emptyView.show("没有路灯数据", null);
                    } else {
                        viewBinding.emptyView.hide();
                        adapter = new LightResultAdapter(requireContext(), dataBeans);
                        viewBinding.lightRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
                        viewBinding.lightRecyclerView.setAdapter(adapter);
                        adapter.setOnGridItemClickListener(new LightResultAdapter.OnGridItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                String lampId = dataBeans.get(position).getLampId();
                                if (TextUtils.isEmpty(lampId)) {
                                    StringHub.show(requireContext(), "错误，路灯编号为空");
                                    return;
                                }
                                new LightDetailDialog.Builder()
                                        .setContext(requireContext())
                                        .setLifecycleOwner(requireActivity())
                                        .setStreetLightId(lampId)
                                        .build()
                                        .show();
                            }
                        });
                        adapter.setOnSwitchClickListener(new LightResultAdapter.OnSwitchClickListener() {

                            @Override
                            public void onClick(int position) {
                                LightListBean.DataBean.RowsBean rowsBean = dataBeans.get(position);

                                List<Long> lampIds = new ArrayList<>();
                                lampIds.add(Long.parseLong(rowsBean.getLampId()));

                                String statusName = rowsBean.getStatusName();
                                String controlType;
                                if (statusName.equals("离线")) {
                                    controlType = "1";
                                } else {
                                    controlType = "0";
                                }
                                lightViewModel.controlLight(lampIds, controlType);
                            }
                        });
                    }
                }
            } else if (msg.what == 20210624) {
                isRefresh = true;
                pageIndex = 1;
                lightViewModel.obtainLightList(2 * LocaleConstant.PAGE_LIMIT, pageIndex);
            }
            return true;
        }
    };
}
