package com.casic.dcms.view.pipeline;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

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.ActivityWellListBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.WellListBean;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.WellViewModel;
import com.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.divider.RecyclerViewItemDivider;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.TitleBarView;
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.List;

public class WellListActivity extends AndroidxBaseActivity<ActivityWellListBinding> {

    private final Context context = this;
    private NormalRecyclerAdapter<WellListBean.DataBean.RowsBean> adapter;
    private WellViewModel wellViewModel;
    private int page = 1;
    private boolean isRefresh, isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);
        binding.titleView.setOnClickListener(new TitleBarView.OnClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
                int popupWidth = QMUIDisplayHelper.dp2px(context, 100);
                ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, LocaleConstant.POPUP_OPTION_ITEMS);
                QMUIPopups.listPopup(context, popupWidth, popupWidth * 2, adapter, 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(binding.anchorView);
            }
        });
    }

    @Override
    protected void observeRequestState() {
        wellViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (!isRefresh && !isLoadMore) {
                    if (loadState == LoadState.Loading) {
                        LoadingDialog.show(WellListActivity.this, "数据加载中，请稍后");
                    } else {
                        LoadingDialog.dismiss();
                    }
                }
            }
        });
    }

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        wellViewModel = new ViewModelProvider(this).get(WellViewModel.class);
        wellViewModel.listModel.observe(this, new Observer<WellListBean>() {
            @Override
            public void onChanged(WellListBean resultBean) {
                if (resultBean.getCode() == 200) {
                    bindRecyclerView(resultBean);
                }
            }
        });
        getWellList();

        wellViewModel.operationActionModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.isSuccess()) {
                    StringKit.show(context, "操作成功");
                    //取消成功之后自动刷新列表
                    isRefresh = true;
                    page = 1;
                    getWellList();
                } else {
                    StringKit.show(context, "操作失败，请重试");
                }
            }
        });
    }

    private void bindRecyclerView(WellListBean resultBean) {
        List<WellListBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
        if (isRefresh) {
            binding.refreshLayout.finishRefresh();
            isRefresh = false;
            adapter.refresh(dataRows);
        } else if (isLoadMore) {
            binding.refreshLayout.finishLoadMore();
            isLoadMore = false;
            if (dataRows.size() == 0) {
                StringKit.show(context, "到底了，别拉了");
            }
            adapter.loadMore(dataRows);
        } else {
            if (dataRows.size() == 0) {
                binding.emptyView.show("抱歉，无法为您查到窨井数据", null);
            } else {
                binding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<WellListBean.DataBean.RowsBean>(R.layout.item_well_rv_l, dataRows) {
                    @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, IntKit.convertColor(context, R.color.onLineColor));
                        } else {
                            viewHolder.setText(R.id.wellOptionButton, "撤防")
                                    .setBackgroundColor(R.id.wellOptionButton, IntKit.convertColor(context, R.color.qmui_config_color_red));
                        }

                        viewHolder.setOnClickListener(R.id.wellNameView, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (item.getDeep().isEmpty()) {
                                    StringKit.show(context, "该位置井深未知");
                                    return;
                                }
                                StringKit.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 {
                                    StringKit.show(context, "窨井状态错误，无法进行撤防或者布防");
                                    return;
                                }
                                showSingleOptionDialog(bfztName, dataRows.get(position).getId(), bfzt);
                            }
                        });
                    }
                };
                binding.wellRecyclerView.addItemDecoration(new RecyclerViewItemDivider(1, Color.LTGRAY));
                binding.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);
                    }
                });
            }
        }
    }

    private void getWellList() {
        wellViewModel.getWellList(this, page);
    }

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

    //单个撤防/布防
    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(context, 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(context, bfzt);
                    }

                    @Override
                    public void onCancelClick() {

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