package com.xhly.corelib.utils;

import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

/**
 * 作者：NB的LittleWhite
 * <p>
 * 邮箱：zhan_0313@163.com
 */
public class SystemUtil {


    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        String version = "";
        if (isHarmonyOs()) {
            version = "Harmony    " + getHarmonyVersion();
        } else {
            version = "Android    " + Build.VERSION.RELEASE;
        }
        return version;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }


    /**
     * 获取手机版本号
     *
     * @return 手机型号
     */
    public static String getSystemDisplay() {
        return Build.DISPLAY;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }


    /**
     * 是否为鸿蒙系统
     *
     * @return true为鸿蒙系统
     */
    public static boolean isHarmonyOs() {
        try {
            Class<?> buildExClass = Class.forName("com.huawei.system.BuildEx");
            Object osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass);
            return "Harmony".equalsIgnoreCase(osBrand.toString());
        } catch (Throwable x) {
            return false;
        }
    }

    /**
     * 获取鸿蒙系统版本号
     *
     * @return 版本号
     */
    public static String getHarmonyVersion() {
        return getProp("hw_sc.build.platform.version", "");
    }

    private static String getProp(String property, String defaultValue) {
        try {
            Class spClz = Class.forName("android.os.SystemProperties");
            Method method = spClz.getDeclaredMethod("get", String.class);
            String value = (String) method.invoke(spClz, property);
            if (TextUtils.isEmpty(value)) {
                return defaultValue;
            }
            return value;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return defaultValue;
    }

    public static String getCpuName() {
        String[] abis = Build.SUPPORTED_ABIS;
        StringBuilder abiStr = new StringBuilder();
        for (String abi : abis) {
            abiStr.append(abi);
            abiStr.append(',');
        }
        return abis[0];
    }


    /**
     * 是否存在su命令，并且有执行权限 判断是否root
     *
     * @return 存在su命令，并且有执行权限返回true
     */
    public static boolean isSuEnable() {
        File file = null;
        String[] paths = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/", "/su/bin/"};
        try {
            for (String path : paths) {
                file = new File(path + "su");
                if (file.exists() && file.canExecute()) {
                    return true;
                }
            }
        } catch (Exception x) {
            x.printStackTrace();
        }
        return false;
    }

    /**
     * 获得系统内核版本
     *
     * @return
     */

    public static String getKernelVersion() {
        String kernelVersion = "";
        try {
            kernelVersion = System.getProperty("os.version");
        } catch (Exception e) {

        }
        return kernelVersion;
    }

    public static String getAppVersionName(Context context, String pkg) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_META_DATA);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {

        }
        return "";
    }

    public static Long getAppVersionCode(Context context, String pkg) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_META_DATA);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                return packageInfo.getLongVersionCode();
            }else {
                return (long) packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {

        }
        return 0L;
    }

    public static String getICCID(Context context) {
        String iccid = "";
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                SubscriptionManager sm = SubscriptionManager.from(context);
                List<SubscriptionInfo> sis = sm.getActiveSubscriptionInfoList();
                if (sis.size() >= 1) {
                    SubscriptionInfo si1 = sis.get(0);
                    String iccId1 = si1.getIccId();
                    String phoneNum1 = si1.getNumber();
                    iccid = iccId1;
                    LogUtils.d("获得手机信息", "问题是mei偶222尔与哦是的" + phoneNum1);
                }
                if (sis.size() >= 2) {
                    SubscriptionInfo si2 = sis.get(1);
                    String iccId2 = si2.getIccId();
                    String phoneNum2 = si2.getNumber();
                    iccid = iccId2;
                    LogUtils.d("获得手机信息", "问题是mei偶尔与哦是的" + si2.toString());
                }
                // 获取SIM卡数量相关信息：
                int count = sm.getActiveSubscriptionInfoCount();//当前实际插卡数量
                int max = sm.getActiveSubscriptionInfoCountMax();//当前卡槽数量
            }
        } catch (Exception e) {
            LogUtils.d("获得手机信息", "问题是" + e.toString());
        }
        return iccid;
    }

    public static String getWifiMac(Context context) {
        String wifiMac = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo connectionInfo = wifiManager.getConnectionInfo();
            wifiMac = connectionInfo.getMacAddress();
        } catch (Exception e) {
            LogUtils.d("获得手机信息", "wifi问题是" + e.toString());
        }
        return wifiMac;
    }

    public static String getBluetoothMac() {
        String bMac = "";
        try {
            BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
          /* if (defaultAdapter.isEnabled()){
               bMac= defaultAdapter.getAddress();
           }*/
            bMac = defaultAdapter.getAddress();
        } catch (Exception e) {
            LogUtils.d("获得手机信息", "bluetooth问题是" + e.toString());
        }
        return bMac;
    }

    public static Location getLocation(Context context) {
        Location data = null;
        try {
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                  String bestProvider = "";
            List<String> providers = locationManager.getProviders(true);
            boolean flag=false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                flag=( ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        &&ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_BACKGROUND_LOCATION)== PackageManager.PERMISSION_GRANTED);
            }else {
                flag=( ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
            }
            if (flag) {
                for (String provider : providers) {
                    Location lastKnownLocation =locationManager.getLastKnownLocation(provider);
                    if (lastKnownLocation==null){
                        continue;
                    }
                    if (data==null||lastKnownLocation.getAccuracy()<data.getAccuracy()){
                        data=lastKnownLocation;
                    }
                }
                if (data!=null){
                    LogUtils.d("获得地理位置", "lat="+data.getLatitude()+",lon="+data.getLongitude() );
                }else {
                    LogUtils.d("获得地理位置", "没有位置");
                }
                return data;
            }
        } catch (Exception e) {
            LogUtils.d("获得地理位置", "失败原因" + e.toString());
        }
        return data;
    }

    // 获取定位信息


    // 检查屏幕是否允许旋转
    public static boolean isRotationAllowed(Context context) {
        try{
            int rotationSetting = Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
            return rotationSetting == 1;
        }catch (Exception e){
            return true;
        }
    }

    public static boolean isSDCardMounted(Context context) {
        try{
            File[] externalFilesDirs = context.getExternalFilesDirs(null);
            return externalFilesDirs.length > 1;
        }catch (Exception e){
            return false;
        }
    }

    public static String getProcessName(Context cxt, int pid) {
        //获取ActivityManager对象
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        //在运行的进程的
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

}
