package com.casic.dcms.view;

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

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityWellListBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.WellListBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.vm.WellViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.pengxh.androidx.lite.adapter.NormalRecyclerAdapter;
import com.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.pengxh.androidx.lite.vm.LoadState;
import com.pengxh.androidx.lite.widget.dialog.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.util.ArrayList;
import java.util.List;

public class WellListActivity extends AndroidxBaseActivity<ActivityWellListBinding> {

    private final Context context = this;
    private WeakReferenceHandler weakReferenceHandler;
    private NormalRecyclerAdapter<WellListBean.DataBean.RowsBean> adapter;
    private WellViewModel wellViewModel;
    private List<WellListBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private int pageIndex = 1;
    private boolean isRefresh, isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

        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, LocaleConstant.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
    protected void observeRequestState() {

    }

    @Override
    public void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        wellViewModel = new ViewModelProvider(this).get(WellViewModel.class);
    }

    @Override
    protected void onResume() {
        obtainWellList();
        super.onResume();
    }

    private void obtainWellList() {
        wellViewModel.obtainWellList(pageIndex);
    }

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

        wellViewModel.listModel.observe(this, new Observer<WellListBean>() {
            @Override
            public void onChanged(WellListBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<WellListBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
                    if (isRefresh) {
                        adapter.setRefreshData(dataRows);
                        viewBinding.refreshLayout.finishRefresh();
                        isRefresh = false;
                    } else if (isLoadMore) {
                        if (dataRows.size() == 0) {
                            StringHub.show(context, "到底了，别拉了");
                        }
                        adapter.setLoadMoreData(dataRows);
                        viewBinding.refreshLayout.finishLoadMore();
                        isLoadMore = false;
                    } else {
                        dataBeans = dataRows;
                        weakReferenceHandler.sendEmptyMessage(20210628);
                    }
                }
            }
        });

        wellViewModel.operationActionModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.isSuccess()) {
                    StringHub.show(context, "操作成功");
                    //取消成功之后自动刷新列表
                    isRefresh = true;
                    pageIndex = 1;
                    obtainWellList();
                } else {
                    StringHub.show(context, "操作失败，请重试");
                }
            }
        });
        wellViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "处理中，请稍后...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }

    private final Handler.Callback callback = msg -> {
        if (msg.what == 20210628) {
            if (dataBeans.size() == 0) {
                viewBinding.emptyView.show("抱歉，无法为您查到窨井数据", null);
            } else {
                viewBinding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<WellListBean.DataBean.RowsBean>(R.layout.item_well_rv_l, dataBeans) {
                    @Override
                    public void convertView(ViewHolder viewHolder, int position, WellListBean.DataBean.RowsBean item) {
                        viewHolder.setText(R.id.wellTypeView, item.getWellTypeName())
                                .setText(R.id.wellNameView, item.getWellName())
                                .setText(R.id.wellCodeView, item.getWellCode())
                                .setText(R.id.wellPositionView, item.getPosition())
                                .setText(R.id.wellStatusView, "已" + item.getBfztName());

                        String bfzt = item.getBfzt();
                        if (bfzt.equals("0")) {
                            viewHolder.setText(R.id.wellOptionButton, "布防")
                                    .setBackgroundColor(R.id.wellOptionButton, IntHub.convertColor(context, R.color.onLineColor));
                        } else {
                            viewHolder.setText(R.id.wellOptionButton, "撤防")
                                    .setBackgroundColor(R.id.wellOptionButton, IntHub.convertColor(context, R.color.qmui_config_color_red));
                        }

                        viewHolder.setOnClickListener(R.id.wellNameView, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                StringHub.show(context, "井深" + item.getDeep() + "m");
                            }
                        });

                        viewHolder.setOnClickListener(R.id.wellOptionButton, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String bfzt = item.getBfzt();
                                String bfztName;
                                if (bfzt.equals("0")) {
                                    bfztName = "布防";
                                    bfzt = "1";
                                } else if (bfzt.equals("1")) {
                                    bfztName = "撤防";
                                    bfzt = "0";
                                } else {
                                    StringHub.show(context, "窨井状态错误，无法进行撤防或者布防");
                                    return;
                                }
                                showSingleOptionDialog(bfztName, dataBeans.get(position).getId(), bfzt);
                            }
                        });
                    }
                };
                viewBinding.wellRecyclerView.setAdapter(adapter);
                adapter.setOnItemClickedListener(new NormalRecyclerAdapter.OnItemClickedListener<WellListBean.DataBean.RowsBean>() {
                    @Override
                    public void onItemClicked(int position, WellListBean.DataBean.RowsBean rowsBean) {
                        String lng = rowsBean.getCoordinateX();
                        String lat = rowsBean.getCoordinateY();
                        MapHelper.displayOnMap(context, "others", lng, lat);
                    }
                });
            }
        }
        return true;
    };

    //单个撤防/布防
    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() {
                        wellViewModel.operateSingleWell(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() {
                        wellViewModel.operateBatchWell(bfzt);
                    }

                    @Override
                    public void onCancelClick() {

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