using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SLZ_4
{
    public partial class ConfigDevice : Form
    {
        //UDP广播获取仪器IP地址
        private static byte[] data;
        static string UDPRecvData;
        public bool SocketConn = true;
        public ConfigDevice()
        {
            InitializeComponent();

            getlocalIP();
        }

        public string strlocalIp;
        public string getlocalIP()
        {
            IPAddress localIp = null;
            IPAddress[] ipArray;
            ipArray = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (var item in ipArray)
            {
                if (IpAddressInRange(item.ToString(), "192.168.1.0", "192.168.1.255"))
                {
                    strlocalIp = item.ToString();
                }
            }
            localIp = ipArray.First(ip => ip.AddressFamily == AddressFamily.InterNetwork);

            localIP.Text = strlocalIp;
            return strlocalIp;
        }
        /// <summary>
        /// 判断IP地址在不在某个IP地址段
        /// </summary>
        /// <param name="input">需要判断的IP地址</param>
        /// <param name="begin">起始地址</param>
        /// <param name="ends">结束地址</param>
        /// <returns></returns>
        public static bool IpAddressInRange(string input, string begin, string ends)
        {
            uint current = IPToID(input);
            return current >= IPToID(begin) && current <= IPToID(ends);
        }
        private static uint IPToID(string addr)
        {
            if (!IPAddress.TryParse(addr, out var ip))
            {
                return 0;
            }
            byte[] bInt = ip.GetAddressBytes();
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bInt);
            }
            return BitConverter.ToUInt32(bInt, 0);
        }

        private static int BROADCAST_PORT = 9999;
        static List<IPAddress> GetActiveNICsIP()
        {
            List<IPAddress> ips = new List<IPAddress>();
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up &&
                    !nic.Description.Contains("Loopback"))
                {
                    foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ips.Add(ip.Address);
                        }
                    }
                }
            }
            return ips;
        }

        // 为每个网卡创建独立接收线程
       // private static List<Thread> receiveThreads = new List<Thread>();
        static void SendBroadcast(IPAddress localIP, byte[] data)
        {
            using (Socket sender = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp))
            {
                //发送数据
                try
                {
                    sender.SetSocketOption(SocketOptionLevel.Socket,
                        SocketOptionName.Broadcast, 1);
                    sender.Bind(new IPEndPoint(localIP, 0));
                    IPEndPoint broadcastEP = new IPEndPoint(IPAddress.Broadcast, BROADCAST_PORT);

                    sender.SendTo(data, broadcastEP);
                    Console.WriteLine($"已通过 {localIP} 发送广播");
                    //FormMain.form.wa.InsertWarningData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "-", "发送广播");
                }

                catch (Exception ex)
                {
                    Console.WriteLine($"{localIP} 发送失败: {ex.Message}");
                    FormMain.form.wa.InsertWarningData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "-", "发送失败:" + ex.Message);
                }

                //接受数据
                byte[] buffer = new byte[1024];
                sender.ReceiveTimeout = 2000;
                while (true)
                {
                    try
                    {
                        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                        int bytesRead = sender.ReceiveFrom(buffer, ref remoteEP);
                        string message = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        Console.WriteLine($"[{localIP}] 接收到来自 {remoteEP}: {message}");

                        UDPRecvData += message;
                        UDPRecvData += "\n";
                    }
                    catch (SocketException) 
                    { 
                        break;/* 超时处理 */ 
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[{localIP}] 接收错误: {ex.Message}");
                        FormMain.form.wa.InsertWarningData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "-", "接收错误" + ex.Message);
                    }
                }
            }

        }
        /// <summary>
        /// UDP广播获取仪器IP地址
        /// </summary>
        public void UDPBroadcast()
        {
            try
            {
                UDPRecvData = "";           
                // 获取所有可用网卡IP
                List<IPAddress> localIPs = GetActiveNICsIP();
                if (localIPs.Count == 0)
                {
                    Console.WriteLine("No active network interfaces found");
                    FormMain.form.wa.InsertWarningData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "-", "没有网络");
                }
                data = Encoding.ASCII.GetBytes("hello,udp server");

                // 发送广播
                foreach (IPAddress localIP in localIPs)
                {
                    Thread t = new Thread(() => SendBroadcast(localIP, data));
                    t.IsBackground = true;
                    t.Start();
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("UDP广播:" + ex.Message);
                FormMain.form.wa.InsertWarningData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "-", "UDP广播:" + ex.Message);
            }

            //创建定时器
            System.Timers.Timer timer = new System.Timers.Timer(3000);
            timer.Elapsed += (sender, e) => { UDP_Parse(); };
            timer.AutoReset = false;
            timer.Start();
        }
        public void UDP_Parse()
        {
            try
            {
                if (UDPRecvData.Length > 2)
                {
                    UDPRecvData = UDPRecvData.Substring(0, UDPRecvData.Length - 1);
                }
                if (!String.IsNullOrEmpty(UDPRecvData))
                {
                    FormMain.form.arrDevParam[0].iSwitch = 0;
                    FormMain.form.arrDevParam[1].iSwitch = 0;

                    string[] IPData = UDPRecvData.Split('\n');
                    IPData = IPData.Distinct().ToArray();   //去掉重复
                    int ip_num = IPData.Length;
                    if (ip_num > 0)
                    {
                        for (int i = 0; i < ip_num; i++)
                        {
                            string[] ipaddress = IPData[i].Split(':');
                            int ch_station = Convert.ToInt32(ipaddress[0]);

                            switch (ch_station)
                            {
                                case 1:
                                    if (ipaddress[1] != FormMain.form.arrDevParam[0].sDevAddr)
                                    {
                                        FormMain.form.arrDevParam[0].sDevAddr = ipaddress[1];
                                        FormMain.form.arrDevParam[0].iSlaveId = ch_station;

                                        FormMain.form.deleteDevObj(0);
                                        FormMain.form.arrDevParam[0].iSwitch = 1;
                                    }                                    
                                    break;
                                case 2:
                                    if (ipaddress[1] != FormMain.form.arrDevParam[1].sDevAddr)
                                    {
                                        FormMain.form.arrDevParam[1].sDevAddr = ipaddress[1];
                                        FormMain.form.arrDevParam[1].iSlaveId = ch_station;

                                        FormMain.form.deleteDevObj(1);
                                        FormMain.form.arrDevParam[1].iSwitch = 1;
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("UDP:" + ex.Message);
                FormMain.form.wa.InsertWarningData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "-", "UDP:" + ex.Message);
            }

            bool bSwitch = false;

            //删除设备
            for (int i = 0; i < 2; i++)
            {
                if (FormMain.form.arrDevParam[i].iSwitch == 1)
                {
                    FormMain.form.deleteDevObj(i);
                    bSwitch = true;
                }
            }
            if (bSwitch)
            {
                Thread.Sleep(200);

                //添加设备
                for (int i = 0; i < 2; i++)
                {
                    if (FormMain.form.arrDevParam[i].iSwitch == 1)
                    {
                        Config.saveDevParam(i);
                        FormMain.form.addDevObj(i);
                    }
                }
            }
            if (FormMain.form.cfgDevForm.Visible)
            {
                Invoke((MethodInvoker)delegate
                {
                    showDevInfo();
                });
            }
        }

        public void showDevInfo()
        {
            if (FormMain.form.arrDevObj[0] != null)
            {
                commStatus1.Text = FormMain.form.arrDevObj[0].bStatus  ? "已连接" : "未连接";
                commStatus1.BackColor = FormMain.form.arrDevObj[0].bStatus ? Color.Green : Color.Red;
                labelVersion1.Text = FormMain.form.arrDevObj[0].versionInfo.sSoftWareVersion;
            }
            else
            {
                commStatus1.Text = "";
                commStatus1.BackColor = Color.Transparent;
            }
            ch1IP.Text = FormMain.form.arrDevParam[0].sDevAddr;

            if (FormMain.form.arrDevObj[1] != null)
            {
                commStatus2.Text = FormMain.form.arrDevObj[1].bStatus  ? "已连接" : "未连接";
                commStatus2.BackColor = FormMain.form.arrDevObj[1].bStatus ? Color.Green : Color.Red;
                labelVersion2.Text = FormMain.form.arrDevObj[1].versionInfo.sSoftWareVersion;
            }
            else
            {
                commStatus2.Text = "";
                commStatus2.BackColor = Color.Transparent;
            }
            ch2IP.Text = FormMain.form.arrDevParam[1].sDevAddr;

            buttonSearch.Enabled = true;
        }
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            buttonSearch.Enabled = false;
            UDPBroadcast();
        }
    }
}
