package com.casic.dcms.ui;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.casic.dcms.adapter.WellListAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.WellListBean;
import com.casic.dcms.databinding.ActivityWellListBinding;
import com.casic.dcms.mvp.presenter.impl.OptionWellPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.WellListPresenterImpl;
import com.casic.dcms.mvp.view.IOptionWellView;
import com.casic.dcms.mvp.view.IWellListView;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.AlertControlDialog;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
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 WellListActivity extends AndroidxBaseActivity<ActivityWellListBinding> implements IWellListView, IOptionWellView {

    private final Context context = this;
    private WellListPresenterImpl wellListPresenter;
    private List<WellListBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private WeakReferenceHandler weakReferenceHandler;
    private WellListAdapter adapter;
    private int pageIndex = 1;
    private OptionWellPresenterImpl optionWellPresenter;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
        viewBinding.titleBarLayout.titleView.setText("窨井列表");
        viewBinding.titleBarLayout.rightImageView.setOnClickListener(view -> {
            int popupWidth = QMUIDisplayHelper.dp2px(context, 100);
            ArrayAdapter<String> popupListAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, Constant.POPUP_OPTION_ITEMS);
            QMUIPopups.listPopup(context, popupWidth, popupWidth * 2, popupListAdapter, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            showBatchOptionDialog("布防", "1");
                            break;
                        case 1:
                            showBatchOptionDialog("撤防", "0");
                            break;
                    }
                }
            }).animStyle(QMUIPopup.ANIM_AUTO)
                    .shadowElevation(10, 1)
                    .radius(10)
                    .show(viewBinding.titleBarLayout.rightImageView);
        });
    }

    @Override
    public void initData() {
        wellListPresenter = new WellListPresenterImpl(this);
        wellListPresenter.onReadyRetrofitRequest(pageIndex);

        weakReferenceHandler = new WeakReferenceHandler(this);

        optionWellPresenter = new OptionWellPresenterImpl(this);
    }

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

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

        private WeakReferenceHandler(WellListActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            WellListActivity activity = reference.get();
            if (msg.what == 20210628) {
                if (activity.isRefresh || activity.isLoadMore) {
                    activity.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (activity.dataBeans.size() == 0) {
                        activity.viewBinding.emptyView.show("抱歉，无法为您查到窨井数据", null);
                    } else {
                        activity.viewBinding.emptyView.hide();
                        activity.adapter = new WellListAdapter(activity, activity.dataBeans);
                        activity.viewBinding.wellRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
                        activity.viewBinding.wellRecyclerView.addItemDecoration(new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL));
                        activity.viewBinding.wellRecyclerView.setAdapter(activity.adapter);
                        activity.adapter.setOnItemClickListener(new WellListAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                WellListBean.DataBean.RowsBean rowsBean = activity.dataBeans.get(position);
                                String lng = rowsBean.getCoordinateX();
                                String lat = rowsBean.getCoordinateY();
                                OtherUtils.displayOnMap(activity, "others", lng, lat);
                            }
                        });
                        activity.adapter.setOnOptionClickListener(new WellListAdapter.OnOptionClickListener() {
                            @Override
                            public void onClick(int position) {
                                String bfzt = activity.dataBeans.get(position).getBfzt();
                                String bfztName;
                                if (bfzt.equals("0")) {
                                    bfztName = "布防";
                                    bfzt = "1";
                                } else if (bfzt.equals("1")) {
                                    bfztName = "撤防";
                                    bfzt = "0";
                                } else {
                                    ToastHelper.showToast("窨井状态错误，无法进行撤防或者布防", ToastHelper.ERROR);
                                    return;
                                }
                                activity.showSingleOptionDialog(bfztName, activity.dataBeans.get(position).getId(), bfzt);
                            }
                        });
                    }
                }
            }
        }
    }

    //单个撤防/布防
    private void showSingleOptionDialog(String bfztName, String id, String bfzt) {
        new AlertControlDialog.Builder()
                .setContext(this)
                .setTitle("确认操作")
                .setMessage("确定要对该井进行" + bfztName + "吗？")
                .setNegativeButton("取消")
                .setPositiveButton("确定")
                .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                    @Override
                    public void onConfirmClick() {
                        optionWellPresenter.onReadyRetrofitRequest(id, bfzt);
                    }

                    @Override
                    public void onCancelClick() {

                    }
                }).build().show();
    }

    //一键撤防/布防
    private void showBatchOptionDialog(String bfztName, String bfzt) {
        new AlertControlDialog.Builder()
                .setContext(this)
                .setTitle("确认操作")
                .setMessage("确定对全部井进行" + bfztName + "吗？")
                .setNegativeButton("取消")
                .setPositiveButton("确定")
                .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                    @Override
                    public void onConfirmClick() {
                        optionWellPresenter.onReadyRetrofitRequest(bfzt);
                    }

                    @Override
                    public void onCancelClick() {

                    }
                }).build().show();
    }

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

    @Override
    public void obtainOptionResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("操作成功", ToastHelper.SUCCESS);
            //取消成功之后自动刷新列表
            isRefresh = true;
            pageIndex = 1;
            wellListPresenter.onReadyRetrofitRequest(pageIndex);
        } else {
            ToastHelper.showToast("操作失败，请重试", ToastHelper.ERROR);
        }
    }

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

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

    @Override
    public void obtainDeviceResult(WellListBean resultBean) {
        if (resultBean.isSuccess()) {
            List<WellListBean.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(20210628);
        }
    }

    @Override
    protected void onDestroy() {
        if (wellListPresenter != null) {
            wellListPresenter.disposeRetrofitRequest();
        }
        if (optionWellPresenter != null) {
            optionWellPresenter.disposeRetrofitRequest();
        }
        super.onDestroy();
    }
}
