package com.mayi.fastdevelop.util;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.FloatRange;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.mayi.fastdevelop.R;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;

/**
 * 系统相关工具类
 */
public class SystemUtil {

    /**
     * killProcess之后让整个Application重启，而不是简单重启Activity
     *
     * @param context
     */
    public static void restartApplication(Context context) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent);//500毫秒后重启
        android.os.Process.killProcess(android.os.Process.myPid());//杀死当前进程，AlarmManager系统级别定时任务服务将继续执行
        System.exit(0);
    }

    /**
     * 隐藏输入法
     *
     * @param activity
     * @return
     */
    public static boolean hideInputMethod(Activity activity) {
        return hideInputMethod(activity, null);
    }

    public static void hideInputMethod2(Context context, View view) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 隐藏输入法
     *
     * @param activity
     * @param view
     * @return
     */
    public static boolean hideInputMethod(Activity activity, View view) {
        if (view == null) {
            view = new View(activity);
        }
        boolean result1 = false;
        boolean result2 = false;
        if (activity == null)
            return false;
        try {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            result1 = imm.hideSoftInputFromWindow(activity.getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Throwable e) {
        }
        try {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive() && view != null) {
                result2 = imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
            }
        } catch (Throwable e) {
        }
        return result1 || result2;
    }

    /**
     * 是否输入法正在显示
     *
     * @param context
     * @return
     */
    public static boolean isInputMethodShowing(Context context) {
        if (context == null)
            return false;
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            return imm.isActive();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 显示输入法
     */
    public static void showInputMethod(Context context, View view) {
        if (view != null) {
            if (context == null)
                return;
            try {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 显示输入法
     */
    public static void showInputMethod(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 显示输入法
     */
    public static void showInputMethodFromDialog(Context context, Dialog dialog) {
        if (dialog != null && context != null) {
            try {
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);//显示软键盘
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); //显示软键盘
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 让Activity全屏，不显示标题栏和状态栏
     * 在Activity super.onCreate(savedInstanceState);代码之前调用
     *
     * @param activity
     */
    public static void noTitleFullScreen(Activity activity) {
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 让Activity不显示标题栏和状态栏
     * 在Activity super.onCreate(savedInstanceState);代码之前调用
     *
     * @param activity
     */
    public static void noTitleBar(Activity activity) {
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }


    /**
     * 返回一个控件在其父窗口中的坐标位置 x, y
     *
     * @param view
     * @return {x, y}
     */
    public static int[] getLocationInWindow(View view) {
        int[] location = {0, 0};
        view.getLocationInWindow(location);
        return location;
    }

    /**
     * 返回一个控件在其整个屏幕上的坐标位置 x, y
     *
     * @param view
     * @return {x, y}
     */
    public static int[] getLocationOnScreen(View view) {
        int[] location = {0, 0};
        view.getLocationOnScreen(location);
        return location;
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        try {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            return context.getResources().getDimensionPixelSize(resourceId);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return DisplayUtil.dip2px(context, 20);
    }

    /**
     * 得到屏幕高度
     *
     * @param ctx
     * @return
     */
    public static int getScreenHeight(Context ctx) {
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size.y;
    }

    /**
     * 得到屏幕宽度
     *
     * @param ctx
     * @return
     */
    public static int getScreenWidth(Context ctx) {
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size.x;
    }

    /**
     * 得到App版本名
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String result = "1.0";
        try {
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            result = pinfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 得到App版本号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int result = 1;
        try {
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            result = pinfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取APP应用名称
     *
     * @param context
     * @return
     */
    public static String getAppName(Context context) {
        String result = "";
        try {
            PackageManager packageManager = context.getApplicationContext().getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
            result = (String) packageManager.getApplicationLabel(applicationInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 拨打电话，到拨号页面
     *
     * @param context
     * @param tel     电话号码
     */
    public static void makePhoneCall(Context context, String tel) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + tel));
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制到剪切板
     *
     * @param context
     * @param text
     */
    public static void copyToClipboard(Context context, String text) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(text);
    }

    /**
     * 设置edittext是否显示/隐藏密码
     *
     * @param editText
     * @param show
     */
    public static void setEditTextPwdShow(EditText editText, boolean show) {
        int selection = -1;
        if (editText.getText().toString().length() > 0) {
            selection = editText.getSelectionStart();
        }
        if (show) {
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        if (selection != -1) {
            editText.setSelection(selection);
        }
    }

    /**
     * 浏览选择相册图片，配合onActivityResult和SystemUtils.getSelectedImg
     *
     * @param activity
     * @param requestCode
     */
    public static void callLocalImgViewer(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 调用系统裁剪图片工具，配合onActivityResult后检测output是否存在即可
     *
     * @param activity
     * @param input    要裁剪的图片
     * @param output   裁剪结果图片
     * @param width
     * @param height
     * @param reqCode
     */
    public static void startPhotoZoom(Activity activity, File input, File output, int width, int height, int reqCode) {
        boolean isHuawei = Build.MANUFACTURER.toUpperCase().contains("HUAWEI"); //型号 品牌 什么的判断无效
        Intent intent = new Intent("com.android.camera.action.CROP")
                .setDataAndType(Uri.fromFile(input), "image/*")
                .putExtra("crop", "true")
                .putExtra("circleCrop", "false")
                .putExtra("aspectX", isHuawei ? 0 : 1) // 华为手机 裁剪为原型 所以要进行处理 不传1就可以了
                .putExtra("aspectY", isHuawei ? 0 : 1)
                .putExtra("outputX", width)
                .putExtra("outputY", height)
                .putExtra("scale", true)
                .putExtra("scaleUpIfNeeded", true)
                .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output))
                .putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        activity.startActivityForResult(intent, reqCode);
    }

    /**
     * 检查是否安装了指定包名的apk
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isInstalledPkg(Context context, String packageName) {
        String result = "null";
        PackageManager pm = context.getPackageManager();
        try {
            result = (String) pm.getPackageInfo(packageName, 0).applicationInfo.loadLabel(pm);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if ("null".equals(result)) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否已开启GPS
     */
    public static boolean isGPSAvaiable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static String getSN(Context context) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            return get.invoke(c, "ro.serialno").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 得到用paint画的string的宽度
     */
    public static int getTextLength(String text, Paint paint) {
        try {
            int width = (int) Math.ceil(paint.measureText(text));
            return width;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 根据某个画笔得到字体高度
     */
    public static int getTextHeight(Paint paint) {
        try {
            Paint.FontMetrics fm = paint.getFontMetrics();
            int fontHeight = (int) Math.ceil((fm.descent - fm.top) + 1);
            return fontHeight;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 设置屏幕的背景透明度，常常用于popWindow时背景变暗
     *
     * @param bgAlpha 0.0-1.0
     */
    public static void setWindowAlpha(Activity activity, @FloatRange(from = 0, to = 1) float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 得到屏幕的背景透明度
     *
     * @param activity
     * @return
     */
    public static float getWindwoAlpha(Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        return lp.alpha;
    }

    /**
     * 跳转到指定网页
     *
     * @param context 上下文
     * @param webUrl  网址
     */
    public static void gotoWeb(Context context, String webUrl) {
        if (!webUrl.toLowerCase().contains("http")) {
            webUrl = "http://" + webUrl;
        }
        Uri uri = Uri.parse(webUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(intent);
    }

}
