using System;
using System.Management;
using System.Security.Cryptography;
using System.Text;

namespace UIShare.Helpers
{
    public static class MachineCodeHelper
    {
        private static string UniqueCode = "2021E5B9BB0A54685B9445873F01D8F7";

        /// <summary>
        /// 校验机器码
        /// </summary>
        public static bool VerifyMachineCode(string MachineCode)
        {
            return UniqueCode == MachineCode;
        }

        /// <summary>
        /// 获取最终的设备唯一机器码
        /// </summary>
        public static string GetDeviceMachineCode()
        {
            string cpuId = GetCpuId();
            string boardId = GetMotherboardId();

            // 将主板和CPU序列号拼接，并转换为MD5，生成一个干净的、固定长度的机器码
            string rawCode = $"CPU:{cpuId}_BOARD:{boardId}";
            return GetMD5Hash(rawCode);
        }

        /// <summary>
        /// 获取 CPU 序列号
        /// </summary>
        private static string GetCpuId()
        {
            try
            {
                using (ManagementClass mc = new ManagementClass("win32_processor"))
                {
                    using (ManagementObjectCollection moc = mc.GetInstances())
                    {
                        foreach (ManagementObject mo in moc)
                        {
                            return mo.Properties["ProcessorId"].Value.ToString();
                        }
                    }
                }
            }
            catch
            {
                // 如果获取失败，返回一个默认标识
            }
            return "UNKNOWN_CPU";
        }

        /// <summary>
        /// 获取主板序列号 (最稳定的硬件标识)
        /// </summary>
        private static string GetMotherboardId()
        {
            try
            {
                using (ManagementClass mc = new ManagementClass("Win32_BaseBoard"))
                {
                    using (ManagementObjectCollection moc = mc.GetInstances())
                    {
                        foreach (ManagementObject mo in moc)
                        {
                            return mo.Properties["SerialNumber"].Value.ToString();
                        }
                    }
                }
            }
            catch
            {
            }
            return "UNKNOWN_BOARD";
        }

        /// <summary>
        /// 字符串 MD5 加密
        /// </summary>
        private static string GetMD5Hash(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // 将字节数组转换为16进制字符串
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }
    }
}