package com.hw.nativeapp.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;


import androidx.core.app.ActivityCompat;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class DeviceUtils {

    public static Map<String, Object> deviceInfo(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        Map<String, Object> result= new HashMap<>();
        String imsi = mTm.getSubscriberId();
        String deviceid = mTm.getDeviceId();//获取智能设备唯一编号
        String te1 = mTm.getLine1Number();//获取本机号码
        String imei = mTm.getSimSerialNumber();//获得SIM卡的序号
        String mtype = android.os.Build.MODEL; // 手机型号
        String numer = mTm.getLine1Number(); // 手机号码，有的可得，有的不可得
        String mac = wifiInfo.getMacAddress();//MAC地址
        String mtyb= android.os.Build.BRAND;//手机品牌
        String phoneInfo = "Product: " + android.os.Build.PRODUCT;
        result.put("imsi",imsi);
        result.put("deviceid",deviceid);
        result.put("te1",te1);
        result.put("imei",imei);
        result.put("mtype",mtype);
        result.put("numer",numer);
        result.put("mac",mac);
        result.put("mtyb",mtyb);
        result.put("phoneInfo",phoneInfo);
        return result;
    }

//    public static Boolean hasDeviceId(){
//        String deviceId = MApplication.getCache().getString("deviceId");
//
//        if (StringUtils.isEmpty(deviceId)){
//            return false;
//        }else {
//            return true;
//        }
//    }

    /**
     * 获取设备唯一标识符
     *
     * @param context
     * @return
     */
//    public static String getDeviceId(Context context) {
//        //读取保存的在sd卡中的唯一标识符
////        String deviceId = readDeviceID(context);
//        String deviceId = MApplication.getCache().getString("deviceId");
//        //用于生成最终的唯一标识符
//        StringBuffer s = new StringBuffer();
//        //判断是否已经生成过,
//        if (deviceId != null && !"".equals(deviceId)) {
//            return deviceId;
//        }
//        try {
//            //获取IMES(也就是常说的DeviceId)
//            deviceId = getIMIEStatus(context);
//            s.append(deviceId);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        try {
//            //获取设备的MACAddress地址 去掉中间相隔的冒号
//            deviceId = getLocalMac(context).replace(":", "");
//            s.append(deviceId);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
////        }
//
//        //如果以上搜没有获取相应的则自己生成相应的UUID作为相应设备唯一标识符
//        if (s == null || s.length() <= 0) {
//            UUID uuid = UUID.randomUUID();
//            deviceId = uuid.toString().replace("-", "");
//            s.append(deviceId);
//        }
//        //为了统一格式对设备的唯一标识进行md5加密 最终生成32位字符串
//        String md5 = getMD5(s.toString(), false);
//        if (s.length() > 0) {
//            //持久化操作, 进行保存到SD卡中
////            saveDeviceID(md5, context);
//            MApplication.getCache().putString("deviceId",md5);
//        }
//        return md5;
//    }


    /**
     * 获取设备的DeviceId(IMES) 这里需要相应的权限<br/>
     * 需要 READ_PHONE_STATE 权限
     *
     * @param context
     * @return
     */
    private static String getIMIEStatus(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "";
        }
        String deviceId = tm.getDeviceId();
        return deviceId;
    }



    /**
     * 获取设备MAC 地址 由于 6.0 以后 WifiManager 得到的 MacAddress得到都是 相同的没有意义的内容
     * 所以采用以下方法获取Mac地址
     * @param context
     * @return
     */
    private static String getLocalMac(Context context) {
//        WifiManager wifi = (WifiManager) context
//                .getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = wifi.getConnectionInfo();
//        return info.getMacAddress();


        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "";
            }
            byte[] addr = networkInterface.getHardwareAddress();


            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "";
        }
        return macAddress;
    }


    /**
     * 对挺特定的 内容进行 md5 加密
     * @param message  加密明文
     * @param upperCase  加密以后的字符串是是大写还是小写  true 大写  false 小写
     * @return
     */
    public static String getMD5(String message, boolean upperCase) {
        String md5str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] input = message.getBytes();

            byte[] buff = md.digest(input);

            md5str = bytesToHex(buff, upperCase);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }

    public static String bytesToHex(byte[] bytes, boolean upperCase) {
        StringBuffer md5str = new StringBuffer();
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        if (upperCase) {
            return md5str.toString().toUpperCase();
        }
        return md5str.toString().toLowerCase();
    }
}
