package com.casic.dcms.view.pipeline;

import android.content.Context;
import android.content.Intent;
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.ActivityPipeBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.WellAlarmListBean;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.AlarmViewModel;
import com.casic.dcms.widgets.CancelAlarmDialog;
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.ContextKit;
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.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 PipelineManagerActivity extends AndroidxBaseActivity<ActivityPipeBinding> {

    private static final String TAG = "PipelineManagerActivity";
    private final Context context = this;
    private AlarmViewModel alarmViewModel;
    private NormalRecyclerAdapter<WellAlarmListBean.DataBean.RowsBean> adapter;
    private List<WellAlarmListBean.DataBean.RowsBean> dataRows = new ArrayList<>();
    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_LIST_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:
                                        showBatchCancelDialog();
                                        break;
                                    case 1:
                                        if (dataRows.isEmpty()) {
                                            StringKit.show(context, "无报警数据");
                                            return;
                                        }
                                        Intent intent = new Intent(context, AlarmOnMapActivity.class);
                                        intent.putParcelableArrayListExtra("rows_list", new ArrayList<>(dataRows));
                                        context.startActivity(intent);
                                        break;
                                    case 2:
                                        ContextKit.navigatePageTo(context, WellListActivity.class);
                                        break;
                                }
                            }
                        })
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .shadowElevation(10, 1)
                        .radius(10)
                        .show(binding.anchorView);
            }
        });
    }

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

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        alarmViewModel = new ViewModelProvider(this).get(AlarmViewModel.class);
        alarmViewModel.wellAlarmListResult.observe(this, new Observer<WellAlarmListBean>() {
            @Override
            public void onChanged(WellAlarmListBean resultBean) {
                if (resultBean.getCode() == 200) {
                    bindRecyclerView(resultBean);
                }
            }
        });
        getAlarmList();

        alarmViewModel.cancelActionModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean actionResultBean) {
                if (actionResultBean.getCode() == 200) {
                    StringKit.show(context, "取消报警成功");
                    //取消成功之后自动刷新列表
                    isRefresh = true;
                    page = 1;
                    getAlarmList();
                } else {
                    StringKit.show(context, "操作失败，请重试");
                }
            }
        });
    }

    private void bindRecyclerView(WellAlarmListBean alarmDataBean) {
        dataRows = alarmDataBean.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<WellAlarmListBean.DataBean.RowsBean>(R.layout.item_alarm_list_rv_l, dataRows) {
                    @Override
                    public void convertView(ViewHolder viewHolder, int position, WellAlarmListBean.DataBean.RowsBean item) {
                        viewHolder.setText(R.id.alarmMessageView, item.getAlarmMessage())
                                .setText(R.id.wellCodeView, item.getWellCode())
                                .setText(R.id.alarmPositionView, item.getPosition())
                                .setText(R.id.alarmTimeView, item.getAlarmTime())
                                .setOnClickListener(R.id.cancelAlarmButton, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        showSingleCancelDialog(item.getJobId());
                                    }
                                });
                    }
                };
                binding.warningRecyclerView.addItemDecoration(new RecyclerViewItemDivider(1, Color.LTGRAY));
                binding.warningRecyclerView.setAdapter(adapter);
            }
        }
    }

    private void getAlarmList() {
        alarmViewModel.getAlarmList(this, page);
    }

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

    //单个消警
    private void showSingleCancelDialog(String jobId) {
        //已处理status = 3，无需处理status = 4
        new CancelAlarmDialog.Builder().setContext(this).setOnDialogButtonClickListener(new CancelAlarmDialog.OnDialogButtonClickListener() {
            @Override
            public void onConfirmClick(String status, String editReason) {
                alarmViewModel.cancelSingleAlarm(context, jobId, status, editReason);
            }

            @Override
            public void onCancelClick() {

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

    //一键消警
    private void showBatchCancelDialog() {
        //已处理status = 3，无需处理status = 4
        new CancelAlarmDialog.Builder().setContext(this).setOnDialogButtonClickListener(new CancelAlarmDialog.OnDialogButtonClickListener() {
            @Override
            public void onConfirmClick(String status, String editReason) {
                alarmViewModel.cancelBatchAlarm(context, status, editReason);
            }

            @Override
            public void onCancelClick() {

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