package com.casic.dcms.view;

import android.content.Context;
import android.content.Intent;
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.ActivityPipeBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.AlarmDataBean;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.view.map.WarningOnMapActivity;
import com.casic.dcms.vm.AlarmViewModel;
import com.casic.dcms.widgets.CancelAlarmDialog;
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.SaveKeyValues;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.pengxh.androidx.lite.vm.LoadState;
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 WeakReferenceHandler weakReferenceHandler;
    private AlarmViewModel alarmViewModel;
    private NormalRecyclerAdapter<AlarmDataBean.DataBean.RowsBean> adapter;
    private List<AlarmDataBean.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(v -> {
            int popupWidth = QMUIDisplayHelper.dp2px(context, 100);
            ArrayAdapter<String> popupListAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, LocaleConstant.POPUP_LIST_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:
                                    showBatchCancelDialog();
                                    break;
                                case 1:
                                    startActivity(new Intent(context, WarningOnMapActivity.class));
                                    break;
                                case 2:
                                    startActivity(new Intent(context, WellListActivity.class));
                                    break;
                            }
                        }
                    }).animStyle(QMUIPopup.ANIM_AUTO)
                    .shadowElevation(10, 1)
                    .radius(10)
                    .show(viewBinding.titleBarLayout.rightImageView);
        });
    }

    @Override
    protected void observeRequestState() {
        alarmViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {

            }
        });
    }

    @Override
    public void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        alarmViewModel = new ViewModelProvider(this).get(AlarmViewModel.class);
        alarmViewModel.resultModel.observe(this, new Observer<AlarmDataBean>() {
            @Override
            public void onChanged(AlarmDataBean alarmDataBean) {
                if (alarmDataBean.getCode() == 200) {
                    SaveKeyValues.putValue("alarmTotal", alarmDataBean.getData().getTotal());
                    List<AlarmDataBean.DataBean.RowsBean> dataRows = alarmDataBean.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(20210626);
                    }
                }
            }
        });

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

    @Override
    protected void onResume() {
        super.onResume();
        pageIndex = 1;
        obtainAlarmList();
    }

    private void obtainAlarmList() {
        alarmViewModel.obtainAlarmList(LocaleConstant.PAGE_LIMIT, pageIndex);
    }

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

    private final Handler.Callback callback = msg -> {
        if (msg.what == 20210626) {
            if (dataBeans.size() == 0) {
                viewBinding.emptyView.show(false, "设备状态很好，没有任何报警", null, "刷新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pageIndex = 1;
                        obtainAlarmList();
                    }
                });
            } else {
                viewBinding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<AlarmDataBean.DataBean.RowsBean>(R.layout.item_alarm_recycleview, dataBeans) {
                    @Override
                    public void convertView(ViewHolder viewHolder, int position, AlarmDataBean.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());
                                    }
                                });
                    }
                };
                viewBinding.warningRecyclerView.setAdapter(adapter);
            }
        }
        return true;
    };

    //单个消警
    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(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(status, editReason);
            }

            @Override
            public void onCancelClick() {

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