package com.app.baselibrary.commonUtil;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.TouchDelegate;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.app.baselibrary.R;
import com.app.baselibrary.base.app.BaseApplication;
import com.app.baselibrary.utils.TimerTaskHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class UIUtils {

    static PowerManager.WakeLock mWakeLock;

    static TimerTaskHelper timerTaskHelper;
    static String TASKNAME_AUTODISMISS="autoDismissTask";
    static String TASKNAME_KEYWORD="keywordTask";
    private static double epsilon = 1e-6;

    public static String toShortString(Double d) {
        if (d == null) {
            return "";
        }
        long l = d.longValue();
        if (-epsilon < d - l && d - l < epsilon) {
            return String.valueOf(l);
        } else {
            return String.valueOf(d);
        }
    }

    public static String centToString(Double money) {
        if (money == null) {
            return "";
        }
        return centToString(Math.round(money));
    }

    public static String centToString(Long money) {
        if (money == null) {
            return "";
        }
        return String.format("%,.2f", money / 100.0);
    }

    public static long textViewToCent(View v) {
        try {
            return stringToCent(((TextView) v).getText().toString());
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    public static long stringToCent(String money) {
        return Math.round(Double.parseDouble(money.replace(",", "")) * 100);
    }

    public static int DoubleToInt(Double d) {
        return d.intValue();
    }


    public static int dpToPx(int dp, Context ctx) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dp, ctx.getResources().getDisplayMetrics());
    }


    public static void hideKeyboard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void showKeyboard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    public static boolean isValidMobile(String input) {
        try {
            long phone = Long.parseLong(input);

            String phoneString = String.valueOf(phone);
            if (TextUtils.isEmpty(phoneString) ||
                    phoneString.length() != 11) {

                return false;
            }
        } catch (Exception ex) {
            return false;
        }

        return true;
    }


    //用当前时间给取得的图片命名
    public static String createPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        return dateFormat.format(date) + ".jpg";
    }


    public static int getWindowWidth(Context context) {
        int width;
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        try {
            if (Build.VERSION.SDK_INT < 13) {
                DisplayMetrics displaymetrics = new DisplayMetrics();
                display.getMetrics(displaymetrics);
                width = displaymetrics.widthPixels;
            } else {
                Point size = new Point();
                display.getSize(size);
                width = size.x;
            }
        } catch (NoSuchMethodError e) {
            try {
                width = display.getWidth();
            } catch (Exception ex) {
                width = 200;
            }
        }
        return width;
    }

    public static int getWindowHeight(Context context) {
        int height;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        context.getApplicationContext().getResources().getDisplayMetrics();
        Display display = windowManager.getDefaultDisplay();
        try {
            if (Build.VERSION.SDK_INT < 13) {
                DisplayMetrics displaymetrics = new DisplayMetrics();
                display.getMetrics(displaymetrics);
                height = displaymetrics.heightPixels;
            } else {
                Point size = new Point();
                display.getSize(size);
                height = size.y;
            }
        } catch (NoSuchMethodError e) {
            try {
                height = display.getHeight();
            } catch (Exception ex) {
                height = 200;
            }
        }
        return height;
    }

    public static Boolean isNetworkConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        return networkinfo != null && networkinfo.isAvailable();

    }

    public static Map<String, String> getDeviceInfo() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("os", "android");
        String model = Build.MODEL;
        if (!TextUtils.isEmpty(model)) {
            map.put("model", Uri.encode(model.replaceAll("\\s*", "")));
        }
        String brand = Build.BRAND;

        if (!TextUtils.isEmpty(brand)) {
            map.put("brand", Uri.encode(brand.replaceAll("\\s*", "")));
        }

        String product = Build.PRODUCT;
        if (!TextUtils.isEmpty(product)) {
            map.put("product", Uri.encode(product.replaceAll("\\s*", "")));
        }

        String s = String.valueOf(Build.VERSION.SDK_INT);
        if (!TextUtils.isEmpty(s)) {
            map.put("sdk_int", Uri.encode(s.replaceAll("\\s*", "")));
        }

        String device = Build.DEVICE;
        if (!TextUtils.isEmpty(device)) {
            map.put("device", Uri.encode(device.replaceAll("\\s*", "")));
        }

        String id = Build.ID;
        if (!TextUtils.isEmpty(id)) {
            map.put("device_id", Uri.encode(id.replaceAll("\\s*", "")));
        }

        String manufacturer = Build.MANUFACTURER;
        if (!TextUtils.isEmpty(manufacturer)) {
            map.put("manufacturer", Uri.encode(manufacturer.replaceAll("\\s*", "")));
        }

        return map;
    }

    public static boolean isUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        Pattern p = Pattern
                .compile("[a-zA-z]+://[^\\s]*");
        Matcher m = p.matcher(url);
        return m.matches();
    }




    public static void setOverridePendingTransition(Activity activity) {
        activity.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
    }



    /**
     * 扩大view的点击区域
     *
     * @param view
     * @param top
     * @param bottom
     * @param left
     * @param right
     */
    public static void expandViewTouchDelegate(final View view, final int top,
                                               final int bottom, final int left, final int right) {

        ((View) view.getParent()).post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right += right;

                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }


    /**
     * 显示键盘；
     */
    public static void showKeyboard(final View v) {
        timerTaskHelper=TimerTaskHelper.getInstance();
        timerTaskHelper.start(TASKNAME_KEYWORD, new Runnable() {
            @Override
            public void run() {
                ((InputMethodManager) BaseApplication.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(v, 0);

            }
        },800);
    }

    /**
     * 隐藏软键盘
     */
    public static void hideKeyboard(final Activity activity) {
        if (activity != null) {
            View view = activity.getWindow().peekDecorView();
            if (view != null) {
                InputMethodManager inputmanger = (InputMethodManager) BaseApplication.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    /**
     * 开始抖动动画效果
     *
     * @param view 需要进行抖动效果的文本
     */
    public static void startShakeAnimation(Context context, View view) {
        view.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake));
        view.requestFocus();
    }


    /**
     * 结束activity
     *
     * @param activity  老activity，用于调起finish()方法
     * @param enterAnim 新activity的进入动画
     * @param exitAnim  老activity的退出动画
     */
    public static void finishActivityWithAnim(Activity activity, int enterAnim, int exitAnim) {
        activity.finish();
        activity.overridePendingTransition(enterAnim, exitAnim);
        activity = null;
    }

    //判断当前activity是否存活
    public static boolean isActivityAlive(Activity activity) {
        if (activity != null && !activity.isFinishing())
            return true;
        return false;
    }

    /**
     * 保持播放时,屏幕常亮;
     */
    public static void acquireWakeLock(@NonNull Activity activity) {
        if (mWakeLock == null) {
            PowerManager pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, activity.getClass().getCanonicalName());
            mWakeLock.acquire();
        }
    }

    /**
     * 释放wakeLock;
     */
    public static void releaseWakeLock() {
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    /**
     * 控制试图3秒钟后隐藏;
     *
     * @param views 传入的view集合;
     */
    public static void autoDismiss(final Activity activity, int second, final View... views) {
        timerTaskHelper=TimerTaskHelper.getInstance();
        timerTaskHelper.start(TASKNAME_AUTODISMISS, new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (View v : views) {
                            if (v.getVisibility() == View.VISIBLE) {
                                v.setVisibility(View.GONE);
                            }
                        }
                    }
                });
            }
        }, second * 1000);

    }

    public static void cancelDismissTask() {
        timerTaskHelper.stop(TASKNAME_AUTODISMISS);
    }


    /**
     * 设置view是否可点击;
     *
     * @param isEnable
     * @param views
     */
    public static void setViewIsEnable(boolean isEnable, View... views) {

        for (View view : views) {
            view.setEnabled(isEnable);
            view.setFocusable(isEnable);
        }
    }

    /**
     * 设置View是否隐藏;
     *
     * @param isVisible
     * @param views
     */
    public static void setViewIsVisible(boolean isVisible, View... views) {
        for (View view : views) {
            view.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
        }
    }

    public static SpannableString getColoredString(String string,
                                                   int start,
                                                   int end,
                                                   int textColor,
                                                   float textSize,
                                                   boolean isBold) {
        SpannableString sp = new SpannableString(string);
        // 设置文字颜色

        sp.setSpan(new ForegroundColorSpan(textColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 文字大小
        if (textSize > 0) {
            sp.setSpan(new AbsoluteSizeSpan((int) textSize, true), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (isBold) {
            sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return sp;
    }

}

