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.ProgressBar;
import android.widget.TextView;

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

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
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 butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;

public class FloatAddressSearchBar extends LinearLayout implements Inputtips.InputtipsListener{
    @BindView(R.id.float_search_edit)
    EditText editFloatSearch;
    @BindView(R.id.float_search_sp)
    AppCompatSpinner spinnerSearchMode;
    @BindView(R.id.float_search_progress)
    ProgressBar searchProgress;
    @BindView(R.id.lv_float_search_result)
    ListView lvSearchResult;
    @BindView(R.id.no_search_result)
    TextView textNoResult;
    @BindView(R.id.float_search_nav)
    ImageView imageSearchNavi;
    @BindView(R.id.btn_search_confirm)
    Button btnSearchConfirm;
    @BindView(R.id.float_search_clear)
    ImageView imageSearchClear;

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

    private enum SearchMode {
        addressMode, coordinateMode
    }

    public interface onSearchListener {
        void onSearchClosed();
        void onSearchSelected(double lng, double lat, String addr);
        void onSearchNavi(double lng, double lat);
        void onCoordinateSearch(double lng, double lat);
    }

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

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

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

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

    public FloatAddressSearchBar(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_address, this);
        ButterKnife.bind(this);

        clearInputFocus();
        initSearchSpinner();
    }

    private void initSearchSpinner() {
        mSearchMode = SearchMode.addressMode;
        String[] searchText = getResources().getStringArray(R.array.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("");
        selectedTip = null;
        if (mOnSearchListener != null) {
            mOnSearchListener.onSearchClosed();
        }
    }

    @OnClick({ R.id.float_search_clear, R.id.float_search_nav, R.id.btn_search_confirm})
    void onClicked(View view) {
        if (view.getId() == R.id.float_search_clear) {
           onSearchClosed();
        }
        else if (view.getId() == R.id.float_search_nav) {
            if (mOnSearchListener != null) {
                if (selectedTip != null) {
                    LatLonPoint point = selectedTip.getPoint();
                    mOnSearchListener.onSearchNavi(point.getLongitude(), point.getLatitude());
                }
            }
        } 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.maptool_search_hint_coord));
            }
        }
    }

    @OnItemSelected({R.id.float_search_sp})
    void onItemSelected(AdapterView<?> parent, int position) {
        if (parent.getId() == R.id.float_search_sp) {
            switch (position) {
                case 0:
                    mSearchMode = SearchMode.addressMode;
                    editFloatSearch.setHint(R.string.maptool_search_hint);
                    break;
                case 1:
                    mSearchMode = SearchMode.coordinateMode;
                    editFloatSearch.setHint(R.string.maptool_search_hint_coord);
                    break;
            }
        }
    }

    /*首页地址搜索模块*/
    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;
            }

            imageSearchNavi.setVisibility(GONE);
            String strInput = s.toString();
            if (!TextUtils.isEmpty(strInput)) {
                imageSearchClear.setVisibility(View.VISIBLE);
                spinnerSearchMode.setVisibility(View.GONE);
                if (SearchMode.addressMode == mSearchMode) {
                    if (strInput.length() > 1) {
                        searchPoiPlace(strInput);
                    }
                } else if (SearchMode.coordinateMode == mSearchMode) {
                    btnSearchConfirm.setVisibility(VISIBLE);
                }
            } else {
                searchProgress.setVisibility(View.GONE);
                imageSearchClear.setVisibility(View.GONE);
                spinnerSearchMode.setVisibility(View.VISIBLE);
                textNoResult.setVisibility(View.GONE);
                lvSearchResult.setVisibility(View.GONE);
                btnSearchConfirm.setVisibility(GONE);
            }
        }
    }

    private void searchPoiPlace(String keyWord) {
        searchProgress.setVisibility(View.VISIBLE);

        InputtipsQuery inputtipsQuery = new InputtipsQuery(keyWord, mContext.getString(R.string.city_code_guanghan));
        inputtipsQuery.setCityLimit(true);//限制在当前城市
        Inputtips inputTips = new Inputtips(mContext, inputtipsQuery);
        inputTips.setInputtipsListener(this);
        inputTips.requestInputtipsAsyn();
    }

    private void searchCoordinate(String strInput) {
        try {
            String[] split = TextUtils.split(strInput, ",");
            if (split.length == 2) {
                String lngString = split[0];
                String latString = split[1];
                double lng = Double.parseDouble(lngString);
                double lat = Double.parseDouble(latString);
                if (mOnSearchListener != null) {
                    mOnSearchListener.onCoordinateSearch(lng, lat);
                }
            } else {
                ToastUtil.showToast(mContext, mContext.getString(R.string.maptool_search_hint_coord));
            }
        } catch (Exception e) {
            ToastUtil.showToast(mContext, mContext.getString(R.string.maptool_search_hint_coord));
        }
    }

    @Override
    public void onGetInputtips(final List<Tip> list, int i) {
        searchProgress.setVisibility(GONE);
        if (i == 1000) {
            if (list != null && !list.isEmpty()) {
                final List<Tip> filterTips = filterNoLatLonTip(list);
                showSearchResult(filterTips);
                return;
            }
        }
        ToastUtil.showToast(mContext,"查询地址失败！");
    }

    private List<Tip> filterNoLatLonTip(List<Tip> tips) {
        List<Tip> filtedTips = new ArrayList<>();
        for (Tip tip: tips) {
            LatLonPoint latLonPoint = tip.getPoint();
            if (latLonPoint != null) {
                filtedTips.add(tip);
            }
        }
        return filtedTips;
    }

    //在显示在界面上
    private void showSearchResult(List<Tip> tips) {
        if (tips == null || tips.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> strAddress = new ArrayList<>();
            for (Tip tip: tips) {
                String addr = tip.getName();
                String addrDetail = tip.getAddress();
                if (addrDetail != null && !addrDetail.isEmpty()) {
                    addr += " - " + addrDetail;
                }
                strAddress.add(addr);
            }
            lvSearchResult.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_expandable_list_item_1, strAddress));
            lvSearchResult.setOnItemClickListener((parent, view, position, id) -> {
                Tip tip = tips.get(position);
                selectedTip = tip;
                LatLonPoint latLonPoint = tip.getPoint();
                lvSearchResult.setVisibility(View.GONE);
                //lvSearchResult.setAdapter(null);
                //editFloatSearch.clearFocus();
                //editFloatSearch.removeTextChangedListener(searchEditWatcher);
                ignoredInput = true;
                String naviStrName = tip.getName();
                editFloatSearch.setText(naviStrName);
                ignoredInput = false;
                if (latLonPoint != null) {
                    imageSearchNavi.setVisibility(VISIBLE);
                    if (mOnSearchListener != null) {
                        mOnSearchListener.onSearchSelected(latLonPoint.getLongitude(), latLonPoint.getLatitude(), tip.getName());
                    }
                }
                //editFloatSearch.addTextChangedListener(searchEditWatcher);
            });
        }
    }
}
