package com.casic.dcms.ui;

import android.content.Context;
import android.content.Intent;
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.AlarmListAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.AlarmDataBean;
import com.casic.dcms.databinding.ActivityPipeBinding;
import com.casic.dcms.mvp.presenter.impl.AlarmListPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CancelAlarmPresenterImpl;
import com.casic.dcms.mvp.view.IAlarmListView;
import com.casic.dcms.mvp.view.ICancelAlarmView;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.CancelAlarmDialog;
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 PipelineManagerActivity extends AndroidxBaseActivity<ActivityPipeBinding> implements IAlarmListView, ICancelAlarmView {

    private static final String TAG = "PipelineManagerActivity";
    private final Context context = this;
    private AlarmListPresenterImpl alarmListPresenter;
    private List<AlarmDataBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private boolean isRefresh, isLoadMore = false;
    private WeakReferenceHandler weakReferenceHandler;
    private AlarmListAdapter adapter;
    private int pageIndex = 1;
    private CancelAlarmPresenterImpl cancelAlarmPresenter;

    @Override
    protected void setupTopBarLayout() {
        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, Constant.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
    public void initData() {
        alarmListPresenter = new AlarmListPresenterImpl(this);
        alarmListPresenter.onReadyRetrofitRequest(Constant.PAGE_LIMIT, pageIndex);

        weakReferenceHandler = new WeakReferenceHandler(this);

        cancelAlarmPresenter = new CancelAlarmPresenterImpl(this);
    }

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

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

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

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            PipelineManagerActivity resultActivity = reference.get();
            if (msg.what == 20210626) {
                if (resultActivity.isRefresh || resultActivity.isLoadMore) {
                    resultActivity.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (resultActivity.dataBeans.size() == 0) {
                        resultActivity.viewBinding.emptyView.show("设备状态很好，没有任何报警", null);
                    } else {
                        resultActivity.viewBinding.emptyView.hide();
                        resultActivity.adapter = new AlarmListAdapter(resultActivity, resultActivity.dataBeans);
                        resultActivity.viewBinding.warningRecyclerView.setLayoutManager(new LinearLayoutManager(resultActivity));
                        resultActivity.viewBinding.warningRecyclerView.addItemDecoration(new DividerItemDecoration(resultActivity, DividerItemDecoration.VERTICAL));
                        resultActivity.viewBinding.warningRecyclerView.setAdapter(resultActivity.adapter);
                        resultActivity.adapter.setOnCancelClickListener(new AlarmListAdapter.OnCancelClickListener() {
                            @Override
                            public void onClick(int position) {
                                resultActivity.showSingleCancelDialog(resultActivity.dataBeans.get(position).getJobId());
                            }
                        });
                    }
                }
            }
        }
    }

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

            @Override
            public void onCancelClick() {

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

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

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

    @Override
    public void obtainAlarmResult(AlarmDataBean resultBean) {
        if (resultBean.isSuccess()) {
            SaveKeyValues.putValue("alarmTotal", resultBean.getData().getTotal());
            List<AlarmDataBean.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(20210626);
        }
    }

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

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

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