package com.tofly.ghrq_route.module.map.pipeSearch;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.FeatureTable;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.GeodatabaseFeatureTable;
import com.esri.arcgisruntime.data.QueryParameters;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.module.map.service.Container;
import com.tofly.ghrq_route.common.ui.adapter.FieldAdapter;
import com.tofly.ghrq_route.common.ui.adapter.PipenetResultAdapter;
import com.tofly.ghrq_route.common.ui.adapter.TableNameAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;

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

/**
 * Created by lihualong on 2017/6/23.
 */

public class PipeSearchManager extends LinearLayout {
    private Context mContext;
    private View rootView;
    public BottomSheetBehavior behavior;
    private List<FeatureTable> featureTables;
    @BindView(R.id.layout_pipenet_collapse)
    LinearLayout layoutPipenetCollapse;
    @BindView(R.id.layout_search_option_area)
    LinearLayout layoutSearchOptionArea;
    @BindView(R.id.damageSpinner)
    Spinner damageSpinner;
    @BindView(R.id.causeSpinner)
    Spinner causeSpinner;
    @BindView(R.id.edit_search_content)
    EditText editSearchContent;
    @BindView(R.id.btn_search)
    ImageView btnSearch;

    @BindView(R.id.layout_header_row)
    LinearLayout layoutHeaderRow;
    @BindView(R.id.pipenet_result_listview)
    RecyclerView pipenetResultListview;
    @BindView(R.id.no_search_result)
    TextView noSearchResult;
    @BindView(R.id.progress_search)
    ProgressBar progressSearch;
    @BindView(R.id.pipenet_search_result_title)
    LinearLayout pipenetSearchResultTitle;
    private Container.HideSearchCallback hideCallback;
    private Unbinder bind;
    private PipenetResultAdapter pipenetResultAdapter;
    private TableNameAdapter tableNameAdapter;
    private FieldAdapter fieldAdapter;

    //    模糊查询
    private boolean mSearchObscureMode = true;
    private Container.OnMapShowListener onMapShowListener;

    private boolean mbShowOptionArea = true;
    private boolean mbShowSearchResult = false;

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

    public PipeSearchManager(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PipeSearchManager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();

    }

    private final String TAG = getClass().getName();

    public void onstart(final ClosePipeIconCallback closePipeIconCallback) {
        behavior = BottomSheetBehavior.from(this);
        behavior.setHideable(true);
        post(new Runnable() {
            @Override
            public void run() {
                behavior.setPeekHeight(rootView.getHeight());
            }
        });

        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                Log.w("TAG", "onStateChanged: newState" + newState);
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    if (pipenetResultAdapter != null)
                        pipenetResultAdapter.clearList();
                    closePipeToggle(closePipeIconCallback);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);

//        initSearchRequirement();
    }

    private void closePipeToggle(ClosePipeIconCallback closePipeIconCallback) {
        closePipeIconCallback.close();
    }

    public void destroy() {
        bind.unbind();
    }

    private List<Feature> blurryResult = new ArrayList<>();//模糊查询结果的字符串数组

    private void initSearchRequirement() {
        if (featureTables == null || featureTables.size() == 0)
            return;

        tableNameAdapter = new TableNameAdapter(featureTables, mContext);
        damageSpinner.setAdapter(tableNameAdapter);


        FeatureTable featureTable = featureTables.get(0);
        fieldAdapter = new FieldAdapter(mContext, featureTable.getFields());
        causeSpinner.setAdapter(fieldAdapter);

        pipenetResultAdapter = new PipenetResultAdapter(blurryResult, mContext);
        pipenetResultListview.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        pipenetResultListview.setLayoutManager(layoutManager);
        pipenetResultListview.setAdapter(pipenetResultAdapter);

        if (blurryResult.size() == 0) {
            pipenetSearchResultTitle.setVisibility(View.GONE);
            layoutHeaderRow.setVisibility(View.GONE);
        }

    }

    private void initListener() {

    }

    private void initView() {
        if (this.rootView == null) {
            this.rootView = inflate(this.mContext, R.layout.fragment_pipenet_search, this);
        }else {
            ViewGroup parent = (ViewGroup) this.rootView.getParent();
            parent.removeView(this.rootView);
        }
        bind = ButterKnife.bind(this.rootView);
//        this.behavior = BottomSheetBehavior.from(this.pipeSearchLl);
//        this.rootView.post(new Runnable() {
//            @Override
//            public void run() {
//            }
//        });
//        behavior.setPeekHeight(rootView.getHeight());
    }

    public void initPipeData(List<FeatureTable> allFeatureTable) {
        this.featureTables = allFeatureTable;
        initSearchRequirement();
    }

    @OnClick({R.id.pipenet_search_close_iv, R.id.btn_search, R.id.layout_pipenet_collapse})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pipenet_search_close_iv:
//                PipeSearchFragment.this.dismiss();
                behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                break;
            case R.id.btn_search:
                searchContent();
                break;
            case R.id.layout_pipenet_collapse:
                showOrHideSearchOption();
                break;
        }
    }

    private void showOrHideSearchOption(){
        /*if (mbShowSearchResult){
            mbShowOptionArea = !mbShowOptionArea;
            if (mbShowOptionArea){
                imageDrawerOption.setImageResource(R.mipmap.pipenet_collapse_up);
                layoutSearchOptionArea.setVisibility(VISIBLE);
            }else {
                imageDrawerOption.setImageResource(R.mipmap.pipenet_collapse_down);
                layoutSearchOptionArea.setVisibility(GONE);
            }
        }*/
    }

    private void searchContent() {
        final String strInput = editSearchContent.getEditableText().toString();
        if (strInput == null || strInput.isEmpty()) {
            ToastUtil.showToast(mContext, R.string.pipenet_warning_no_keyword);
            return;
        }

        GeodatabaseFeatureTable geoSel = (GeodatabaseFeatureTable) damageSpinner.getSelectedItem();
        Field fieldSel = (Field) causeSpinner.getSelectedItem();
        if (geoSel == null || fieldSel == null) {
            ToastUtil.showToast(mContext, R.string.pipenet_warning_no_table);
            return;
        }

        if (this.featureTables == null || this.featureTables.isEmpty()) {
            ToastUtil.showToast(mContext, R.string.pipenet_warning_no_beanlist);
            return;
        }
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context
                .INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromInputMethod(editSearchContent.getWindowToken(), 0);
        }
        final String tableName = geoSel.getTableName();
        final String fieldSelName = fieldSel.getName();
        Log.w("TAG", "onQueryTextChange: tableName :" + tableName);
        Log.w("TAG", "onQueryTextChange: fieldName :" + fieldSelName);

        if (blurryResult == null) {
            blurryResult = new CopyOnWriteArrayList<Feature>();
        } else {
            if (blurryResult.size() > 0) {
                blurryResult.clear();
            }
        }

        btnSearch.setEnabled(false);
        pipenetSearchResultTitle.setVisibility(View.GONE);
        layoutHeaderRow.setVisibility(View.GONE);
        pipenetResultListview.setVisibility(View.GONE);
        noSearchResult.setVisibility(View.GONE);
        progressSearch.setVisibility(View.VISIBLE);
        if (behavior.getState() == BottomSheetBehavior.STATE_COLLAPSED)
            behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        Runnable searhRunnable
                = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getBlurryResult(tableName, fieldSelName, strInput, featureTables);
                mHandler.sendEmptyMessage(HAN_SEARCHTEXTCHANGE);

            }
        };
        new Thread(searhRunnable).start();
    }

    private final int HAN_SEARCHTEXTCHANGE = 10;//模糊搜索结果

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HAN_SEARCHTEXTCHANGE) {
                progressSearch.setVisibility(View.GONE);
                if (blurryResult != null && blurryResult.size() > 0) {
                    showPipeSearchResult(-1);
                } else {
                    closePipeSearchResult();
                }
                btnSearch.setEnabled(true);
            }
        }

    };

    //关闭查询结果列表
    private void closePipeSearchResult() {
        pipenetResultListview.setVisibility(View.GONE);
        pipenetSearchResultTitle.setVisibility(View.VISIBLE);
        layoutHeaderRow.setVisibility(View.GONE);
        noSearchResult.setVisibility(View.VISIBLE);
        mbShowSearchResult = false;
    }

    //显示管线查询结果列表
    private void showPipeSearchResult(int selectPosition) {
//        resultAdapter.clearList();

        pipenetResultAdapter.setDataChanged(blurryResult, selectPosition);
        pipenetResultAdapter.setResultListener(new Container.OnResultClickListener() {
            @Override
            public void showCalloutAtMap(Feature feature, int position) {
                if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
                if (pipenetResultAdapter != null) {
                    pipenetResultAdapter.setSelected(position);
                }
                if (onMapShowListener != null) {
                    onMapShowListener.showAtMap(feature);
                }
            }
        });
        pipenetResultListview.setVisibility(View.VISIBLE);
        pipenetSearchResultTitle.setVisibility(View.VISIBLE);
        layoutHeaderRow.setVisibility(View.VISIBLE);
        noSearchResult.setVisibility(View.GONE);
        mbShowSearchResult = true;
    }

    public void getBlurryResult(String tableName, final String fieldName,
                                         final String layName, List<FeatureTable> tableBeanList) {
        for (FeatureTable featureTable : tableBeanList) {
            if (tableName.equals(featureTable.getTableName())) {
                if (featureTable.hasGeometry()) {
                    Log.w("TAG", "getBlurryResult: featureTable = " + featureTable);
                    String where = fieldName + " like '%" + layName + "%'";
                    if (!mSearchObscureMode) {
                        where = fieldName + " = " + layName;
                    }
                    Log.w(TAG, "Search query is: " + where);
                    QueryParameters queryParameters = new QueryParameters();
                    queryParameters.setWhereClause(where);

                    final ListenableFuture<FeatureQueryResult> query = featureTable.queryFeaturesAsync(queryParameters);
                    query.addDoneListener(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                FeatureQueryResult result = query.get();
                                for (Feature feature : result) {
                                    blurryResult.add(feature);
                                }
                            } catch (ExecutionException e) {
                                Log.w("TAG", "getBlurryResult: 查询时出错 e = " + e.getMessage());
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                Log.w("TAG", "getBlurryResult: 查询时出错 e = " + e.getMessage());
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }

    @OnCheckedChanged(R.id.switch_search_mode)
    protected void onChanged(boolean isChecked) {
        mSearchObscureMode = isChecked;
    }

    @OnItemSelected({R.id.damageSpinner})
    public void onItemClicked(View view, int position, long i) {
        List<Field> fields = featureTables.get(position).getFields();
        fieldAdapter = new FieldAdapter(mContext, fields);
        causeSpinner.setAdapter(fieldAdapter);
    }

    public void setOnMapShowListener(Container.OnMapShowListener osl) {
        this.onMapShowListener = osl;
    }


    public interface ClosePipeIconCallback {
        void close();
    }

}
