package com.casic.dcms.ui.fragment;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.casic.dcms.adapter.LightResultAdapter;
import com.casic.dcms.base.AndroidxBaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.LightListBean;
import com.casic.dcms.databinding.FragmentLightListBinding;
import com.casic.dcms.mvp.presenter.impl.LightControlPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.LightListPresenterImpl;
import com.casic.dcms.mvp.view.ILightControlView;
import com.casic.dcms.mvp.view.ILightListView;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.LightDetailDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class LightOnListFragment extends AndroidxBaseFragment<FragmentLightListBinding> implements ILightListView, ILightControlView {

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

    @Override
    protected void setupTopBarLayout() {
        context = getContext();
    }

    @Override
    protected void initData() {
        lightListPresenter = new LightListPresenterImpl(this);
        lightListPresenter.onReadyRetrofitRequest(2 * Constant.PAGE_LIMIT, pageIndex);

        weakReferenceHandler = new WeakReferenceHandler(this);

        controlPresenter = new LightControlPresenterImpl(this);
    }

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

    @Override
    public void obtainLightResult(LightListBean resultBean) {
        if (resultBean.isSuccess()) {
            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) {
                    ToastHelper.showToast("到底了，别拉了", ToastHelper.INFO);
                }
                dataBeans.addAll(dataRows);
                viewBinding.refreshLayout.finishLoadMore();
                isLoadMore = false;
            } else {
                dataBeans = dataRows;
            }
            weakReferenceHandler.sendEmptyMessage(20210623);
        }
    }

    private static class WeakReferenceHandler extends Handler {
        private final WeakReference<LightOnListFragment> reference;

        private WeakReferenceHandler(LightOnListFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

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

                            @Override
                            public void onClick(int position) {
                                LightListBean.DataBean.RowsBean rowsBean = fragment.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";
                                }
                                fragment.controlPresenter.onReadyRetrofitRequest(lampIds, controlType);
                            }
                        });
                    }
                }
            } else if (msg.what == 20210624) {
                fragment.isRefresh = true;
                fragment.pageIndex = 1;
                fragment.lightListPresenter.onReadyRetrofitRequest(2 * Constant.PAGE_LIMIT, fragment.pageIndex);
            }
        }
    }

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(context, "处理中，请稍后...");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @Override
    public void obtainControlResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            //开灯指令发下去之后，虽然返回成功，但仅仅表示app发送指令到后台成功，但是开没开灯无法确定，所以，只能延迟几秒再刷新列表
            ToastHelper.showToast("指令发送成功", ToastHelper.SUCCESS);
            weakReferenceHandler.sendEmptyMessageDelayed(20210624, 3000);
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    public void onDestroyView() {
        if (lightListPresenter != null) {
            lightListPresenter.disposeRetrofitRequest();
        }
        if (controlPresenter != null) {
            controlPresenter.disposeRetrofitRequest();
        }
        super.onDestroyView();
    }
}
