package com.tofly.ghrq_route.module.emergencyHandle.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.widget.ListPopupWindow;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lcp.arecyclerview.widget.ARecycleView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.module.emergencyHandle.EmergencyTool;
import com.tofly.ghrq_route.module.emergencyHandle.controller.EmergencyCallBack;
import com.tofly.ghrq_route.module.emergencyHandle.domain.EmergencyHandleData;
import com.tofly.ghrq_route.module.emergencyHandle.domain.MyEmergencyEvent;
import com.tofly.ghrq_route.module.emergencyHandle.ui.adapter.EmergencyAdapter;
import com.tofly.ghrq_route.common.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UiEmergencyQueryList extends BaseUi {
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;
    @BindView(R.id.text_select_state)
    TextView textSelectState;
    @BindView(R.id.text_search_title)
    TextView textSearchTitle;
    @BindView(R.id.search_edit)
    EditText editSearch;
    @BindView(R.id.btn_search_confirm)
    Button btnSearchConfirm;
    @BindArray(R.array.emergency_status)
    String[] arrayStatus;

    private EmergencyAdapter emergencyAdapter;

    private EmergencyTool emergencyTool;

    private String keyword = "";

    private int pageindex = 1;

    private int indexState = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_emergency_query_list);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

        EventBusUtil.register(this);
    }

    private void initView() {

    }

    private void initData() {
        emergencyTool = EmergencyTool.getInstance();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg_recyclerview_divider);
        if (drawable != null)
            dividerItemDecoration.setDrawable(drawable);
        recyclerView.addItemDecoration(dividerItemDecoration);

        List<EmergencyHandleData> emergencyData = new ArrayList<>();
        emergencyAdapter = new EmergencyAdapter(this, emergencyData, -1);
        recyclerView.setAdapter(emergencyAdapter);

        getOnlineTroubleList();
    }

    private void initListener() {
        recyclerView.setOnRefreshListener(() -> {
            pageindex = 1;
            getOnlineTroubleList();
        });

        recyclerView.setOnLoadMoreListener(() -> {
            pageindex++;
            getOnlineTroubleList();
        });

        if (emergencyAdapter != null) {
            emergencyAdapter.setOnItemClickListener((view, position) -> {
                EmergencyHandleData emergencyData = emergencyAdapter.getItem(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(EmergencyHandleData.EMERGENCY_DATA_KEY, emergencyData);
                bundle.putSerializable(EmergencyHandleData.EMERGENCY_POSITION_KEY, position);
                bundle.putInt(EmergencyHandleData.EMERGENCY_LIST_SELECT_TYPE, -1);
                intent.setClass(UiEmergencyQueryList.this, UiEmergencyDetail.class);
                intent.putExtras(bundle);
                startActivity(intent);
            });
        }
    }

    @Subscribe
    public void onMessageEvent(MyEmergencyEvent event) {
        if (MyEmergencyEvent.EMERGENCY_EMERGENCY_HAS_READ.equals(event.message)) {
            if (event.arg0 != null) {
                int position = (int) event.arg0;
                if (emergencyAdapter != null) {
                    emergencyAdapter.notifyItemChanged(position);
                }
            }
        }
    }

    @OnClick({R.id.btn_search_confirm, R.id.text_select_state})
    void onClicked(View view) {
        if (view.getId() == R.id.btn_search_confirm) {
            pageindex = 1;
            String input = editSearch.getText().toString();
            if (!input.isEmpty()) {
                keyword = input;
                getOnlineTroubleList();
            }else {
                keyword = "";
                getOnlineTroubleList();
                toast("地址不能为空");
            }
        }else if (view.getId() == R.id.text_select_state) {
            showStatesSelectPopupWindow();
        }
    }

    private void showStatesSelectPopupWindow(){
        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, arrayStatus));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            boolean bNeedReload = indexState != position;
            indexState = position;
            textSelectState.setText(arrayStatus[indexState]);
            if (bNeedReload) {
                pageindex = 1;
                getOnlineTroubleList();
            }
            listPopupWindow.dismiss();
        });
        listPopupWindow.setAnchorView(textSelectState);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    private void startRefreshing() {
        recyclerView.setRefreshing(true);
    }

    private void stopRefreshing() {
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            recyclerView.setRefreshing(false);
            recyclerView.hideMoreProgress();
        }, 500);
    }

    private void getOnlineTroubleList() {
        startRefreshing();
        emergencyTool.getEmergencyListOnline(this, -1, indexState, keyword, pageindex, new EmergencyCallBack() {
            @Override
            public void onGetDatas(boolean isSuccess, int errorCode, String errMsg, List dataList, int total) {
                super.onGetDatas(isSuccess, errorCode, errMsg, dataList, total);
                stopRefreshing();
                if (pageindex == 1) {
                    recyclerView.setTotal(total);
                    emergencyAdapter.clear();
                }
                if (dataList != null) {
                    emergencyAdapter.addAll(dataList);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
