using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MeterVision.Util
{
    //注册管理类
    public class LicenseMana
    {
        public static LicenseModel mLicenseModel { get; set; }

        private static string _machineCode = "";
        //private const string LICENSE_FILE_PATH = "license.dat";
        private static string LICENSE_FILE_PATH = AppDomain.CurrentDomain.BaseDirectory + "\\license.dat";

        // 保存 licenseKey 到文件，如果文件已存在则覆盖
        public static void SaveLicenseKey(string licenseKey)
        {
            try
            {
                // 使用 File.WriteAllText 确保每次写入时覆盖现有内容
                File.WriteAllText(LICENSE_FILE_PATH, licenseKey);
                Console.WriteLine("许可证已成功保存。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存许可证时出错: {ex.Message}");
            }
        }

        // 加载注册信息
        public static bool IsLicensed()
        {
            if (File.Exists(LICENSE_FILE_PATH))
            {
                try
                {
                    // 读取加密的注册信息
                    string licenseKey = File.ReadAllText(LICENSE_FILE_PATH);

                    // 解密注册信息
                    //string jsonData = Decrypt(encryptedData);

                    //// 反序列化 JSON 数据
                    //return JsonConvert.DeserializeObject<LicenseData>(jsonData);
                    //mLicenseModel = ValidateLicense(licenseKey);

                    return ValidateLicense(licenseKey);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"加载注册信息时出错: {ex.Message}");
                }
            }

            return false;
        }

        public static bool ValidateLicense(string enLicenseKey)
        {
            mLicenseModel = null;
            //先解密
            string decLicenseKey = AesEncryptionHelper.DecryptString(enLicenseKey, AesEncryptionHelper.key);

            string publicKey = GetPublicKeyFromResource();
            if(publicKey == null)
            {
                //throw new Exception("软件无法使用，请联系开发者！");
                return false;
            }
            
            // 分割注册码为签名和许可证数据
            //string[] parts = licenseKey.Split("::");
            string[] parts = decLicenseKey.Split(new string[] { "::" }, StringSplitOptions.None);
            if (parts.Length != 2)
            {
                Console.WriteLine("无效的注册码格式");
                return false;
                //throw new Exception("无效的注册码！");
            }

            string signatureBase64 = parts[0];
            string jsonData = parts[1];

            // 解析许可证数据
            var licenseData = JsonConvert.DeserializeObject<dynamic>(jsonData);
            string machineCode = licenseData.MachineCode;
            string expirationDateStr = licenseData.ExpirationDate;

            // 检查硬件码是否匹配
            string currentMachineCode = GetMachineCode();

            if (machineCode != currentMachineCode)
            {
                Console.WriteLine("激活码不匹配");
                return false;
            }

            // 检查有效期
            DateTime expirationDate = DateTime.Parse(expirationDateStr);
            if (DateTime.Now > expirationDate)
            {
                Console.WriteLine("注册码已过期");
                return false;
            }

            //LicenseData licenseData = new LicenseData();
            // 验证签名
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(publicKey);

                // 将签名从 Base64 字符串转换为字节数组
                byte[] signature = Convert.FromBase64String(signatureBase64);

                // 对许可证数据进行哈希
                byte[] dataToVerify = Encoding.UTF8.GetBytes(jsonData);

                // 验证签名
                bool isValid = rsa.VerifyData(dataToVerify, CryptoConfig.MapNameToOID("SHA256"), signature);
                if (!isValid)
                {
                    Console.WriteLine("无效的签名");
                    return false;
                }

                Console.WriteLine("注册码验证成功");
                //return true;
                mLicenseModel = new LicenseModel
                {
                    MachineCode = machineCode,
                    ExpirationDate = expirationDate,
                    IsPermanent = expirationDateStr.Substring(0, 4).Equals("9999"),
                    LicenseKey = enLicenseKey
                };

                return true;
            }
        }

        public static string GetPublicKeyFromResource()
        {
            // 获取当前程序集
            Assembly assembly = Assembly.GetExecutingAssembly();

            // 列出所有嵌入的资源名称
            foreach (string resourceName1 in assembly.GetManifestResourceNames())
            {
                Console.WriteLine(resourceName1);
            }

            // 获取资源名称
            string resourceName = "MeterVision.public_key.xml"; // 注意命名空间和文件名

            // 读取嵌入的资源文件
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                {
                    return null;
                }
                //throw new FileNotFoundException("无法找到私钥资源文件");

                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }


        public static string GetMachineCode()
        {
            if (!string.IsNullOrWhiteSpace(_machineCode))
            {
                return _machineCode;
            }
            // 获取硬件信息
            //string hddSerial = GetHDDSerial();
            string cpuId = GetCPUId();
            //string macAddress = GetMACAddress();

            // 组合硬件信息并生成哈希
            using (SHA256 sha256 = SHA256.Create())
            {
                //byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(hddSerial + cpuId + macAddress));
                byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(cpuId));

                _machineCode = Convert.ToBase64String(hashBytes);
                return _machineCode;
            }
        }

        private static string GetCPUId()
        {
            try
            {
                // 查询CPU的ProcessorId
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
                {
                    foreach (ManagementObject cpu in searcher.Get())
                    {
                        if (cpu["ProcessorId"] != null)
                        {
                            return cpu["ProcessorId"].ToString().Trim();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取CPU ID时出错: " + ex.Message);
            }

            //return "无法获取CPU ID";
            return "CPU_ID_ABCDEF";
        }

        //------------------------------------------------------------------
    }


    // 许可证数据类
    public class LicenseModel
    {
        public string MachineCode { get; set; }
        public DateTime ExpirationDate { get; set; }
        public bool IsPermanent { get; set; }
        public string LicenseKey { get; set; }
    }
}
