using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Data;
using DBFactory;
namespace CommonLibrary
{
    public static  class CConnectTCPIP
    {
        static bool _exitThread = false;
        static string _tcpServerError;
        static int[] _plcValues;

        public static int[] PlcValues
        {
            get { return CConnectTCPIP._plcValues; }
            set { CConnectTCPIP._plcValues = value; }
        }
        /// <summary>
        /// 监听接收AGV发送的数据时发生的故障
        /// </summary>
        public static string TcpServerError
        {
            get { return CConnectTCPIP._tcpServerError; }
            set { CConnectTCPIP._tcpServerError = value; }
        }
        static string _receiveOK=null;
        /// <summary>
        /// 监听到该AGV车的所有队列完成
        /// </summary>
        public static string ReceiveOK
        {
            get { return CConnectTCPIP._receiveOK; }
            set { CConnectTCPIP._receiveOK = value; }
        }
        static Thread mythread;
        static Socket Localsocket;
        
        static bool ConnectedServer = false;
        static byte[] _GetData = new byte[6];
        
        static CGetState agvstate = new CGetState();
        static DBOperator dbo = new DBOperator();
        static DBOperator dboM = new DBOperator("ManConnString", "ManDBFactory");
        /// <summary>
        /// 开始监听接收到的数据
        /// </summary>
        private static void BeginListen()
        {
            while (true)
            {
                if (_exitThread == true)
                {
                    mythread.Abort();
                    return;
                }
                try
                {

                    if (ConnectedServer == false)
                    {
                        if (ConnectTcpIPServer() == false) continue;
                    }

                    Localsocket.Listen(1);
                    try
                    {

                        SocketsTCPIP.CClientTCPIP.ClientSocket.Receive(_GetData);
                        if (_GetData[0] == 0) continue;
                        CommonClassLib.CCarryConvert.WriteDarkCasket("ReceiveAGV", "SocketsTCPIP.CConnectTCPIP", "Receive", "1000", _GetData);
                    }
                    catch
                    {
                        continue;
                    }

                    //处理接收到数据
                    if (_GetData != null)
                    {

                        if ((_GetData[0] == 70))
                        {
                            ////管理任务与AGV车号绑定
                            //int AgvNo, taskindex, MonitorIndex, taskkind;
                            //MonitorIndex = Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]);
                            //AgvNo = Convert.ToInt32(_GetData[5] * Math.Pow(2, 8) + _GetData[4]);
                            //taskindex = ccf.GetAgvTaskIndex(MonitorIndex);
                            //taskkind = ccf.GetManageTaskKindIndex(MonitorIndex);
                            //dbo.ExceSQL("update t_base_monitor_task set f_agvno=" + AgvNo + " where f_managetaskindex=" + taskindex + " and f_managetaskkindindex=" + taskkind);
                            //dbo.ExceSQL("update t_base_monitor_task set f_deviceindex =" + AgvNo + "  where f_managetaskindex=" + taskindex + " and f_deviceindex<=12  and f_managetaskkindindex=" + taskkind);
                            //任务完成
                            agvstate.ActionComplete(Convert.ToInt32(_GetData[5] * Math.Pow(2, 8) + _GetData[4]), Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]));
                        }
                        if ((_GetData[0] == 81))
                        {
                            //AGV已经完成“删除监控下达的任务”（81＋任务号），是否在此向PCS反馈AGV状态readystatus把3改为0


                        }
                        if ((_GetData[0] == 86))
                        {
                            ////AGV下线（86＋任务号+AGV车号），监控把AGV正在执行的任务自动复位
                            //dbo.ExceSQL("update t_base_monitor_task set F_STATUS=0 where F_STATUS>0 and F_DEVICEINDEX=" + Convert.ToInt32(_GetData[5] * Math.Pow(2, 8) + _GetData[4]));
                            //dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + Convert.ToInt32(_GetData[5] * Math.Pow(2, 8) + _GetData[4]));
                        }
                        if ((_GetData[0] == 87))
                        {
                            ////AGV上报地标点（87＋任务号＋AGV车号＋地标点）地标点＝＝284时上报PCS离开称料区(PCS地址251)
                            ////if (Convert.ToInt32(_GetData[7] * Math.Pow(2, 8) + _GetData[6]) == 284)
                            ////{
                            //int fid = ccf.GetAgvTaskIndex(Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]));
                            //dboM.ExceSQL("update agvtask set CurrentLocation=251 where taskindex=" + fid);
                            ////}

                        }
                        else if ((_GetData[0] == 71))//任务开始
                        {//报告小车号

                            //ccf.ActionRecordAgvNo(0, Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]), Convert.ToInt32(_GetData[5] * Math.Pow(2, 8) + _GetData[4]));
                        }

                        //82 是否接受任务：1拒绝；0接受；

                        else if ((_GetData[4] == 1) && (_GetData[0] == 82))//AGV是否接受任务：0接受；1拒绝；
                        {
                            agvstate.ActionError(0, Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]), 82);
                        }
                        //77 上报输送机完成的小车号是否正确：1错误；0正确；
                        else if ((_GetData[4] == 0) && (_GetData[0] == 77))//0车号正确；
                        {
                            //agvstate.ActionComplete(Convert.ToInt32(_GetData[5] * Math.Pow(2, 8) + _GetData[4]), Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]));
                            //_receiveOK = agvstate.ActionOK;
                            //agvstate.ActionOK = null;
                        }
                        else if ((_GetData[4] == 1) && (_GetData[0] == 77))//1车号错误；
                        {
                            //agvstate.ActionError(0, Convert.ToInt32(_GetData[3] * Math.Pow(2, 8) + _GetData[2]), 77);
                        }

                      


                    }

                }
                catch (SocketException ex)
                {
                    //SocketsTCPIP.CClientTCPIP.IfInit = false;
                    ConnectedServer = false;
                    _tcpServerError = "CConnectTCPIP.BeginListen:" + ex.Message;
                }
            }
        }
        /// <summary>
        /// 连接远程主机和绑定本地主机端口
        /// </summary>
        /// <returns></returns>
        public static bool ConnectTcpIPServer()
        {
            string remoteIP; int remotePort; string localIP; int localPort;
            try
            {
                //根据DeviceIndex,得到Sockets通讯的初始设置
                DataView dv = dbo.ExceSQL("SELECT  F_DeviceIndex,F_DeviceKindIndex, F_LocalIP,  F_LocalPort, F_RemoteIP,  F_RemotePort  FROM T_Base_Device where F_DeviceIndex=0 and F_DeviceKindIndex=6").Tables[0].DefaultView;
                
                if (dv.Count == 0)
                {
                    return false;

                }
                else
                {
                    remoteIP = (dv[0]["F_RemoteIP"]).ToString();
                    localIP = (dv[0]["F_LocalIP"]).ToString();
                    remotePort =Convert.ToInt32 (dv[0]["F_RemotePort"]);
                    localPort =Convert.ToInt32 (dv[0]["F_LocalPort"]);
                }
                
                IPAddress ipAddress = IPAddress.Parse(localIP);
                IPEndPoint EPlocal = new IPEndPoint(ipAddress, localPort);
                

                // Create a TCP/IP socket.
                if (Localsocket == null)
                {
                    Localsocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
                    Localsocket.Bind((EndPoint)EPlocal);

                }
                
                
                
                if (SocketsTCPIP.CClientTCPIP.IfInit == false)
                {
                    if (SocketsTCPIP.CClientTCPIP.InitClientTCPIP(remoteIP,remotePort) == false)
                    {
                        _tcpServerError = SocketsTCPIP.CClientTCPIP.TcpError;
                        return false;
                    }
                }
                 
                 ConnectedServer = true;
                
                return ConnectedServer;

            }
            catch (Exception ex)
            {
                _tcpServerError = "CConnectTCPIP.ConnectTcpIPServer:" + ex.Message;
                return false;
            }
        }
        public static void EndListen()
        {
            _exitThread = true;
            if (SocketsTCPIP.CClientTCPIP.ClientSocket != null)
            {
                SocketsTCPIP.CClientTCPIP.ClientSocket.Close();
            }
            if (mythread != null)
            {
                mythread.Abort();
            }
        }
        
        public static void StartListen()
        {
            mythread = new Thread(new ThreadStart(BeginListen));
            mythread.Start();
        }
       
    }
}
