using ryCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Windows.Forms;

namespace RyHardWare
{
    /// <summary>
    /// 
    /// </summary>
    public class HardWare
    {
        /// <summary>
        /// 获取WMI内容
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public string GetWMI(string sql)
        {
            System.Management.ManagementObjectSearcher mos =
               new System.Management.ManagementObjectSearcher(sql);
            System.Management.ManagementObjectCollection.ManagementObjectEnumerator moe = mos.Get().GetEnumerator();
            //注意
            //Properties["Manufacturer"].Value 可能为Null，意味着没有厂商信息
            var result = "";
            while (moe.MoveNext())
            {
                foreach (var item in moe.Current.Properties)
                {
                    if (item.Value != null)
                    {
                        if (item.Value is string[])
                        {
                            var list = (string[])item.Value;
                            for (int i = 0; i < list.Length; i++)
                            {
                                result += "\r\n" + item.Name + "=>数组" + i + "=>" + list[i];
                            }
                        }
                        else
                        {
                            result += "\r\n" + item.Name + "=>" + item.Value.ToString();
                        }
                    }
                }
                result += "\r\n";
            }
            return result.Trim();
        }
        /// <summary>
        /// 获取WMI内容
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetWMIByName(string name)
        {
            return GetWMI("select * from " + name);
        }
        /// <summary>
        /// 获取内存信息
        /// </summary>
        /// <returns></returns>
        public static string GetMemoryInfo()
        {
            var result = "";
            System.Management.ManagementObjectSearcher mos =
               new System.Management.ManagementObjectSearcher("select * from Win32_PhysicalMemory");
            System.Management.ManagementObjectCollection.ManagementObjectEnumerator moe = mos.Get().GetEnumerator();
            long total_size = 0;
            var index = 0;
            Dictionary<string, int> dict = new Dictionary<string, int>();
            while (moe.MoveNext())
            {
                index++;
                var item = moe.Current.Properties;
                long Capacity = item["Capacity"].Value.ToInt64() / 1024 / 1024 / 1024;
                total_size += Capacity;
                var Manufacturer = ObjToStr(item["Manufacturer"].Value);
                var Speed = item["Speed"].Value.ToInt();
                var ddr = ObjToStr(item["PartNumber"].Value);
                if (ddr.IndexOfEx("DDR3") >= 0) { ddr = "DDR3"; }
                else if (ddr.IndexOfEx("DDR4") >= 0) { ddr = "DDR4"; }
                else if (ddr.IndexOfEx("D4") >= 0) { ddr = "DDR4"; }
                else if (ddr.IndexOfEx("D3") >= 0) { ddr = "DDR3"; }
                else if (Speed == 266 || Speed == 333 || Speed == 400)
                {
                    ddr = "DDR";
                }
                else if (Speed == 533 || Speed == 667 || Speed == 800)
                {
                    ddr = "DDR2";
                }
                else if (Speed == 1066 || Speed == 1333 || Speed == 1600)
                {
                    ddr = "DDR3";
                }
                else if (Speed == 2400 || Speed == 2133 || Speed == 2666 || Speed == 2667 || Speed == 3200)
                {
                    ddr = "DDR4";
                }
                else { ddr = "未知"; }
                if (Manufacturer == "Kingston") { Manufacturer = "金士顿"; }
                else if (Manufacturer == "A-DATA Technology") { Manufacturer = "威刚"; }
                else { Manufacturer = GetManufacturer(Manufacturer); }
                var memory = Capacity + "GB " + Manufacturer + " " + ddr + " " + Speed + "MHz";
                if (dict.ContainsKey(memory))
                {
                    dict[memory]++;
                }
                else { dict[memory] = 1; }
            }
            foreach (var item in dict)
            {
                if (result.Length > 0) { result += "/"; }
                if (item.Value >= 2)
                {
                    result += item.Key + "*" + item.Value;
                }
                else { result += item.Key; }
            }
            if (index >= 2)
            {
                result = total_size + "GB(" + result + ")";
            }
            return result;
        }
        /// <summary>
        /// 获取显卡信息
        /// </summary>
        /// <returns></returns>
        public static string GetVideoInfo()
        {
            var result = "";
            System.Management.ManagementObjectSearcher mos =
               new System.Management.ManagementObjectSearcher("select * from Win32_VideoController");
            System.Management.ManagementObjectCollection.ManagementObjectEnumerator moe = mos.Get().GetEnumerator();
            while (moe.MoveNext())
            {
                var item = moe.Current.Properties;
                var Availability = ObjToStr(item["Availability"].Value);
                if (Availability != "3") { continue; }
                var Caption = ObjToStr(item["Caption"].Value);
                string RAM_Str;
                var RAM = ObjToStr(item["AdapterRAM"].Value).ToInt64()/1024/1024;
                if (RAM >= 1024) { RAM_Str = (RAM / 1024m).ToNString("0.00")+"GB"; }
                else { RAM_Str = RAM + "MB"; }
                if (result.Length > 0) { result += "/"; }
                result += Caption+ "("+ RAM_Str + ")";
            }
            return result;
        }
        /// <summary>
        /// 获取显卡信息
        /// </summary>
        /// <returns></returns>
        public static string GetDiskInfo()
        {
            var list = GetDiskListInfo();
            var result = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (result.Length > 0) { result += "/"; }
                result += list[i];
            }
            return result;
        }
        /// <summary>
        /// 获取显卡信息
        /// </summary>
        /// <returns></returns>
        public static List<string> GetDiskListInfo()
        {
            var result = new List<string>();
            System.Management.ManagementObjectSearcher mos =
               new System.Management.ManagementObjectSearcher("select * from Win32_DiskDrive");
            System.Management.ManagementObjectCollection.ManagementObjectEnumerator moe = mos.Get().GetEnumerator();
            while (moe.MoveNext())
            {
                var item = moe.Current.Properties;
                var size_long = ObjToStr(item["Size"].Value).ToInt64();
                var Size_1024 = size_long / 1024 / 1024 / 1024;
                var Size_1000 = size_long / 1000 / 1000 / 1000;
                string SizeStr;
                if(Size_1000>=1000)
                {
                    SizeStr = (Size_1000 / 1000) + "TB";
                }
                else
                {
                    SizeStr = Size_1000 + "GB";
                }
                if (Size_1024 >= 1024)
                {
                    SizeStr += "[实际"+(Size_1024 / 1024d).ToNString("0.00") + "TB]";
                }
                else
                {
                    SizeStr += "[实际" + Size_1024 + "GB]";
                }
                var Caption = ObjToStr(item["Caption"].Value);
                var MediaType = ObjToStr(item["MediaType"].Value);
                if (MediaType == "External hard disk media") { continue; }
                if (MediaType == "Removable Media") { continue; }
                if (Caption.StartsWith("TOSHIBA", StringComparison.OrdinalIgnoreCase))
                { result.Add(SizeStr + " 东芝 " + Caption); }
                else if (Caption.StartsWith("ST", StringComparison.OrdinalIgnoreCase))
                { result.Add(SizeStr + " 希捷 " + Caption); }
                else if (Caption.StartsWith("WD", StringComparison.OrdinalIgnoreCase))
                { result.Add(SizeStr + " 西数 " + Caption); }

                else
                {
                    var iPos = Caption.IndexOfEx(" ");
                    if(iPos<=0)
                    {
                        result.Add(SizeStr + " " + Caption);
                    }
                    else
                    {
                        result.Add(SizeStr + " " + GetManufacturer(Caption.Substring(0,iPos))+" "+Caption.Substring(iPos+1));
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 获取硬盘信息
        /// </summary>
        /// <returns></returns>
        public static string GetDiskMultiInfo()
        {
            var list = GetDiskListInfo();
            var result = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (result.Length > 0) { result += "\r\n"; }
                result += i == 0 ? "主硬盘:" : "硬盘" + (i + 1) + ":";
                result += list[i];
            }
            return result;
        }
        /// <summary>
        /// 获取主板信息
        /// </summary>
        /// <returns></returns>
        public static string GetBaseBoardInfo()
        {
            var result = "";
            System.Management.ManagementObjectSearcher mos =
               new System.Management.ManagementObjectSearcher("select * from WIN32_BaseBoard");
            System.Management.ManagementObjectCollection.ManagementObjectEnumerator moe = mos.Get().GetEnumerator();
            while (moe.MoveNext())
            {
                var item = moe.Current.Properties;
                var Manufacturer = ObjToStr(item["Manufacturer"].Value);
                var Product = ObjToStr(item["Product"].Value);
                if (result.Length > 0) { result += "/"; }
                result += "["+GetManufacturer(Manufacturer) + "]" + Product;
            }
            return result;
        }
        private static string GetManufacturer(string Manufacturer)
        {
            var ini_path = Application.StartupPath + "\\UserDb\\Manufacturer.ini";
            var name = "";
            if (System.IO.File.Exists(ini_path))
            {
                ryCommon.Ini ini = new ryCommon.Ini(ini_path);
                name= ini.ReadIni(Manufacturer, "name", Manufacturer);
            }
            if (name.Length == 0)
            {
                switch (Manufacturer)
                {
                    case "SOYO": return "梅捷";
                    case "BIOSTAR": case "BIOSTAR Group": return "映泰";
                    case "Gigabyte Technology Co., Ltd.": return "技嘉";
                    case "ASUSTeK COMPUTER INC.": return "华硕";
                    case "Micro-Star International Co., Ltd.": return "微星";
                    case "ONDA": return "昂达";
                    case "Shenzhen Jinge Information Co Ltd": return "亿储";
                    case "SUPoX COMPUTER CO.,LTD": return "磐正";
                    case "Samsung": return "三星";
                    case "ADATA": return "威刚";
                    case "SanDisk": return "闪迪";
                    case "Macmemory": return "王储";
                    case "KINGSTON": return "金士顿";
                    case "G Skill": return "芝奇";
                    case "GALAX": return "影驰";
                    case "Corsair": return "海盗船";
                    case "INTEL": return "英特尔";
                    case "Micron":return "镁光";
                    case "Hitachi":return "日立";
                }
            }
            if (name.Length == 0) { name = Manufacturer; }
            return name;
        }
        /// <summary>
        /// 获取处理器信息
        /// </summary>
        /// <returns></returns>
        public static string GetCPU()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher();   //用于查询一些如系统信息的管理对象
            searcher.Query = new SelectQuery("Win32_Processor ", "", new string[] { "Name" });//设置查询条件
            ManagementObjectCollection collection = searcher.Get();   //获取内存容量
            ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();

            string name = "";
            Dictionary<string, int> dict = new Dictionary<string, int>();
            while (em.MoveNext())
            {
                ManagementBaseObject baseObj = em.Current;
                if (baseObj.Properties["Name"].Value != null)
                {
                    try
                    {
                        name = baseObj.Properties["Name"].Value.ToString();
                        if (dict.ContainsKey(name))
                        {
                            dict[name]++;
                        }
                        else { dict[name] = 1; }
                    }
                    catch
                    {
                        return "";
                    }
                }
            }
            name = "";
            foreach (var item in dict)
            {
                if (name.Length > 0) { name += "/"; }
                if (item.Value >= 2)
                {
                    name += "("+item.Key + ")*" + item.Value;
                }
                else { name += item.Key; }
            }
            return name;
        }
        /// <summary>
        ///获取主要硬件信息
        /// </summary>
        /// <returns></returns>
        public static string GetMainHardware()
        {
            return GetMainHardware(false);
        }
        /// <summary>
        /// 获取主要硬件信息
        /// </summary>
        /// <param name="getbyXML">是否获取XML格式</param>
        /// <returns></returns>
        public static string GetMainHardware(bool getbyXML)
        {
            if (getbyXML)
            {
                ryCommon.Storage mStor = new Storage();
                addValue("主板", GetBaseBoardInfo());
                addValue("处理器", GetCPU());
                addValue("显卡", GetVideoInfo());
                addValue("内存", GetMemoryInfo());
                var list_disk = HardWare.GetDiskListInfo();
                for (int i = 0; i < list_disk.Count; i++)
                {
                    addValue((i == 0 ? "主硬盘 " : "硬盘"), list_disk[i]);
                }
                void addValue(string name, string value)
                {
                    mStor.AddNode2("name", name);
                    mStor.SetAttrValue("value", value);
                }
                return mStor.XMLText;
            }
            else
            {
                var content = "主板 " + HardWare.GetBaseBoardInfo();
                content += "\r\n处理器 " + HardWare.GetCPU();
                content += "\r\n显卡 " + HardWare.GetVideoInfo();
                content += "\r\n内存 " + HardWare.GetMemoryInfo();
                var list_disk = HardWare.GetDiskListInfo();
                for (int i = 0; i < list_disk.Count; i++)
                {
                    content += "\r\n" + (i == 0 ? "主硬盘 " : "硬盘" + " ") + list_disk[i];
                }
                return content;
            }
        }
        private static string ObjToStr(object obj)
        {
            if (obj == null) { return ""; }
            return obj.ToString();
        }
    }
}
