package com.renrenliao.im.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.core.content.ContextCompat;

import com.renrenliao.im.provider.ClarityPotion;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * *@ClassName DeviceUtils
 * *@Description TODO
 * *@Author ganzhe
 * *@Date 2022/5/21 15:50
 **/
public class DeviceUtils {

    private static int versionCode;// 版本号
    private static String versionName;// 版本名字
    private static String mobileType; //手机类型
    private static String phoneManu;//手机型号厂商
    private static int sdk_vertioncode;//sdk版本号

    /**
     * 获取手机类型
     */
    public static String getMobileType(){
        if (StringUtils.isEmpty(mobileType)){
            return "android";
        }else {
            return mobileType;
        }
    }

    public static String getDeviceId(){
        StringBuilder sbDeviceId = new StringBuilder();
//        //获得设备默认IMEI（>=6.0 需要ReadPhoneState权限）
    //    String imei = getIMEI(context);
        //获得AndroidId（无需权限）
        String androidid = getAndroidId();
        //获得设备序列号（无需权限）
        String serial = getSERIAL();
        //获得硬件uuid（根据硬件相关属性，生成uuid）（无需权限）
        String uuid = getDeviceUUID().replace("-", "");
        //追加imei
//        if (imei != null && imei.length() > 0) {
//            sbDeviceId.append(imei);
//            sbDeviceId.append("|");
//        }
        //追加androidid
        if (androidid != null && androidid.length() > 0) {
            sbDeviceId.append(androidid);
            sbDeviceId.append("|");
        }
        //追加serial
        if (serial != null && serial.length() > 0) {
            sbDeviceId.append(serial);
            sbDeviceId.append("|");
        }
        //追加硬件uuid
        if (uuid != null && uuid.length() > 0) {
            sbDeviceId.append(uuid);
        }
        //生成SHA1，统一DeviceId长度
        if (sbDeviceId.length() > 0) {
            try {
                byte[] hash = DigestUtils.getHashByString(sbDeviceId.toString());
                String sha1 = DigestUtils.bytesToHexStr(hash);
                if (sha1 != null && sha1.length() > 0) {
                    //返回最终的DeviceId
                    return sha1;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //如果以上硬件标识数据均无法获得，
        //则DeviceId默认使用系统随机数，这样保证DeviceId不为空
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @return 当前版本的名称
     */
    public static String getVersionName() {
        if (StringUtils.isEmpty(versionName)) {
            try {
                PackageManager packageManager = ClarityPotion.healingSalve.getPackageManager();
                PackageInfo packageInfo = packageManager.getPackageInfo(
                        ClarityPotion.healingSalve.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                versionName = "";
            }
        }
        return versionName;
    }

    /**
     * [获取应用程序版本号信息]
     *
     * @return 当前版本的名称
     */
    public static int getVersionCode() {
        if (versionCode == 0) {
            try {
                PackageManager packageManager = ClarityPotion.healingSalve.getPackageManager();
                PackageInfo packageInfo = packageManager.getPackageInfo(
                        ClarityPotion.healingSalve.getPackageName(), 0);
                versionCode = packageInfo.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                versionCode = 0;
            }
        }
        return versionCode;
    }

    /**
     * 获得设备的AndroidId
     *
     * @param
     * @return 设备的AndroidId
     */
    private static String getAndroidId() {
        try {
            return Settings.Secure.getString(ClarityPotion.clarityPotion.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
    /**
     * 获得设备序列号（如：WTK7N16923005607）, 个别设备无法获取
     *
     * @return 设备序列号
     */
    private static String getSERIAL() {
        try {
            return Build.SERIAL;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
    /**
     * 获得设备硬件uuid
     * 使用硬件信息，计算出一个随机数
     *
     * @return 设备硬件uuid
     */
    private static String getDeviceUUID() {
        try {
            String dev = "3883756" +
                    Build.BOARD.length() % 10 +
                    Build.BRAND.length() % 10 +
                    Build.DEVICE.length() % 10 +
                    Build.HARDWARE.length() % 10 +
                    Build.ID.length() % 10 +
                    Build.MODEL.length() % 10 +
                    Build.PRODUCT.length() % 10 +
                    Build.SERIAL.length() % 10;
            return new UUID(dev.hashCode(),
                    Build.SERIAL.hashCode()).toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    /**
     * 返回手机型号厂商
     * @return
     */
    public static String getPhoneManu() {
        if(StringUtils.isEmpty(phoneManu)){
            String man = Build.MANUFACTURER;//手机品牌
            String mode = Build.MODEL;//手机型号
            String model = Build.MODEL;//系统版本
            phoneManu = man + mode + model;
        }
        return phoneManu;
    }

    /**
     * 获取当前的系统版本
     * @return
     */
    public static int getSdkVertion() {
        if (sdk_vertioncode == 0) {
            sdk_vertioncode = Build.VERSION.SDK_INT;
        }
        return sdk_vertioncode;
    }


    public static int getStatusBarHeight(Context context){
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    public static void setFullScreen(Activity activity,int colorStatusBar,boolean isDark){
        Window window = activity.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        int visibility;
        if (isDark){
            visibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE ;//| View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }else {
            visibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_VISIBLE;
        }
        window.getDecorView().setSystemUiVisibility(visibility);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(activity, colorStatusBar));

    }
    //屏幕px高度
    public static int getScreenH(Context context){
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }
    //屏幕px宽度
    public static int getScreenW(Context context){
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

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

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int  px2dip(Context context,int pxValue){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue/scale+0.5f);
    }


}
