package com.rv.component.utils;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 虚拟键盘操作
 */
public class KeyboardUtil {

    /**
     * 关闭虚拟键盘
     *
     * @param activity
     */
    public static boolean getKeyboardState(Activity activity) {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager)
                    activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            //键盘是打开的状态
            return inputMethodManager.isActive();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 关闭虚拟键盘
     *
     * @param activity
     */
    public static void hideKeyboard(Activity activity) {

        if (getKeyboardState(activity)) {
            //键盘是打开的状态
            InputMethodManager inputMethodManager = (InputMethodManager)
                    activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            View view = activity.getCurrentFocus();
            if (view != null) {
                if (view.getWindowToken() != null) {
                    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }

    }

    /**
     * 显示虚拟键盘
     *
     * @param mEditText
     */
    public static void showKeyboard(EditText mEditText) {
        mEditText.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager) mEditText.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(mEditText, 0);
    }

    /**
     * 隐藏虚拟键盘
     *
     * @param mEditText
     */
    public static void hideKeyboard(EditText mEditText) {
        InputMethodManager imm =
                (InputMethodManager) mEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        mEditText.clearFocus();
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }


    public interface OnKeyboardStateListener {
        void onKeyboardShow();

        void onKeyboardHide();
    }

    //屏幕高度
    private static int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private static int keyHeight = 0;

    /**
     * 监听虚拟键盘弹起与隐藏
     * 所要具备的条件：
     * 1.在manifest文件配置当前activity  android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
     * 2.得到当前屏幕高度
     * 3.设置虚拟键盘弹出来的高度阀值
     * 4.在onResume里调用此方法
     *
     * @param activity
     * @param view     必须是根布局
     * @param listener 另外，如果根布局是ScrollView 可设置其 android:fillViewport="true" 达到自动撑开布局
     *                 如果是在横屏状态下可设置editText   android:imeOptions="flagNoExtractUi"达到不用新开一个界面来输入
     */
    public static void setOnKeyboardStateListener(Activity activity, View view, final OnKeyboardStateListener listener) {
        //获取屏幕高度
        screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;

        view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right,
                                       int bottom, int oldLeft, int oldTop,
                                       int oldRight, int oldBottom) {
                //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                    listener.onKeyboardShow();
                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                    listener.onKeyboardHide();
                }
            }
        });
    }


    /**
     * 监听EditText软件 键盘，现在是禁用换行
     */
    public static void setOnEditTextKeyboardListener(EditText... mEditText) {
        for (int i = 0; i < mEditText.length; i++) {
            final EditText editText = mEditText[i];
            editText.setImeOptions(EditorInfo.IME_ACTION_SEND);
            editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    //当actionId == XX_SEND 或者 XX_DONE时都触发
                    //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                    //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                    if (actionId == EditorInfo.IME_ACTION_SEND
                            || actionId == EditorInfo.IME_ACTION_DONE ||
                            (event != null
                                    && KeyEvent.KEYCODE_ENTER == event.getKeyCode()
                                    && KeyEvent.ACTION_DOWN == event.getAction())) {
                        //处理事件
                        hideKeyboard(editText);
                        editText.requestFocus();
                        editText.setFocusable(true);
                        return true;
                    }
                    return false;
                }
            });
        }

    }


    public static void setEditTextMaxLength(final EditText editText, final int max, final TextView maxTextHint) {
        final int alreadyStringLenght = editText.getText().toString().length();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (charSequence.length() <= max) {
                    maxTextHint.setText(String.valueOf(charSequence.length()));
                } else {
                    editText.setText(charSequence.subSequence(0, max));
                    editText.setSelection(editText.getText().toString().length());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    //EditText软键盘显示下一个
    public static void addKeyboardNextEditText(final OnEditDoneListener listener, EditText... views) {
        for (int i = 0; i < views.length; i++) {
            EditText it = views[i];
            if (i < views.length - 1) {
                it.setImeOptions(EditorInfo.IME_ACTION_NEXT);
                it.setNextFocusForwardId(views[(i + 1)].getId());
            } else {
                it.setImeOptions(EditorInfo.IME_ACTION_DONE);
            }
            it.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) listener.actionDone((EditText) v);

                    return false;
                }
            });
            InputFilter inputFilter = new InputFilter() {
                Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                        Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    Matcher emojiMatcher = emoji.matcher(source);
                    if (emojiMatcher.find()) {
                        //ToastUtils.showShort("不支持输入emoji表情");
                        return "";
                    }
                    return null;
                }
            };
            //限制 表情输入
            InputFilter[] inputFilters = new InputFilter[]{inputFilter, new InputFilter.LengthFilter(KeyboardUtil.getMaxLength(it))};
            it.setFilters(inputFilters);
        }
    }


    /**
     * 　　 获取设置的最大长度
     * 　　 @return int max
     */

    public static int getMaxLength(EditText et) {
        int length = 200;//默认200
        try {
            InputFilter[] inputFilters = et.getFilters();
            for (InputFilter filter : inputFilters) {
                Class<?> c = filter.getClass();
                if (c.getName().equals("android.text.InputFilter$LengthFilter")) {
                    Field[] f = c.getDeclaredFields();
                    for (Field field : f) {
                        if (field.getName().equals("mMax")) {
                            field.setAccessible(true);
                            length = (Integer) field.get(filter);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }

    public interface OnEditDoneListener {
        void actionDone(EditText e);
    }
}
