using FlyTcpFramework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace WaferAlignment
{
    class TCP
    {
        // 用于通讯的本地连接的IP地址
        private string ipServer = "192.168.2.200";

        // 定义IP服务器
        private TcpSvr m_Svc;

        // 允许连接的客户端IP地址列表
        private List<string> allowedClientIps = new List<string> { "192.168.2.100" };

        // 接收数据事件的委托
        public event EventHandler<DataReceivedEventArgs> DataReceived;

        // 用于存储客户端的字典
        private Dictionary<string, TcpClientState> clientDictionary = new Dictionary<string, TcpClientState>();

        // 启动服务器
        public void StartServer()
        {
            try
            {
                ushort _port = 3000;
                m_Svc = new TcpSvr(IPAddress.Parse(ipServer), _port, 10, new Coder(Coder.EncodingMothord.Default), AppDomain.CurrentDomain.BaseDirectory);

                // 订阅事件
                m_Svc.RecvData += new NetEvent(RecvData);
                m_Svc.ClientConn += new NetEvent(ClientConnect);
                m_Svc.ClientClose += new NetEvent(ClientClosed);

                // 启动服务器
                m_Svc.Start();

                if (m_Svc.IsRun)
                {
                    Console.WriteLine("Server已上线");
                }
                else
                {
                    Console.WriteLine("Server未能上线");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("启动服务器失败！" + ex);
            }
        }

        // 停止服务器
        public void StopServer()
        {
            try
            {
                if (m_Svc != null)
                {
                    // 取消订阅事件
                    m_Svc.RecvData -= RecvData;
                    m_Svc.ClientConn -= ClientConnect;
                    m_Svc.ClientClose -= ClientClosed;

                    // 停止服务器
                    m_Svc.Stop();
                    m_Svc = null;

                    Console.WriteLine("Server已下线");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("停止服务器失败！" + ex);
            }
        }

        // 服务器接收数据TCPIP
        private void RecvData(object sender, NetEventArgs e)
        {
            try
            {
                //string info = Encoding.ASCII.GetString(e.Client.Datagram); // 解码为 ASCII 字符串
                string info = e.Client.Datagram;    // 收到的数据
                string ip = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
                // 触发处理收到的数据
                OnDataReceived(new DataReceivedEventArgs(ip, info));
            }
            catch (Exception ex)
            {
                throw new Exception("接收数据失败！" + ex.Message);
            }
        }
        // 触发数据接收事件
        protected virtual void OnDataReceived(DataReceivedEventArgs e)
        {
            // 将空条件运算符改为传统的 null 检查
            EventHandler<DataReceivedEventArgs> handler = DataReceived;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        // 发送数据到指定客户端
        public void SendData(string clientIp, string data)
        {
            TcpClientState clientState;
            if (clientDictionary.TryGetValue(clientIp, out clientState))
            {
                byte[] dataBytes = Encoding.Default.GetBytes(data);
                clientState.ClientSocket.Send(dataBytes);
                Console.WriteLine("向客户端 {0} 发送数据: {1}", clientIp, data);
            }
            else
            {
                throw new Exception("客户端未连接");
            }
        }
        //// 触发数据接收事件
        //protected virtual void OnDataReceived(DataReceivedEventArgs e)
        //{
        //    DataReceived?.Invoke(this, e);
        //}

        //// 发送数据到指定客户端
        //public void SendData(string clientIp, string data)
        //{
        //    if (clientDictionary.TryGetValue(clientIp, out TcpClientState clientState))
        //    {
        //        byte[] dataBytes = Encoding.Default.GetBytes(data);
        //        clientState.ClientSocket.Send(dataBytes);
        //        Console.WriteLine($"向客户端 {clientIp} 发送数据: {data}");
        //    }
        //    else
        //    {
        //        throw new Exception("客户端未连接");
        //    }
        //}
        
        // 客户端是否链接判断
        private void ClientConnect(object sender, NetEventArgs e)
        {
            try
            {
                string ip = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();

                // 检查客户端IP是否在允许列表中
                if (allowedClientIps.Contains(ip))
                {
                    TcpClientState clientState = new TcpClientState(e.Client.ClientSocket, ip);
                    clientDictionary[ip] = clientState;
                    //Console.WriteLine($"客户端 {ip} 已连接");
                }
                else
                {
                    // 拒绝不在允许列表中的客户端连接
                    //Console.WriteLine($"拒绝客户端 {ip} 的连接");
                    e.Client.ClientSocket.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("TCP连接失败！" + ex);
            }
        }

        // 客户端链接断开判断
        private void ClientClosed(object sender, NetEventArgs e)
        {
            try
            {
                string ip = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
                if (clientDictionary.ContainsKey(ip))
                {
                    clientDictionary.Remove(ip);
                    //Console.WriteLine($"客户端 {ip} 已断开");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("通信断开失败！" + ex);
            }
        }

        ///// <summary>
        ///// 客户端是否链接判断
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //void ClientConnect(object sender, NetEventArgs e)
        //{
        //    try
        //    {
        //        ip = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
        //        if (ip == ip1)
        //        {
        //            //lb_ClientOnlineStatus.Text = "客户端已连接";
        //            //lb_ClientOnlineStatus.BackColor = Color.GreenYellow;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("TCP连接失败！"+ ex.Message);

        //    }

        //}

        ///// <summary>
        ///// 客户端链接断开判断
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //void ClientClosed(object sender, NetEventArgs e)
        //{
        //    try
        //    {
        //        ip = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
        //        if (ip == ip1)
        //        {
        //            //lb_ClientOnlineStatus.Text = "客户端已断开";
        //            //lb_ClientOnlineStatus.BackColor = Color.Yellow;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("通信断开失败！"+ ex.Message);

        //    }

        //}

    }

    public class DataReceivedEventArgs : EventArgs
    {
        public string ClientIp { get;  private set;}
        public string Data { get; private set; }

        public DataReceivedEventArgs(string clientIp, string data)
        {
            ClientIp = clientIp;
            Data = data;
        }
    }

    public class TcpClientState
    {
        /// <summary>
        /// 客户端的套接字
        /// </summary>
        public Socket ClientSocket { get; private set; }

        /// <summary>
        /// 客户端的IP地址
        /// </summary>
        public string ClientIp { get; private set; }

        /// <summary>
        /// 客户端连接的时间
        /// </summary>
        public DateTime ConnectionTime { get; private set; }

        /// <summary>
        /// 客户端的唯一标识符
        /// </summary>
        public string ClientId { get; private set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="clientSocket">客户端的套接字</param>
        /// <param name="clientIp">客户端的IP地址</param>
        public TcpClientState(Socket clientSocket, string clientIp)
        {
            ClientSocket = clientSocket;
            ClientIp = clientIp;
            ConnectionTime = DateTime.Now;
            ClientId = Guid.NewGuid().ToString();
        }
    }
}
