package com.tofly.ghrq_route.common.ui.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;

import com.esri.arcgisruntime.data.Feature;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;

public class FloatDeviceSearchBar extends LinearLayout{
    @BindView(R.id.float_search_edit)
    EditText editFloatSearch;
    @BindView(R.id.float_search_sp)
    AppCompatSpinner spinnerSearchMode;
    @BindView(R.id.lv_float_search_result)
    ListView lvSearchResult;
    @BindView(R.id.no_search_result)
    TextView textNoResult;
    @BindView(R.id.btn_search_confirm)
    Button btnSearchConfirm;
    @BindView(R.id.float_search_clear)
    ImageView imageSearchClear;

    private Context mContext;
    // 搜索栏的查询模式 地址查询 - 经纬度查询
    private TextWatcher searchEditWatcher;
    private onSearchListener mOnSearchListener;

    private int layerIds[] = {3, 5};

    private int mLayerIndex = 0;

    public interface onSearchListener {
        void onSearchClosed();
        void onSearchSelected(Feature feature, String deviceName);
/*        void onSearchNavi(double lng, double lat);
        void onCoordinateSearch(double lng, double lat);*/
        void onSearchDevice(int layerid, String device_code);
    }

    public void setOnSearchListener(onSearchListener listener) {
        mOnSearchListener = listener;
    }

    public void clearInputFocus() {
        editFloatSearch.clearFocus();
    }

    public FloatDeviceSearchBar(Context context) {
        this(context, null);
    }

    public FloatDeviceSearchBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloatDeviceSearchBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        initView();
        initListener();
    }

    private void initView() {
        inflate(mContext, R.layout.layout_float_search_device, this);
        ButterKnife.bind(this);

        clearInputFocus();
        initSearchSpinner();
    }

    private void initSearchSpinner() {
        String[] searchText = getResources().getStringArray(R.array.device_search_mode_texts);
        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(
                mContext, R.layout.my_spinner_text_center_item, searchText);
        stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSearchMode.setAdapter(stringArrayAdapter);
        spinnerSearchMode.setDropDownVerticalOffset(BaseApp.dip2px(36));
    }

    private void initListener() {
        //搜索框监听
        searchEditWatcher = new MainTextWatcher();
        editFloatSearch.addTextChangedListener(searchEditWatcher);
        setFocusableInTouchMode(true);
/*        setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                Activity activity = (Activity) mContext;
                activity.onBackPressed();
                return true;
            }
            return false;
        });*/
    }

    public void removeTextWatcher() {
        editFloatSearch.removeTextChangedListener(searchEditWatcher);
    }

    public void onSearchClosed() {
        editFloatSearch.setText("");
        if (mOnSearchListener != null) {
            mOnSearchListener.onSearchClosed();
        }
    }

    @OnClick({ R.id.float_search_clear, R.id.btn_search_confirm})
    void onClicked(View view) {
        if (view.getId() == R.id.float_search_clear) {
            onSearchClosed();
        }else if (view.getId() == R.id.btn_search_confirm) {
            String input = editFloatSearch.getText().toString();
            if (!input.isEmpty()) {
                searchCoordinate(input);
            }else {
                ToastUtil.showToast(mContext, mContext.getString(R.string.map_search_hint_device));
            }
        }
    }

    @OnItemSelected({R.id.float_search_sp})
    void onItemSelected(AdapterView<?> parent, int position) {
        if (parent.getId() == R.id.float_search_sp) {
            mLayerIndex = position;
        }
    }

    /*首页地址搜索模块*/
    boolean ignoredInput = false;
    private class MainTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (ignoredInput) {
                return;
            }

            String strInput = s.toString();
            if (!TextUtils.isEmpty(strInput)) {
                imageSearchClear.setVisibility(View.VISIBLE);
                btnSearchConfirm.setVisibility(VISIBLE);
                spinnerSearchMode.setVisibility(View.GONE);
            } else {
                imageSearchClear.setVisibility(View.GONE);
                btnSearchConfirm.setVisibility(GONE);
                spinnerSearchMode.setVisibility(View.VISIBLE);
                textNoResult.setVisibility(View.GONE);
                lvSearchResult.setVisibility(View.GONE);
            }
        }
    }

    private void searchCoordinate(String strInput) {
        int layerId = layerIds[mLayerIndex];
        if (mOnSearchListener != null) {
            mOnSearchListener.onSearchDevice(layerId, strInput);
        }
    }

    //在显示在界面上
    public void showSearchResult(List<Feature> features) {
        if (features == null || features.isEmpty()) {
            textNoResult.setVisibility(View.VISIBLE);
            lvSearchResult.setVisibility(View.GONE);
            lvSearchResult.setAdapter(null);
        } else {
            if (!editFloatSearch.getText().toString().isEmpty()) {
                textNoResult.setVisibility(View.GONE);
                lvSearchResult.setVisibility(View.VISIBLE);
            }
            List<String> strDevices = new ArrayList<>();
            for (Feature feature: features) {
                String device = "设备: ";
                Map<String, Object> attrs = feature.getAttributes();
                if (attrs != null && !attrs.isEmpty()) {
                    Object object = attrs.get("CODE");
                    if (object != null) {
                        device += object.toString();
                    }
                }
                strDevices.add(device);
            }
            lvSearchResult.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_expandable_list_item_1, strDevices));
            lvSearchResult.setOnItemClickListener((parent, view, position, id) -> {
                Feature feature = features.get(position);
                String device = strDevices.get(position);
                lvSearchResult.setVisibility(View.GONE);
                ignoredInput = true;
                ignoredInput = false;
                if (feature != null) {
                    if (mOnSearchListener != null) {
                        mOnSearchListener.onSearchSelected(feature, device);
                    }
                }
                //editFloatSearch.addTextChangedListener(searchEditWatcher);
            });
        }
    }
}
