package com.common.lib_base.utils.ui;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.InputFilter;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.common.lib_base.CommonApplication;
import com.common.lib_base.utils.LogUtils;
import com.common.lib_base.utils.StringUtils;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Date: 2022/5/19 0019 17:38
 * Description:
 */
public final class UIUtils {

    // 当前类名
    public static String mTag = "UIUtils--";


    public static Context getContext() {
        return CommonApplication.getContext();
    }


    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public static int px2dip(float pxValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dip2px(float dpValue) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 设置EditText hint文字
     *
     * @param et
     * @param text
     * @param size
     */
    public static void setEditTextHint(EditText et, String text, int size) {

        if (et == null) {
            return;
        }

        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(text);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan as = new AbsoluteSizeSpan(size, true);
        // 附加属性到文本
        ss.setSpan(as, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        et.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }


    public static String getEditText(EditText et) {
        if (et == null) {
            return "";
        }
        String result = et.getText().toString().trim();
        return result;
    }

    public static void setEditText(EditText et, String text) {
        if (et == null) {
            return;
        }
        et.setText(text);
    }


    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpeChats(EditText editText) {

//        InputFilter filter = (source, start, end, dest, dstart, dend) -> {
//            if (!TextUtils.isEmpty(source)) {
//                SpannableString ss = new SpannableString(source);
//                Object[] spans = ss.getSpans(0, ss.length(), Object.class);
//                if (spans != null) {
//                    String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
//
////                    String speChat="^([a-z]|[A-Z]|[0-9]|[u2E80-u9FFF]){3,}|@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$";
//
//                    //这里也可以根据自己的需求自行添加需要判断的特殊符号
//                    if (source.toString().equals("\"") || source.toString().equals("\'")) {
//                        return "";
//                    }
////                    String speChat = "[`''<>/”“’]";
//                    Pattern pattern = Pattern.compile(speChat);
//                    Matcher matcher = pattern.matcher(source.toString());
//                    if (matcher.find()) {
//                        return "";
//                    } else {
//                        return null;
//                    }
//                }
//            }
//            return null;
//        };
//        editText.setFilters(new InputFilter[]{filter});
//        editText.setFilters(new EmojiFilter[]{filter});
        editText.setFilters(inputFilters);
    }

    public static void setEditTextEmojiFilter(EditText editText) {
        editText.setFilters(inputFilters);
    }

    public static InputFilter[] inputFilters = new 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);
                    LogUtils.e("inputFilters : " + source + " dest: " + dest);
                    // 表情包判断
                    if (emojiMatcher.find()) {
                        ToastUtils.showLongToast("不支持输入表情");
                        return "";
                    }

                    // 颜文字判断
                    SpannableString ss = new SpannableString(source);
                    Object[] spans = ss.getSpans(0, ss.length(), Object.class);
                    if (spans != null) {
                        String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

//                    String speChat="^([a-z]|[A-Z]|[0-9]|[u2E80-u9FFF]){3,}|@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$";

                        //这里也可以根据自己的需求自行添加需要判断的特殊符号
                        if (source.toString().equals("\"") || source.toString().equals("\'")) {
                            return "";
                        }
//                    String speChat = "[`''<>/”“’]";
                        Pattern pattern = Pattern.compile(speChat);
                        Matcher matcher = pattern.matcher(source.toString());
                        if (matcher.find()) {
                            ToastUtils.showLongToast("不支持输入颜文字");
                            return "";
                        }
                    }
                    return null;
                }

            },
            new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    for (int i = start; i < end; i++) {
                        int type = Character.getType(source.charAt(i));
                        LogUtils.e("inputFilters2 : " + source + " type: " + type);
                        if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
                            ToastUtils.showLongToast("不支持输入表情");
                            return "";
                        }
                    }
                    return null;
                }
            },
            /**这里限制输入的长度为200*/
            new InputFilter.LengthFilter(200)
    };


    public static String getText(TextView tv) {
        String result = tv.getText().toString().trim();
        return result;
    }


    public static void showSoftKeyboard(final AppCompatActivity activity) {
        showSoftKeyboardDelay(activity, 300);
    }

    /**
     * 弹起软键盘输入法
     *
     * @param activity
     * @param delayTime
     */
    public static void showSoftKeyboardDelay(final AppCompatActivity activity, final int delayTime) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, delayTime);
    }

    /**
     * 判断输入法是否弹起
     *
     * @param activity
     * @return true 表示弹起状态   false  表示非弹起
     */
    public static boolean softKeyboardStatus(final AppCompatActivity activity) {
        if (activity.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            LogUtils.e(mTag + "softKeyboardStatus 软键盘弹起状态");
            return true;
        }
        LogUtils.e(mTag + "softKeyboardStatus 软键盘隐藏状态");
        return false;
    }


    /**
     * 根据软键盘状态隐藏软键盘输入法
     * 建议使用
     *
     * @param activity
     */
    public static void hideSoftKeyboardByStatus(final AppCompatActivity activity) {
        if (softKeyboardStatus(activity)) {
            //
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        } else {
            ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(activity.getCurrentFocus()
                            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 隐藏软键盘输入法
     *
     * @param activity
     */
    public static void hideSoftKeyboard(final AppCompatActivity activity) {
        // 无软键盘弹出时，有时候空指针
//        ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
//                .hideSoftInputFromWindow(activity.getCurrentFocus()
//                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }


    /**
     * @param activity
     */
    public static void hideSoftKeyboard(final Activity activity) {
        // 有时候空指针
//        ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
//                .hideSoftInputFromWindow(activity.getCurrentFocus()
//                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    /**
     * 解决dropDownMenu隐藏软键盘时，报android.os.IBinder android.view.View.getWindowToken()——https://blog.csdn.net/qq_16318981/article/details/53301997
     *
     * @param activity
     * @param view
     */
    public static void hideSoftKeyboard(final Activity activity, final View view) {
        ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(view.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void setColor(Context context, TextView tv, int color) {
        tv.setTextColor(context.getResources().getColor(color));
    }


    /**
     * 设置背景透明度
     *
     * @param activity
     * @param f        值为0-1.0，值越小就越不透明
     */
    public static void setBackgroundAlpha(AppCompatActivity activity, float f) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = f;
        activity.getWindow().setAttributes(lp);
    }

    public static void setBackgroundAlpha(Activity activity, float f) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = f;
        activity.getWindow().setAttributes(lp);
    }

    public static void setText(TextView tv, String text) {
        if (tv != null) {
            if (StringUtils.isNull(text)) {
                tv.setText("");
            } else {
                tv.setText(text + "");
            }

        }
    }

    public static void setText(TextView tv, int text) {
        if (tv != null) {
            tv.setText(text + "");
        }
    }


    /**
     * 关键字高亮变色
     *
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     * @return 结果SpannableString
     */
    public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
        SpannableString s = new SpannableString(text);
        keyword = escapeExprSpecialWord(keyword);
        text = escapeExprSpecialWord(text);
        if (text.contains(keyword) && !TextUtils.isEmpty(keyword)) {
            try {
                Pattern p = Pattern.compile(keyword);
                Matcher m = p.matcher(s);
                while (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } catch (Exception e) {
            }
        }
        return s;
    }

    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     *
     * @param keyword
     * @return keyword
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (!TextUtils.isEmpty(keyword)) {
            String[] fbsArr = {"\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|"};
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }

    /**
     * @param color #ff9314
     * @return
     */
    public static int str2Color(String color) {
        int i = Color.parseColor(color);
        return i;
    }


    /**
     * @param color R.color.text_unblocked
     * @return
     */
    public static int setTextColor(int color) {
        int i = getContext().getResources().getColor(color);
        return i;
    }

    public static void setTextColor(TextView tv, String color) {
        tv.setTextColor(UIUtils.str2Color(color));
    }

    public static void setEditTextColor(EditText tv, String color) {
        tv.setTextColor(UIUtils.str2Color(color));
    }

    public static void setTextColor(TextView tv, int color) {
        tv.setTextColor(getContext().getResources().getColor(color));
    }

    public static void setBackground(View view, int drawable) {
        view.setBackground(getContext().getResources().getDrawable(drawable));
    }

    public static void setBackgroundColor(View view, String color) {
        view.setBackgroundColor(Color.parseColor(color));
//        view.setBackgroundColor(getContext().getResources().getColor(UIUtils.str2Color(color)));
    }

    /**
     * ImageView更换图片
     *
     * @param view
     * @param drawable R.mipmap.
     */
    public static void setImageResource(ImageView view, int drawable) {
        view.setImageResource(drawable);
    }

    public static void setIcon(ImageView iv, int resId) {
        iv.setImageResource(resId);
    }

    public static void setViewGone(View view) {
        if (view == null) {
            return;
        }
        view.setVisibility(View.GONE);
    }

    public static void setViewVisible(View view) {
        if (view == null) {
            return;
        }
        view.setVisibility(View.VISIBLE);
    }

    public static void setViewInvisible(View view) {
        if (view == null) {
            return;
        }
        view.setVisibility(View.INVISIBLE);
    }


    public static int dp2px(float dipValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


//    public static void showOrHideContent(TextView content,ImageView btn,int maxLines,String btntext){
//        Layout layout = content.getLayout();
//        if (layout != null) {
//            int lineCount = layout.getLineCount();
//            if (lineCount > maxLines) {
////                btn.setText(btntext);
//                btn.setVisibility(View.VISIBLE);
//            } else {
//                int ellipsisCount = layout.getEllipsisCount(lineCount - 1);//小米note2下返回0
//                if (ellipsisCount > 0) {
//                    btn.setVisibility(View.VISIBLE);
//                } else {
//                    btn.setVisibility(View.GONE);
//                }
//            }
//        } else {
//            ViewTreeObserver observer = content.getViewTreeObserver();
//            if (observer.isAlive()) {
//                observer.addOnPreDrawListener(
//                        new ViewTreeObserver.OnPreDrawListener() {
//                            @Override
//                            public boolean onPreDraw() {
//                                Layout layout = content.getLayout();
//                                if (layout != null) {
//                                    int lineCount = layout.getLineCount();
//                                    if (lineCount > maxLines) {//小米note2的兼容处理
//                                        btn.setVisibility(View.VISIBLE);
//                                    } else {
//                                        int ellipsisCount = layout.getEllipsisCount(lineCount - 1);//小米note2下返回0
//                                        if (ellipsisCount > 0) {
//                                            btn.setVisibility(View.VISIBLE);
//                                        } else {
//                                            btn.setVisibility(View.GONE);
//                                        }
//                                    }
//                                }
//                                try {
//                                    (content.getViewTreeObserver()).removeOnPreDrawListener(this);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                return true;
//                            }
//                        }
//                );
//            }
//        }
//    }


    public static boolean copyStr(Context context, String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            ToastUtils.showLongToast("已复制");
            return true;
        } catch (Exception e) {
            ToastUtils.showLongToast("复制失败");
            return false;
        }
    }

    /**
     * 手机号中间4位脱敏
     * @param phone
     * @return
     */
    public static String phoneDesensitization(String phone) {
        if (StringUtils.isNull(phone)) {
            return "";
        }
        if (phone.length() == 11) {
            phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
//            phone = phone.substring(3, 7).replaceAll("\\d", "*");
        }
        return phone;

    }


}
