/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.bxzk.afxj.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.bxzk.afxj.R;


/**
 * 通用密码、手机号、验证码输入框输入字符判断及错误提示 类
 *
 * @author Lemon
 * @use EditTextUtil.xxxMethod(...);
 */
public class EditTextUtil {
    private static final String TAG = "EditTextUtil";


    //显示/隐藏输入法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 隐藏输入法
     *
     * @param context
     * @param toGetWindowTokenView
     */
    public static void hideKeyboard(Context context, View toGetWindowTokenView) {
        showKeyboard(context, null, toGetWindowTokenView, false);
    }

    /**
     * 显示输入法
     *
     * @param context
     * @param et
     */
    public static void showKeyboard(Context context, EditText et) {
        showKeyboard(context, et, true);
    }

    /**
     * 显示/隐藏输入法
     *
     * @param context
     * @param et
     * @param show
     */
    public static void showKeyboard(Context context, EditText et, boolean show) {
        showKeyboard(context, et, null, show);
    }

    /**
     * 显示输入法
     *
     * @param context
     * @param et
     * @param toGetWindowTokenView(为null时toGetWindowTokenView = et) 包含et的父View，键盘根据toGetWindowTokenView的位置来弹出/隐藏
     */
    public static void showKeyboard(Context context, EditText et, View toGetWindowTokenView) {
        showKeyboard(context, et, toGetWindowTokenView, true);
    }

    /**
     * 显示/隐藏输入法
     *
     * @param context
     * @param et
     * @param toGetWindowTokenView(为null时toGetWindowTokenView = et) 包含et的父View，键盘根据toGetWindowTokenView的位置来弹出/隐藏
     * @param show
     */
    public static void showKeyboard(Context context, EditText et, View toGetWindowTokenView, boolean show) {
        if (context == null) {
            Log.e(TAG, "showKeyboard  context == null >> return;");
            return;
        }

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);//imm必须与context唯一对应
        if (toGetWindowTokenView == null) {
            Log.w(TAG, "showKeyboard   toGetWindowTokenView == null");
            toGetWindowTokenView = et;
        }
        if (toGetWindowTokenView == null) {
            Log.e(TAG, "showKeyboard  toGetWindowTokenView == null && et == null  >> return;");
            return;
        }

        if (show == false) {
            imm.hideSoftInputFromWindow(toGetWindowTokenView.getWindowToken(), 0);
            if (et != null) {
                et.clearFocus();
            }
        } else {
            if (et != null) {
                et.setFocusable(true);
                et.setFocusableInTouchMode(true);
                et.requestFocus();
                imm.toggleSoftInputFromWindow(toGetWindowTokenView.getWindowToken()
                        , InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        }
    }

    //显示/隐藏输入法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //对输入字符判断<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    public final static int TYPE_NOT_ALLOWED_EMPTY = 0;
    public final static int TYPE_VERIFY = 1;
    public final static int TYPE_PASSWORD = 2;
    public final static int TYPE_PHONE = 3;
    public final static int TYPE_MAIL = 4;

    private static ColorStateList oringinalHintColor;

    /**
     * 判断edittext输入文字是否合法
     *
     * @param context
     * @param et
     * @return
     */
    public static boolean isInputedCorrect(Activity context, EditText et) {
        return isInputedCorrect(context, et, TYPE_NOT_ALLOWED_EMPTY, null);
    }

    /**
     * 判断edittext输入文字是否合法
     *
     * @param context
     * @param et
     * @param errorRemind
     * @return
     */
    public static boolean isInputedCorrect(Activity context, EditText et, String errorRemind) {
        return isInputedCorrect(context, et, TYPE_NOT_ALLOWED_EMPTY, errorRemind);
    }

    /**
     * 判断edittext输入文字是否合法
     *
     * @param context
     * @param et
     * @param type
     * @return
     */
    public static boolean isInputedCorrect(Activity context, EditText et, int type) {
        return isInputedCorrect(context, et, type, null);
    }

    /**
     * 判断edittext输入文字是否合法
     *
     * @param context
     * @param stringResId
     * @param et
     * @return
     */
    public static boolean isInputedCorrect(Activity context, int stringResId, EditText et) {
        return isInputedCorrect(context, et, TYPE_NOT_ALLOWED_EMPTY, stringResId);
    }

    /**
     * 判断edittext输入文字是否合法
     *
     * @param context
     * @param et
     * @param type
     * @param stringResId
     * @return
     */
    public static boolean isInputedCorrect(Activity context, EditText et, int type, int stringResId) {
        try {
            if (context != null && stringResId > 0) {
                return isInputedCorrect(context, et, type, context.getResources().getString(stringResId));
            }
        } catch (Exception e) {
            Log.e(TAG, "isInputedCorrect try { if (context != null && stringResId > 0) {catch (Exception e) \n" + e.getMessage());
        }
        return false;
    }

    /**
     * 判断edittext输入文字是否合法
     *
     * @param context
     * @param et
     * @param type
     * @return
     */
    public static boolean isInputedCorrect(Activity context, EditText et, int type, String errorRemind) {
        if (context == null || et == null) {
            Log.e(TAG, "isInputedCorrect context == null || et == null >> return false;");
            return false;
        }
        oringinalHintColor = et.getHintTextColors();

        String inputed = StringUtil.getTrimedString(et);
        switch (type) {
            case TYPE_VERIFY:
                if (type == TYPE_VERIFY && inputed.length() < 4) {
                    return showInputedError(context, et, StringUtil.isNotEmpty(errorRemind, true) ? errorRemind : "验证码不能小于4位");
                }
                break;
            case TYPE_PASSWORD:
                if (inputed.length() < 6) {
                    return showInputedError(context, et, StringUtil.isNotEmpty(errorRemind, true) ? errorRemind : "密码不能小于6位");
                }
                if (StringUtil.isNumberOrAlpha(inputed) == false) {
                    return showInputedError(context, et, StringUtil.isNotEmpty(errorRemind, true) ? errorRemind : "密码只能含有字母或数字");
                }
                break;
            case TYPE_PHONE:
                if (inputed.length() != 11) {
                    return showInputedError(context, et, StringUtil.isNotEmpty(errorRemind, true) ? errorRemind : "请输入11位手机号");
                }
                if (StringUtil.isPhone(inputed) == false) {
                    Toast.makeText(context, "您输入的手机号格式不对哦~", Toast.LENGTH_SHORT).show();
                    return false;
                }
                break;
            case TYPE_MAIL:
                if (StringUtil.isEmail(inputed) == false) {
                    return showInputedError(context, "您输入的邮箱格式不对哦~");
                }
                break;
            default:
                if (StringUtil.isNotEmpty(inputed, true) == false || inputed.equals(StringUtil.getTrimedString(et.getHint()))) {
                    return showInputedError(context, et, StringUtil.isNotEmpty(errorRemind, true) ? errorRemind : StringUtil.getTrimedString(et));
                }
                break;
        }

        et.setHintTextColor(oringinalHintColor);
        return true;
    }


    /**
     * 字符不合法提示(toast)
     *
     * @param context
     * @param resId
     * @return
     */
    public static boolean showInputedError(Activity context, int resId) {
        return showInputedError(context, null, resId);
    }

    /**
     * 字符不合法提示(et == null ? toast : hint)
     *
     * @param context
     * @param et
     * @param resId
     * @return
     */
    public static boolean showInputedError(Activity context, EditText et, int resId) {
        try {
            return showInputedError(context, et, context.getResources().getString(resId));
        } catch (Exception e) {
            Log.e(TAG, "" + e.getMessage());
        }
        return false;
    }

    /**
     * 字符不合法提示(toast)
     *
     * @param context
     * @param string
     * @return
     */
    public static boolean showInputedError(Activity context, String string) {
        return showInputedError(context, null, string);
    }

    /**
     * 字符不合法提示(et == null ? toast : hint)
     *
     * @param context
     * @param et
     * @param string
     * @return
     */
    public static boolean showInputedError(Activity context, EditText et, String string) {
        if (context == null || StringUtil.isNotEmpty(string, false) == false) {
            Log.e(TAG, "showInputedError  context == null || et == null || StringUtil.isNotEmpty(string, false) == false >> return false;");
            return false;
        }
        if (et == null) {
            Toast.makeText(context, StringUtil.getTrimedString(string), Toast.LENGTH_SHORT).show();
        } else {
            et.setText("");
            et.setHint(string);
            et.setHintTextColor(context.getResources().getColor(R.color.red));
        }
        return false;
    }

    //对输入字符判断>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    /**
     * 密码显示或隐藏 （切换）
     */
    public static void showOrHide(EditText etPassword) {
        //记住光标开始的位置
        int pos = etPassword.getSelectionStart();
        if (etPassword.getInputType() != (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {//隐藏密码
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {//显示密码
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
        etPassword.setSelection(pos);

    }

    /**
     * 密码显示或隐藏 （切换）
     */
    public static void show(EditText etPassword) {
        //记住光标开始的位置
        int pos = etPassword.getSelectionStart();
        etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        etPassword.setSelection(pos);

    }

    public static void hide(EditText etPassword) {
        //记住光标开始的位置
        int pos = etPassword.getSelectionStart();
        etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        etPassword.setSelection(pos);

    }

    public static void enableEdit(EditText editText, boolean editable) {
        if (editable) {
            editText.setFocusableInTouchMode(true);

            editText.setFocusable(true);

            editText.requestFocus();
        } else {
            editText.setFocusable(false);

            editText.setFocusableInTouchMode(false);
        }
    }

    public static void setInputMethodManager(Activity context, boolean isOpenInput, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isOpenInput) {
            editText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    imm.showSoftInput(editText, 0);//强制显示
                }
            }, 200);
        } else {
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    /**
     * 禁止EditText输入空格
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * Edittext字符数
     *
     * @param editText
     */
    public static void setMaxNum(EditText editText, int num) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) return "";
                else return null;
            }
        };

        InputFilter[] filters = {filter, new InputFilter.LengthFilter(num)};
        editText.setFilters(filters);


    }

    public static void setNum(EditText editText, int decimalNumber) {

        editText.setFilters(new InputFilter[]{new InputFilter() {

            @Override
            //source:即将输入的内容 dest：原来输入的内容
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String sourceContent = source.toString();
                String lastInputContent = dest.toString();

                //验证删除等按键
                if (TextUtils.isEmpty(sourceContent)) {
                    return "";
                }
                //以小数点"."开头，默认为设置为“0.”开头
                if (sourceContent.equals(".") && lastInputContent.length() == 0) {
                    return "0.";
                }
                //输入“0”，默认设置为以"0."开头
                if (sourceContent.equals("0") && lastInputContent.length() == 0) {
                    return "0.";
                }
                //小数点后保留两位
                if (lastInputContent.contains(".")) {
                    int index = lastInputContent.indexOf(".");
                    if (dend - index >= decimalNumber + 1) {
                        return "";
                    }

                }
                return null;
            }
        }});


    }

    public static void setPoint(final EditText editText, int DECIMAL_DIGITS) {

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

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

    /**
     * @param editText
     * @param DECIMAL_DIGITS 小数限制位数
     * @param num            整数限制位数
     */
    public static void setPoint(final EditText editText, int DECIMAL_DIGITS, int num) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                    String[] split = s.toString().split("\\.");
                    if (split.length == 2 && split[0].length() > num) {
                        s = split[0].substring(0,5) + "." + split[1];
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }

                }
                String[] split = s.toString().split("\\.");
                if (split.length == 1 && split[0].length() > num) {
                    s = split[0].substring(0,5);
                    editText.setText(s);
                    editText.setSelection(s.length());
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

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


}
