package aicare.net.cn.sdk.ailinksdkdemoandroid.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * APP和手机信息获取工具类
 */
public class AppPhoneInfoUtils {

    private AppPhoneInfoUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");

    }

    /**
     * 版本名--给用户看
     */
    public static String getVersionName(Context context) {
        PackageInfo mPackageInfo = getPackageInfo(context.getApplicationContext());
        if (mPackageInfo != null) {
            return mPackageInfo.versionName;
        }
        return "1.0.0";

    }

    /**
     * 版本号---主要用于程序升级检测
     */
    public static int getVersionCode(Context context) {
        PackageInfo mPackageInfo = getPackageInfo(context.getApplicationContext());
        if (mPackageInfo != null) {
            return mPackageInfo.versionCode;
        }
        return 1;
    }


    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }

    public static String getSystemVersion() {
        try {
            if (getPhoneBrand().toLowerCase().equalsIgnoreCase("xiaomi")) {
                return getMIUI();
            } else if (getPhoneBrand().toLowerCase().equalsIgnoreCase("huawei") || getPhoneBrand().toLowerCase().equals("honor")) {
                return getEMUI();
            } else if (getPhoneBrand().toLowerCase().equalsIgnoreCase("vivo")) {
                String[] vivo = getVivo();
                if (vivo != null && vivo.length > 1) {
                    return vivo[0] + "_" + vivo[1];
                }
                return "";
            } else if (getPhoneBrand().toLowerCase().equalsIgnoreCase("oppo")) {
                return getOppo();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "解析错误";
        }
        return "不是HMOV,没有做解析";
    }

    public static String getSystemVersionString() {
        try {
            if (getPhoneBrand().toLowerCase().equalsIgnoreCase("xiaomi")) {
                return getSystemProperty("ro.miui.ui.version.name");
            } else if (getPhoneBrand().toLowerCase().equalsIgnoreCase("huawei") || getPhoneBrand().toLowerCase().equals("honor")) {
                return getSystemProperty("ro.build.version.emui");
            } else if (getPhoneBrand().toLowerCase().equalsIgnoreCase("vivo")) {
                return getSystemProperty("ro.vivo.os.build.display.id");
            } else if (getPhoneBrand().toLowerCase().equalsIgnoreCase("oppo") || getPhoneBrand().toLowerCase().equals("realme")) {
                return getSystemProperty("ro.build.version.opporom");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "解析错误";
        }
        return "不是HMOV,没有做解析";
    }


    /**
     * 获取华为手机emui版本
     *
     * @return String
     */
    public static String getEMUI() {
        String systemProperty = "";
        try {
            systemProperty = getSystemProperty("ro.build.version.emui");
            //EmotionUI_11.1.0=harmonyOS2.0
            return systemProperty != null ? systemProperty.substring(systemProperty.indexOf("_") + 1).trim() : "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return systemProperty;
    }

    /**
     * 获取小米手机版本
     *
     * @return String
     */
    public static String getMIUI() {
        String systemProperty = "";
        try {
            systemProperty = getSystemProperty("ro.miui.ui.version.name");
            return systemProperty != null ? systemProperty.substring(systemProperty.indexOf("V") + 1).trim() : "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return systemProperty;
    }

    /**
     * 获取vivo手机版本
     *
     * @return String
     */
    public static String[] getVivo() {
        try {
            String systemProperty = getSystemProperty("ro.vivo.os.build.display.id");
            if (systemProperty != null) {
                if (!systemProperty.contains("_")) {
                    systemProperty = systemProperty.replace(" ", "_");
                }
                return systemProperty.split("_");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //OriginOS 1.0
        //Funtouch OS
        return null;
    }

    public static String getOppo() {
        //ro.build.version.opporom
        String systemProperty = "";
        try {
            systemProperty = getSystemProperty("ro.build.version.opporom");
            return systemProperty != null ? systemProperty.substring(systemProperty.indexOf("V") + 1).trim() : "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return systemProperty;
    }


    public static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }

    public static String getPhoneInfo() {
        return Build.MANUFACTURER +//手机厂商
                " " + Build.MODEL; //手机型号
    }


    public static String getBrand() {
        return Build.BRAND;
    }

    public static String getPhoneBrand() {
        return Build.MANUFACTURER;//手机厂商
    }

    /**
     * 返回手机型号
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }


    /**
     * 返回手机系统版本
     */
    public static String getPhoneVersion() {
        return "android " + Build.VERSION.RELEASE;//系统版本;
    }


    /**
     * 读取手机电话号码
     *
     * @param context context
     * @return 手机号, 空代表读取失败
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getPhoneNumber(Context context) {
        String phoneNumber = "";
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            phoneNumber = telephonyManager.getLine1Number();
            if (phoneNumber.startsWith("+86")) {
                phoneNumber = phoneNumber.substring(3);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return phoneNumber;
        }
        return phoneNumber;
    }


    /**
     * 检测应用是否安装
     *
     * @param context     Context
     * @param packagename 包名
     * @return boolean
     */
    public static boolean checkMapAppsIsExist(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }


    /**
     * 安装apk
     */
    public static void install(Context mContext, Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(install);
    }


    /**
     * 获取进程名
     *
     * @param context 上下文
     * @return 进程名
     */
    public static String getProcessName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                if (proInfo.processName != null) {
                    return proInfo.processName;
                }
            }
        }
        return null;
    }


    /**
     * 用来判断服务是否运行.
     *
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;
        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(2000);
            if (!(serviceList.size() > 0)) {
                return false;
            }
            for (int i = 0; i < serviceList.size(); i++) {
                if (serviceList.get(i).service.getClassName().equals(className)) {
                    isRunning = true;
                    break;
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return isRunning;
    }


    public static  int getSystemBattery(Context context) {
        int level = 0;
        Intent batteryInfoIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        level = batteryInfoIntent.getIntExtra("level", 0);
        int batterySum = batteryInfoIntent.getIntExtra("scale", 100);
        int percentBattery = 100 * level / batterySum;
        return percentBattery;
    }


}
