using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;

using DBFactory;
using System.Data;
namespace ControlSystem
{
    static class CGeneralFunction
    {
        static DBOperator dbo = CListenAGVState.dbo;
        //static Model.MDevice devinfo;
        /// <summary>
        /// 双叉关联任务是否能同步运行
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <returns></returns>
        public static bool DoubleForkIfSync(int monitorIndex, int devIndex, int devKind)
        {//查找关联的调度任务（主任务或者辅助任务）；输送机与堆垛机区别对待
            //如果只能找到关联任务未被拆分，那么认为能同步运行20100323
            int mankind = GetManageTaskKindIndexFromMonitor(monitorIndex);
            int FID = GetManageTaskIndexfromMonitor(monitorIndex);
            int devOrder = GetDeviceOrderFromMonitor(monitorIndex);
            int dfx = GetDoubleForkX(mankind, FID, devIndex, devOrder);
            int mx = GetXCoorFromMonitor(monitorIndex, devIndex, devOrder);
            int dfy = GetDoubleForkY(mankind, FID, devIndex, devOrder);
            int my = GetYCoorFromMonitor(monitorIndex, devIndex, devOrder);
            int dfz = GetDoubleForkZ(mankind, FID, devIndex, devOrder);
            int mz = GetZCoorFromMonitor(monitorIndex, devIndex, devOrder);
            if (GetDoubleForkUnIntoStep(monitorIndex) == true) return true;

            switch (devKind)
            {
                case 1:
                    //如果主任务和副任务的列数都是1列，则是1121、1122顶升机构，可以同步
                    if (1 == GetDoubleForkX(mankind, FID, devIndex, devOrder) && (GetXCoorFromMonitor(monitorIndex, devIndex, devOrder) == 1))
                    {
                        return true;
                    }

                    //堆垛机的同排，同层，临列可以同步并且ST_CELL的FDoubleFork值匹配


                    if ((Math.Abs(dfx - mx) == 1) && (dfy == my) && (mz == dfz))
                    {
                        if (EqualMonitorDoubleFork(mankind, FID, devIndex, devOrder) == true)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }

                case 2:
                    //输送机同步
                    return true;
                case 6:
                    //AGV临列可以同步并且ST_CELL的F_UseAwayFork值匹配


                    if (Math.Abs(dfx - mx) == 1)
                    {
                        if (EqualAGVGateDoubleFork(mankind, FID, devIndex, devOrder) == true)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }


                default:
                    return false;
            }

        }
        /// <summary>
        /// 获得双叉控制的堆垛机的送货任务（已经分配远货叉或者近货叉的任务）的值
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <returns></returns>
        public static string GetUseAwayFork(int monitorIndex)
        {
            DataView dv = dbo.ExceSQL("SELECT F_UseAwayFork FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIndex + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return dv[0][0].ToString();
            }
            else
            {
                return "-";
            }
        }

        /// <summary>
        /// 获取双叉控制的堆垛机的取货任务（尚未指定应该使用哪个货叉）是否使用远货叉（主货叉）：0，近货叉；1远货叉
        /// </summary>
        /// <param name="z">排</param>
        /// <param name="x">列</param>
        /// <param name="y">层</param>
        /// <param name="FWAREHOUSE">库房索引</param>
        /// <param name="Mankind">任务类型</param>
        /// <param name="ManFID">调度任务索引</param>
        /// <param name="devIndex">设备索引</param>
        /// <param name="devOrder">指令</param>
        /// <returns></returns>
        public static int GetUseAwayFork(int monitorIndex, int devIndex, int devOrder)
        {
            int z = GetZCoorFromMonitor(monitorIndex, devIndex, devOrder);
            int x = GetXCoorFromMonitor(monitorIndex, devIndex, devOrder);
            int y = GetYCoorFromMonitor(monitorIndex, devIndex, devOrder);

            string FWAREHOUSE = GetWAREHOUSEFromSTCELL(devIndex);
            int Mankind = GetManageTaskKindIndexFromMonitor(monitorIndex);
            int ManFID = GetManageTaskIndexfromMonitor(monitorIndex);

            DataView dv; int UseAwayFork = 1;
            try
            {
                dv = dbo.ExceSQL("SELECT FDoubleFork FROM ST_CELL WHERE (FWAREHOUSE='" + FWAREHOUSE
                + "') and (F_Z = " + z + ") AND (F_X = " + x + ") AND (F_Y = " + y + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    UseAwayFork = Convert.ToInt32(dv[0][0]);
                }
                else
                {
                    UseAwayFork = 0;
                }
                switch (UseAwayFork)
                {
                    case 0://可用任何一个货叉:
                        int xcoor = GetDoubleForkX(Mankind, ManFID, devIndex, devOrder);
                        if (xcoor != -1)
                        {
                            //根据关联任务的货位判断使用近货叉（列坐标小）或者远货叉（列坐标大）
                            if (xcoor != x)
                            {
                                if (xcoor < x)
                                {
                                    UseAwayFork = 1;
                                }
                                else
                                {
                                    UseAwayFork = 0;
                                }
                            }
                            else
                            {
                                //列坐标相同的，判断层坐标，近货叉（层坐标小）或者远货叉（层坐标大）
                                int ycoor = GetDoubleForkY(Mankind, ManFID, devIndex, devOrder);
                                if (ycoor != -1)
                                {
                                    if (ycoor != y)
                                    {
                                        if (ycoor < y)
                                        {
                                            UseAwayFork = 1;
                                        }
                                        else
                                        {
                                            UseAwayFork = 0;
                                        }
                                    }
                                    else
                                    {
                                        //列和层都相同的，判断排坐标，近货叉（排坐标小）或者远货叉（排坐标大）
                                        int zcoor = GetDoubleForkZ(Mankind, ManFID, devIndex, devOrder);
                                        if (zcoor != -1)
                                        {
                                            if (zcoor != z)
                                            {
                                                if (zcoor < z)
                                                {
                                                    UseAwayFork = 1;
                                                }
                                                else
                                                {
                                                    UseAwayFork = 0;
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            UseAwayFork = 1;
                        }
                        break;
                    case 1://只能用近叉
                        UseAwayFork = 0;
                        break;
                    case 2://只能用远叉
                        UseAwayFork = 1;
                        break;
                }
                return UseAwayFork;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        public static int GetDoubleForkFromST_CELL(int z, int x, int y, string FWAREHOUSE)
        {
            DataView dv; int UseAwayFork = 1;
            try
            {
                dv = dbo.ExceSQL("SELECT FDoubleFork FROM ST_CELL WHERE (FWAREHOUSE='" + FWAREHOUSE
                + "') and (F_Z = " + z + ") AND (F_X = " + x + ") AND (F_Y = " + y + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    UseAwayFork = Convert.ToInt32(dv[0][0]);
                }
                else
                {
                    UseAwayFork = 0;
                }

                return UseAwayFork;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }


        public static string GetWAREHOUSEFromSTCELL(int stackIndex)
        {
            DataView dv;
            try
            {
                dv = dbo.ExceSQL("SELECT FWAREHOUSE FROM ST_CELL WHERE  (FStack = " + stackIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return dv[0][0].ToString();
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally { dv = null; }
        }
        /// <summary>
        /// 查找双叉关联任务的列坐标
        /// </summary>
        /// <param name="mankind">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <param name="devOrder">设备指令</param>
        /// <returns></returns>
        public static int GetDoubleForkX(int mankind, int fid, int devIdx, int devOrder)
        {
            DataView dv;
            string xc = "F_NumParam2";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if (devOrder == 4)
                {
                    xc = "F_NumParam2";
                }
                else if (devOrder == 5)
                {
                    xc = "F_NumParam5";
                }
            }
            try
            {
                //查找被关联辅助设备指令索引的列坐标
                string sql = "SELECT " + xc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.F_RELATIVECONTORLID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][xc]);
                }

                //查找关联自己的主设备指令索引的列坐标
                sql = "SELECT " + xc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][xc]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }

        }
        /// <summary>
        /// 查找双叉关联任务的层坐标
        /// </summary>
        /// <param name="mankind">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <param name="devOrder">设备指令</param>
        /// <returns></returns>
        public static int GetDoubleForkY(int mankind, int fid, int devIdx, int devOrder)
        {
            DataView dv;
            string yc = "F_NumParam3";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if (devOrder == 4)
                {
                    yc = "F_NumParam3";
                }
                else if (devOrder == 5)
                {
                    yc = "F_NumParam6";
                }
            }
            try
            {
                //查找被关联辅助设备指令索引的层坐标
                string sql = "SELECT " + yc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.F_RELATIVECONTORLID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][yc]);
                }

                //查找关联自己的主设备指令索引的层坐标
                sql = "SELECT " + yc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][yc]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }

        }
        /// <summary>
        /// 查找双叉关联任务的排坐标
        /// </summary>
        /// <param name="mankind">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <param name="devOrder">设备指令</param>
        /// <returns></returns>
        public static int GetDoubleForkZ(int mankind, int fid, int devIdx, int devOrder)
        {
            DataView dv;
            string zc = "F_NumParam1";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if (devOrder == 4)
                {
                    zc = "F_NumParam1";
                }
                else if (devOrder == 5)
                {
                    zc = "F_NumParam4";
                }
            }
            try
            {
                //查找被关联辅助设备指令索引的排坐标
                string sql = "SELECT " + zc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.F_RELATIVECONTORLID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][zc]);
                }

                //查找关联自己的主设备指令索引的排坐标
                sql = "SELECT " + zc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][zc]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }

        }

        /// <summary>
        /// 查找双叉关联任务的ST_CELL表的使用哪个货叉属性是否相同
        /// </summary>
        /// <param name="mankind">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <param name="devOrder">设备指令</param>
        /// <returns></returns>
        public static bool EqualMonitorDoubleFork(int mankind, int fid, int devIdx, int devOrder)
        {
            DataView dv; char DoubleFork = '0', DoubleFork1 = '0';
            string xc = "F_NumParam2"; string yc = "F_NumParam3"; string zc = "F_NumParam1";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if ((devOrder == 4) || (devOrder == 2))
                {
                    xc = "F_NumParam2";
                    yc = "F_NumParam3";
                    zc = "F_NumParam1";
                }
                else if ((devOrder == 5) || (devOrder == 3))
                {
                    xc = "F_NumParam5";
                    yc = "F_NumParam6";
                    zc = "F_NumParam4";
                }
            }


            try
            {

                int z = 0, x = 0, y = 0, z1 = 0, x1 = 0, y1 = 0;
                //查找被关联辅助设备指令索引的列坐标
                string sql = "SELECT " + zc + "," + xc + "," + yc + ",F_UseAwayFork FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.F_RELATIVECONTORLID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    z = Convert.ToInt32(dv[0][zc]);
                    x = Convert.ToInt32(dv[0][xc]);
                    y = Convert.ToInt32(dv[0][yc]);
                    DoubleFork = Convert.ToChar(dv[0]["F_UseAwayFork"]);
                }
                else
                {
                    //查找关联自己的主设备指令索引的列坐标
                    sql = "SELECT " + zc + "," + xc + "," + yc + ",F_UseAwayFork FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex " +
                        " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                        fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        z = Convert.ToInt32(dv[0][zc]);
                        x = Convert.ToInt32(dv[0][xc]);
                        y = Convert.ToInt32(dv[0][yc]);
                        DoubleFork = Convert.ToChar(dv[0]["F_UseAwayFork"]);
                    }

                }
                if ((z == 0) && (x == 0) && (y == 0))
                {
                    return false;
                }
                else
                {
                    sql = "SELECT " + zc + "," + xc + "," + yc + ",F_UseAwayFork FROM T_Monitor_Task Where ( F_ManageTASKKINDINDEX = " + mankind + ") AND (F_ManageTaskIndex = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        z1 = Convert.ToInt32(dv[0][zc]);
                        x1 = Convert.ToInt32(dv[0][xc]);
                        y1 = Convert.ToInt32(dv[0][yc]);
                        DoubleFork1 = Convert.ToChar(dv[0]["F_UseAwayFork"]);
                        if (((x1 > x) && (DoubleFork1 > DoubleFork)) || ((x > x1) && (DoubleFork > DoubleFork1)))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }

        }

        /// <summary>
        /// 查找双叉关联任务的T_Base_AGV_Gate表的货叉属性是否匹配
        /// </summary>
        /// <param name="mankind">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <param name="devOrder">设备指令</param>
        /// <returns></returns>
        public static bool EqualAGVGateDoubleFork(int mankind, int fid, int devIdx, int devOrder)
        {
            DataView dv;
            string xc = "F_NumParam2";
            if (GetDeviceKindIdx(devIdx) == 6)
            {
                if (devOrder == 1)
                {
                    xc = "F_NumParam2";
                }
                else if (devOrder == 2)
                {
                    xc = "F_NumParam5";
                }
                else if (devOrder == 4)
                {
                    xc = "F_NumParam5";
                }
            }

            try
            {

                int x = 0, x1 = 0;
                int channelleft = 0, channelleft1 = 0, xd = 0, xd1 = 0;
                //查找被关联辅助设备指令索引的列坐标
                string sql = "SELECT " + xc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.F_RELATIVECONTORLID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                    xd = Convert.ToInt32(dv[0][xc]);
                    dv = dbo.ExceSQL("SELECT F_Sequence FROM T_Base_AGV_Gate WHERE (F_AGVGateDeviceIndex = " + xd + ")").Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        x = Convert.ToInt32(dv[0]["F_Sequence"]);
                    }
                    else
                    {
                        x = 0;
                    }
                }
                else
                {
                    //查找关联自己的主设备指令索引的列坐标
                    sql = "SELECT " + xc + " FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex " +
                        " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                        fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        xd = Convert.ToInt32(dv[0][xc]);
                        dv = dbo.ExceSQL("SELECT F_Sequence FROM T_Base_AGV_Gate WHERE (F_AGVGateDeviceIndex = " + xd + ")").Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            x = Convert.ToInt32(dv[0]["F_Sequence"]);
                        }
                        else
                        {
                            x = 0;
                        }
                    }

                }
                if (x == 0)
                {
                    return false;
                }
                else
                {
                    sql = "SELECT " + xc + " FROM T_Monitor_Task Where ( F_ManageTASKKINDINDEX = " + mankind + ") AND (F_ManageTaskIndex = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        xd1 = Convert.ToInt32(dv[0][xc]);
                        dv = dbo.ExceSQL("SELECT F_Sequence FROM T_Base_AGV_Gate WHERE (F_AGVGateDeviceIndex = " + xd1 + ")").Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            x1 = Convert.ToInt32(dv[0]["F_Sequence"]);
                        }
                        else
                        {
                            x1 = 0;
                        }
                        int DoubleFork = 0, DoubleFork1 = 0;
                        dv = dbo.ExceSQL("SELECT F_UseAwayFork,F_IfChannelLeft FROM T_Base_AGV_Gate WHERE F_AGVGateDeviceIndex =" + xd).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            DoubleFork = Convert.ToInt32(dv[0]["F_UseAwayFork"]);
                            channelleft = Convert.ToInt32(dv[0]["F_IfChannelLeft"]);
                        }
                        else
                        {
                            return false;
                        }
                        dv = dbo.ExceSQL("SELECT F_UseAwayFork,F_IfChannelLeft FROM T_Base_AGV_Gate WHERE F_AGVGateDeviceIndex =" + xd1).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            DoubleFork1 = Convert.ToInt32(dv[0]["F_UseAwayFork"]);
                            channelleft1 = Convert.ToInt32(dv[0]["F_IfChannelLeft"]);
                        }
                        else
                        {
                            return false;
                        }
                        if ((((x1 > x) && (DoubleFork1 > DoubleFork)) || ((x > x1) && (DoubleFork > DoubleFork1))) && (channelleft == channelleft1))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }

        }

        /// <summary>
        /// 在设备指令队列表获取Z 排坐标
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <returns></returns>
        public static int GetZCoorFromMonitor(int monitorIndex, int devIdx, int devOrder)
        {
            DataView dv;
            string zc = "F_NumParam1";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if (devOrder == 4)
                {
                    zc = "F_NumParam1";
                }
                else if (devOrder == 5)
                {
                    zc = "F_NumParam4";
                }
            }
            try
            {
                dv = dbo.ExceSQL("SELECT " + zc + " FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][0]);
                }
                else
                {
                    return -1;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        /// <summary>
        /// 在设备指令队列表获取X 列坐标
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <returns></returns>
        public static int GetXCoorFromMonitor(int monitorIndex, int devIdx, int devOrder)
        {
            DataView dv;
            string xc = "F_NumParam2";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if (devOrder == 4)
                {
                    xc = "F_NumParam2";
                }
                else if (devOrder == 5)
                {
                    xc = "F_NumParam5";
                }
            }
            try
            {
                dv = dbo.ExceSQL("SELECT " + xc + " FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][0]);
                }
                else
                {
                    return -1;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }
        /// <summary>
        /// 在设备指令队列表获取Y 层坐标
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <returns></returns>
        public static int GetYCoorFromMonitor(int monitorIndex, int devIdx, int devOrder)
        {
            DataView dv;
            string yc = "F_NumParam3";
            if (GetDeviceKindIdx(devIdx) == 1)
            {
                if (devOrder == 4)
                {
                    yc = "F_NumParam3";
                }
                else if (devOrder == 5)
                {
                    yc = "F_NumParam6";
                }
            }
            try
            {
                dv = dbo.ExceSQL("SELECT " + yc + " FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][0]);
                }
                else
                {
                    return -1;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        /// <summary>
        /// 返回双叉关联设备指令信息：【0】设备指令索引【1】提前检测【2】设备索引【3】路径
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <returns></returns>
        public static string[] GetDoubleForkMonitorInfo(int monitorIndex, int devIdx)
        {
            DataView dv;

            string[] rr = null;
            try
            {
                int mankind = GetManageTaskKindIndexFromMonitor(monitorIndex);
                int fid = GetManageTaskIndexfromMonitor(monitorIndex);
                int devOrder = GetDeviceOrderFromMonitor(monitorIndex);
                //查找被关联辅助设备指令索引的列坐标
                string sql = "SELECT F_MonitorIndex,F_AheadDetect,F_DeviceIndex,F_RouteID FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.F_RELATIVECONTORLID = T_Monitor_Task.F_ManageTaskIndex " +
                    " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    rr = new string[4];
                    rr[0] = dv[0]["F_MonitorIndex"].ToString();
                    rr[1] = dv[0]["F_AheadDetect"].ToString();
                    rr[2] = dv[0]["F_DeviceIndex"].ToString();
                    rr[3] = dv[0]["F_RouteID"].ToString();
                }
                else
                {
                    //查找关联自己的主设备指令索引的列坐标
                    sql = "SELECT F_MonitorIndex,F_AheadDetect,F_DeviceIndex,F_RouteID FROM T_Manage_Task,T_Monitor_Task Where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex " +
                        " AND T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX) and ( T_Monitor_Task.F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                        fid + ") and (F_DeviceIndex=" + devIdx + " and F_DeviceCommandIndex=" + devOrder + ")";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        rr = new string[4];
                        rr[0] = dv[0]["F_MonitorIndex"].ToString();
                        rr[1] = dv[0]["F_AheadDetect"].ToString();
                        rr[2] = dv[0]["F_DeviceIndex"].ToString();
                        rr[3] = dv[0]["F_RouteID"].ToString();
                    }
                    else
                    {
                        return null;
                    }
                }
                return rr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
                rr = null;
            }
        }

        /// <summary>
        /// 返回未拆分的双叉关联设备指令,true 代表有未拆分的双叉关联设备指令
        /// </summary>
        /// <param name="monitorIndex">设备指令索引</param>
        /// <returns></returns>
        public static bool GetDoubleForkUnIntoStep(int monitorIndex)
        {
            DataView dv;
            try
            {
                int mankind = GetManageTaskKindIndexFromMonitor(monitorIndex);
                int fid = GetManageTaskIndexfromMonitor(monitorIndex);
                //查找被关联辅助设备指令索引的列坐标
                string sql = "SELECT F_RELATIVECONTORLID FROM T_Manage_Task Where (T_Manage_Task.F_RELATIVECONTORLID <>-1 ) and ( F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    fid + ")";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    sql = "SELECT FID FROM T_Manage_Task Where ( F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                    dv[0][0] + " and FIntoStepOK<>'1')";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }




                }
                else
                {
                    //查找关联自己的主设备指令索引的列坐标
                    sql = "SELECT FID FROM T_Manage_Task Where ( F_ManageTaskKindIndex = " + mankind + ") AND (F_RELATIVECONTORLID = " +
                        fid + ")";
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        sql = "SELECT FID FROM T_Manage_Task Where ( F_ManageTaskKindIndex = " + mankind + ") AND (FID = " +
                        dv[0][0] + " and FIntoStepOK<>'1')";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        public static int GetManageTaskIndexfromMonitor(int monitorIdx)
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIdx + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_ManageTaskIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;
            }
        }
        public static int GetManageTaskKindIndexFromMonitor(int monitorIdx)
        {//20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT F_ManageTaskKindIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIdx + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;

            }


        }

        /// <summary>
        /// 在调度队列中找到设备命令
        /// </summary>
        /// <param name="MonitorIndex">调度所引</param>
        /// <returns></returns>
        public static int GetDeviceOrderFromMonitor(int MonitorIndex)
        {
            //20100108
            DataView dv;
            try
            {
                string sql = "select F_DeviceCommandIndex from T_Monitor_Task where (F_DeviceCommandIndex IS NOT NULL) and F_MonitorIndex=" + MonitorIndex;
                //20100108
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_DeviceCommandIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        public static int GetDeviceKindIdx(int devIdx)
        {
            object ob;
            try
            {
                ob = dbo.GetSingle("SELECT F_DeviceKindIndex FROM T_Base_Device WHERE (F_DeviceIndex = " + devIdx + ")");
                //devinfo = Model.CGetInfo.GetDeviceInfo(devIdx);
                if (ob != null)
                {
                    return Convert.ToInt32(ob);
                }
                else
                {
                    return -1;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static int GetDeviceIndexFromMonitor(int MonitorIndex)
        {
            //20100108
            DataView dv;
            try
            {
                string sql = "select F_DeviceIndex from T_Monitor_Task where (F_DeviceIndex IS NOT NULL) and F_MonitorIndex=" + MonitorIndex;
                //20100108
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        /// <summary>
        /// 双叉堆垛机在一个输送机取送盘时需要额外检测的探物开关（隔壁输送机是否有探物）
        /// </summary>
        /// <param name="devinx"></param>
        /// <returns></returns>
        //public static int GetDoubleForkDetect(int devinx)
        //{

        //    try
        //    {
        //        devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
        //        return Convert.ToInt32(devinfo.DoubleForkDetect);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    finally
        //    {
        //        devinfo = null;
        //    }

        //}

        /// <summary>
        /// 获取能同步运行的设备指令的关联设备指令索引
        /// </summary>
        /// <param name="monitorIdx"></param>
        /// <returns></returns>
        public static int GetCorrelDoubleForkFromMonitor(int monitorIdx)
        {
            DataView dv = dbo.ExceSQL("select F_CorrelDoubleFork from T_Monitor_Task where F_MonitorIndex=" + monitorIdx + " and (F_CorrelDoubleFork is not null) ").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0][0]);
            }
            else
            {
                return -1;
            }
        }
    }
    /// <summary>
    /// Creator:Richard.liu
    /// 独立线程，监听AGV反馈的数据，并进行解析
    /// </summary>
    public static class CListenAGVState
    {
        
        //记录AGV操作地址号
        static ushort[] AgvActive = new ushort[4];
        //static bool _exitThread = false;
        static string _tcpServerError="";

        /// <summary>
        /// 监听接收AGV发送的数据时发生的故障
        /// </summary>
        public static string TcpServerError
        {
            get { return CListenAGVState._tcpServerError; }
            set { CListenAGVState._tcpServerError = value; }
        }
        static string _receiveOK = null;
        /// <summary>
        /// 监听到该AGV车的所有队列完成
        /// </summary>
        public static string ReceiveOK
        {
            get { return CListenAGVState._receiveOK; }
            set { CListenAGVState._receiveOK = value; }
        }
        static Thread mythread;
        static Socket Localsocket;
        static bool exitThread = false;//20091107
        static bool ConnectedServer = false;
        static byte[] _GetData = new byte[8192];
        public static DBOperator dbo = new DBOperator();
        static DBOperator dboM = new DBOperator("ManConnString", "ManDBFactory");
        static CControl cc = new CControl();

        /// <summary>
        /// 开始监听接收到的数据
        /// </summary>
        private static void BeginListen()
        {
            //20091107
            while (!exitThread )
            {
                
                try
                {
                    int gcount = 0;
                    if (ConnectedServer == false)
                    {
                        if (ConnectTcpIPServer() == false)
                        {
                            Thread.Sleep(200);//20100710
                            continue;
                        }
                    }

                    Localsocket.Listen(1);
                    try

                    {
                        //20090920
                        if (SocketsTCPIP.CClientTCPIP.ClientSocket.Connected == true)
                        {

                            gcount = SocketsTCPIP.CClientTCPIP.ClientSocket.Receive(_GetData);
                        }
                        else
                        {
                            SocketsTCPIP.CClientTCPIP.IfInit = false;
                            ConnectedServer = false;
                        }
                        if (gcount == 0)
                        {//20091107
                            SocketsTCPIP.CClientTCPIP.IfInit = false;
                            ConnectedServer = false;
                            Thread.Sleep(200);//20100710
                            continue;
                        }
                        
                    }
                    catch (SocketException ex)
                    {
                        _tcpServerError = "CListenAGVState.BeginListen:" + ex.Message;
                        SocketsTCPIP.CClientTCPIP.IfInit = false;
                        ConnectedServer = false;
                        Thread.Sleep(200);//20100710
                        continue;
                    }

                    //处理接收到数据:根据gcount在_GetData中查找各个帧头，按帧拆分
                    //帧的每两个字节（一个字）代表一个含义
                    byte[] chatnew;
                    chatnew = new byte[gcount];
                    Array.Copy(_GetData,0,  chatnew,0, gcount);
                    //将byte数组转换成UInt16数组
                    UInt16[] newData = ConvertByteToUInt16(chatnew);
                    CCarryConvert.WriteDarkCasket("ReceiveAGV", "SocketsTCPIP.CConnectTCPIP", "Receive", "1000", chatnew);
                    
                    
                    //处理收到的消息
                    DisposeReceivedMessage(newData);
                    chatnew = null;//20100127
                    
                }
                catch (SocketException ex)
                {
                    ConnectedServer = false;
                    _tcpServerError = "CListenAGVState.BeginListen:" + ex.Message;
                }
                Thread.Sleep(200);//20100710
            }
        }

        #region 将BYTE数组转换为UInt16数组
        /// <summary>
        /// 将BYTE数组转换为UInt16数组
        /// </summary>
        /// <param name="srcData">需要处理的byte数组</param>
        /// <returns>返回UInt16数组</returns>
        private static UInt16[] ConvertByteToUInt16(byte[] srcData)
        {
            byte[] chat = null;
            //判断srcData数组的维数是否为奇数，如果为奇数则舍弃最后一位
            if (srcData.Length % 2 == 1)
            {
                chat = new byte[srcData.Length - 1];
                Array.Copy(srcData,0, chat,0, srcData.Length - 1);
                //Buffer.BlockCopy(srcData, 0, chat, 0, srcData.Length - 1);
            }
            else
            {
                chat = new byte[srcData.Length];
                Array.Copy(srcData,0, chat,0, srcData.Length);
                //Buffer.BlockCopy(srcData, 0, chat, 0, srcData.Length);
            }

            UInt16[] newData = new UInt16[chat.Length / 2];

            int temp = 0;
            for (int i = 0; i < newData.Length; i++)
            {
                newData[i] = (UInt16)((chat[temp+ 1] << 8) + chat[temp ]);//C#版：0是低位，1是高位；VC++版：1是低位，0是高位；
                temp += 2;
            }

            return newData;
        }
        #endregion

        #region 处理收到的消息
        /// <summary>
        /// 处理收到的消息
        /// </summary>
        /// <param name="message">消息数组</param>
        private static void DisposeReceivedMessage(UInt16[] message)
        {
            ushort[] chatnew;
            
            try
            {
                for (int i = 0; i < message.Length; )
                {

                    switch (message[i])
                    {
                        case 75://75（ushort）+任务号（ushort）+65535（ushort）,进入消息队列
                            if (message.Length >= 3)//
                            {
                                if (message.Length <= (i + 2)) break;
                                try
                                {
                                    dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_Status=2  WHERE F_MonitorIndex = " + message[i + 1] + "");
                                    #region 双叉关联任务可以同步的一同报开始
                                    if (CGeneralFunction.DoubleForkIfSync(message[i + 1], 1001, 6) == true)
                                    {
                                        string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(message[i + 1], 1001);
                                        if (df != null)
                                        {
                                            dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_Status=2  WHERE F_MonitorIndex = " +Convert.ToInt32( df[0]) + "");
                                            
                                        }
                                    }
                                    #endregion
                                }
                                catch (Exception ex)
                                {
                                    _tcpServerError = "CListenAGVState.DisposeReceivedMessage:任务进入消息队列，" + ex.Message;
                                }
                                chatnew = new ushort[3];
                                Array.Copy(message, i, chatnew, 0, 3);
                                CCarryConvert.WriteDarkCasket("ReceiveAGV", "SocketsTCPIP.CConnectTCPIP", "Receive", "AGV任务进入消息队列", chatnew);
                                i += 3;
                            }
                            break;

                        case 70://70（ushort）+任务号（ushort）+AGV编号（ushort）  AGV完成任务；调度需要发送：75（ushort）+任务号（ushort）+65535（ushort）
                            if (message.Length >= 3)
                            {
                                if (message.Length <= (i + 2)) break;
                                try
                                {
                                    //20100817 zhangxy 修改
                                    int fid = GetManageTaskIndexfromMonitor(message[i + 1]);
                                    int mankind = GetManageTaskKindIndexFromMonitor(message[i + 1]);
                                    ///////////////////////
                                    string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(message[i + 1], 1001);
                                    bool snyc = CGeneralFunction.DoubleForkIfSync(message[i + 1], 1001, 6);
                                    //根据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=1001" ).Tables[0].DefaultView;
                                    if (dv.Count > 0)
                                    {
                                        byte[] _Sdata = new byte[6];
                                        _Sdata[0] = 75;
                                        _Sdata[1] = 0;

                                        _Sdata[2] = Convert.ToByte(message[i + 1] & 255);
                                        _Sdata[3] = Convert.ToByte(message[i + 1] >> 8);
                                        _Sdata[4] = Convert.ToByte(65535 & 255);
                                        _Sdata[5] = Convert.ToByte(65535 >> 8);
                                        if (SocketsTCPIP.CClientTCPIP.Send(dv[0]["F_RemoteIP"].ToString(), Convert.ToInt32(dv[0]["F_RemotePort"]), _Sdata) == true)
                                        {
                                            
                                            //20100817 zhangxy 修改
                                            dbo.ExceSQL("update T_Base_device set F_LockedState=" + message[i + 1] +
                                                " where   F_DeviceIndex=" + message[i + 2] + "");
                                            int ir = dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_AgvNo=" + message[i + 2] + "  WHERE F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex=" + mankind + " and F_DeviceIndex=1001 and (F_AgvNo is null) ");
                                            ///////////////////////
                                            ActionComplete(1001, message[i + 1], 0);
                                            //刷新监控中心显示
                                            #region 双叉关联任务，能同步的同时报告完成；异步的直接执行关联的命令
                                            //20100323
                                            if (df != null)//20100702
                                            {
                                                //20100817 zhangxy 修改
                                                fid = GetManageTaskIndexfromMonitor(Convert.ToInt32(df[0]));
                                                mankind = GetManageTaskKindIndexFromMonitor(Convert.ToInt32(df[0]));
                                                dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_AgvNo=" + message[i + 2] + "  WHERE F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex=" + mankind + " and F_DeviceIndex=1001");
                                                ///////////////////////
                                                if (snyc == true)//20100702
                                                {
                                                    ActionComplete(1001, Convert.ToInt32(df[0]), 1);//20100702

                                                }
                                                else
                                                {//20100702

                                                    cc.SendMonitorTask(Convert.ToInt32(df[0]));


                                                }
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            _tcpServerError = "向AGV反馈任务：" + message[i + 1]+"的应答时，发送失败！";
                                        }


                                    }
                                                                       
                                    
                                    chatnew = new ushort[3];
                                    Array.Copy(message, i, chatnew, 0, 3);
                                    CCarryConvert.WriteDarkCasket("ReceiveAGV", "SocketsTCPIP.CConnectTCPIP", "Receive", "AGV完成任务", chatnew);
                                    
                                }
                                catch (Exception ex)
                                {
                                    _tcpServerError = "CListenAGVState.DisposeReceivedMessage:AGV完成任务," + ex.Message;
                                }
                                i += 3;
                            }
                            break;
                        case 71://71（ushort）+任务号（ushort）＋AGV编号（ushort） ;AGV控制台开始分配AGV车号
                            if (message.Length >= 3)
                            {
                                if (message.Length <= (i + 2)) break;
                                try
                                {
                                    int fid = GetManageTaskIndexfromMonitor(message[i + 1]);
                                    int mankind = GetManageTaskKindIndexFromMonitor(message[i + 1]);
                                    //dbo.ExceSQL("update T_Base_device set F_LockedState=" + message[i + 1] +
                                    //" where   F_DeviceIndex=" + message[i + 2] + "");
                                    if (mankind == 1)
                                    {//20100714
                                        dboM.ExecuteSql("update IO_CONTROL set CONTROL_STATUS=11 where CONTROL_ID=" + fid + "");
                                    }
                                    //int ir = dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_AgvNo=" + message[i + 2] + "  WHERE F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex=" + mankind + " and F_DeviceIndex=1001 and (F_AgvNo is null) ");
                                    
                                    #region 双叉关联任务一起分配车号
                                    string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(message[i + 1], 1001);
                                    if (df != null)
                                    {
                                        fid = GetManageTaskIndexfromMonitor(Convert.ToInt32(df[0]));
                                        mankind = GetManageTaskKindIndexFromMonitor(Convert.ToInt32(df[0]));
                                        //dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_AgvNo=" + message[i + 2] + "  WHERE F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex=" + mankind + " and F_DeviceIndex=1001");
                                        if (mankind == 1)
                                        {//20100714
                                            dboM.ExecuteSql("update IO_CONTROL set CONTROL_STATUS=11 where CONTROL_ID=" + fid + "");
                                        }

                                    }
                                    else
                                    {
                                        #region 给单一AGV任务配双叉任务
                                        
                                        //if ((ir > 0) &&(GetDeviceOrderFromMonitor(message[i + 1])==1)&&(GetFCONTROLTASKTYPEFromManageTask(GetManageTaskKindIndexFromMonitor(message[i + 1]),GetManageTaskIndexfromMonitor(message[i + 1])))==1)//第一次分配车号并且是入库任务的取货指令
                                        //{//查找一个后续位置的未发送的关联任务，可能会涉及到关联设备改道和重分配货叉
                                        //    int xCoor=CGeneralFunction.GetXCoorFromMonitor(message[i + 1], 1001, 1);
                                        //    int agvSquence = GetAgvSquence(xCoor);
                                        //    int useAwayfork = GetUseAwayFork(message[i + 1]);
                                        //    if (useAwayfork == 1)
                                        //    {
                                        //        useAwayfork = 0;
                                        //    }
                                        //    else
                                        //    {
                                        //        useAwayfork = 1;
                                        //    }
                                        //    DataView dv = dbo.ExceSQL(" SELECT TOP 1 T_Monitor_Task.F_ManageTaskIndex,T_Monitor_Task.F_ManageTASKKINDINDEX,T_Monitor_Task.F_MonitorIndex FROM T_Monitor_Task,T_Base_AGV_Gate,T_Manage_Task where T_Monitor_Task.F_NumParam2 = T_Base_AGV_Gate.F_AGVGateDeviceIndex and T_Monitor_Task.F_ManageTaskIndex = T_Manage_Task.FID AND  T_Monitor_Task.F_ManageTASKKINDINDEX = T_Manage_Task.F_ManageTaskKindIndex and (T_Monitor_Task.F_Status = 0) AND (T_Base_AGV_Gate.F_Sequence >" + agvSquence + ") AND(T_Monitor_Task.F_DeviceIndex = 1001) AND (T_Monitor_Task.F_DeviceCommandIndex = 1) AND (T_Manage_Task.F_RELATIVECONTORLID = - 1) and (FCONTROLTASKTYPE=1) and (F_UseAwayFork ='" + useAwayfork + "') and (F_AgvNo is null) ORDER BY F_Sequence asc").Tables[0].DefaultView;
                                        //    if (dv.Count > 0)
                                        //    {//找到一个合适的双叉关联任务
                                        //        fid = GetManageTaskIndexfromMonitor(message[i + 1]);
                                        //        mankind = GetManageTaskKindIndexFromMonitor(message[i + 1]);
                                        //        int fidr =Convert.ToInt32( dv[0]["F_ManageTaskIndex"]);
                                        //        int mankindr = Convert.ToInt32(dv[0]["F_ManageTASKKINDINDEX"]);
                                        //        dbo.TransBegin();
                                        //        try
                                        //        {
                                        //            //修改双叉关联任务；分配AGV车号
                                        //            dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + fidr + " where FID=" + fid + " and F_ManageTaskKindIndex="+mankind+"");
                                        //            dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + fid + " where FID=" + fidr + " and F_ManageTaskKindIndex=" + mankindr + "");
                                        //            dbo.ExecuteSql("UPDATE T_Monitor_Task SET F_AgvNo=" + message[i + 2] + "  WHERE F_ManageTaskIndex=" + fidr + " and F_ManageTaskKindIndex=" + mankindr + " and F_DeviceIndex=1001");
                                        //            dbo.TransCommit();
                                        //        }
                                        //        catch (Exception ex)
                                        //        {
                                        //            _tcpServerError = "CListenAGVState.DisposeReceivedMessage:分配AGV车号," + ex.Message;
                                        //            dbo.TransRollback();
                                        //        }

                                        //    }
                                        //    dv = null;
                                        //}

                                        #endregion
                                    }
                                    #endregion

                                }
                                catch (Exception ex)
                                {
                                    _tcpServerError = "CListenAGVState.DisposeReceivedMessage:AGV控制台开始分配AGV车号," + ex.Message;
                                }
                                chatnew = new ushort[3];
                                Array.Copy(message, i, chatnew, 0, 3);
                                CCarryConvert.WriteDarkCasket("ReceiveAGV", "SocketsTCPIP.CConnectTCPIP", "Receive", "AGV控制台开始分配AGV车号", chatnew);
                                i += 3;
                            }
                            break;
                        
                    }
                }
            }
            catch (Exception ex)
            {
                _tcpServerError = "CConnectTCPIP.DisposeReceiveMessage:" + ex.Message;
                
            }
            finally
            {//20100127
                chatnew  = null;
                
            }
        }
        #endregion
        public static int GetAgvSquence(int agvGate)
        {
            object ob = dbo.GetSingle("SELECT F_Sequence FROM T_Base_AGV_Gate WHERE (F_AGVGateDeviceIndex = "+agvGate+")");
            if (ob != null)
            {
                return Convert.ToInt32(ob);

            }
            else
            {
                return -1;
            }
        }
        public static int GetUseAwayFork(int taskno)
        {
            string obj = dbo.GetSingle("SELECT F_UseAwayFork FROM T_Monitor_Task WHERE (F_MonitorIndex = "+taskno+")").ToString();
            if (obj == "-")
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        public static int GetFCONTROLTASKTYPEFromManageTask(int taskKindIndex, int Managefid)
        {
            DataView dv;
            try
            {
                dv = dbo.ExceSQL("SELECT FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FID = " + Managefid + ") AND (F_ManageTaskKindIndex = " + taskKindIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["FCONTROLTASKTYPE"] == DBNull.Value) return -1;
                    return Convert.ToInt32(dv[0]["FCONTROLTASKTYPE"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;

            }
        }

        /// <summary>
        /// 连接远程主机和绑定本地主机端口
        /// </summary>
        /// <returns></returns>
        public static bool ConnectTcpIPServer()
        {
            string remoteIP; int remotePort; string localIP; int localPort;
            //20100127
            DataView dv;
            IPAddress ipAddress ;
            IPEndPoint EPlocal;
            try
            {
                //根据DeviceIndex,得到Sockets通讯的初始设置
                //20100127
                dv = dbo.ExceSQL("SELECT  F_DeviceIndex,F_DeviceKindIndex, F_LocalIP,  F_LocalPort, F_RemoteIP,  F_RemotePort  FROM T_Base_Device where F_DeviceIndex=1001 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"]);
                }
                //20100127
                ipAddress = IPAddress.Parse(localIP);
                //20100127
                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;
            }
            finally
            {//20100127
                dv = null;
                ipAddress =null ;
                EPlocal = null;
                remoteIP = null;
                localIP = null;
            }
        }
        public static void EndListen()
        {//20091107
            exitThread=true ;
            if (SocketsTCPIP.CClientTCPIP.ClientSocket != null)
            {
                SocketsTCPIP.CClientTCPIP.ClientSocket.Close();
            }
            if (mythread != null)
            {
                mythread.Abort();
               
                mythread = null;
            }
        }

        public static void StartListen()
        {
            exitThread = false ;
            if (mythread == null)
            {
                mythread = new Thread(new ThreadStart(BeginListen));
                mythread.IsBackground = true;
            }
            if (mythread.ThreadState != ThreadState.Running)
            {
                mythread.Start();
            }
        }
        public static void ActionComplete(int DeviceIdx, int TaskIdx, int ClearZero)
        {
            int devKind = GetDeviceKindIdx(DeviceIdx);
            int order = GetDeviceOrderFromMonitor(TaskIdx);
            int fid = GetManageTaskIndexfromMonitor(TaskIdx);
            int mti = GetManageTaskKindIndexFromMonitor(TaskIdx);
            //20100710
            #region 取得AGV放货点输送机的编号（AGV通道内的停车点设备）
            
            int AgvNextConveyor = 0;
            object ob = dbo.GetSingle("SELECT F_NumParam5 FROM T_Monitor_Task WHERE (F_MonitorIndex = "+TaskIdx+") ");
            if (ob != null)
            {
                if (GetDeviceKindIdx(Convert.ToInt32(ob)) == 2)
                {
                    AgvNextConveyor = Convert.ToInt32(ob);
                }
            }//20100710

            #endregion


            string cap;
            int errrcode = GetExceptionNOFromManageTask(fid, mti);
            DataView dv;//20100127
            //dbo.TransBegin();
            try
            {
                //20100127
                dv = dbo.ExceSQL("select count(F_MonitorIndex) as counts from T_Monitor_Task " +
                                    " where F_ManageTaskIndex =" + fid + " and F_ManageTaskKindIndex= " + mti).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if ((Convert.ToInt32(dv[0]["counts"]) == 1) && (CStaticClass.RouteSearchMode == "0"))
                    {
                        //固定路径模式
                        //调度任务的fid的最后一个监控分解任务完成

                        if (mti == 1)
                        {
                            cap = "调度任务";
                            //完成FSTATUS=999；970堆垛机送货重故障异常完成；980堆垛机取空故障异常完成；990条码扫描异常完成；调度撤销删除调度任务900
                            if (errrcode > 900)//异常完成
                            {
                                dboM.ExceSQL("update IO_Control set Control_STATUS=" + errrcode + " where Control_ID=" + fid);
                            }
                            else
                            {
                                if (ClearZero == Model.CGeneralFunction.TASKDELETE)//调度撤销删除调度任务900
                                {
                                    dboM.ExceSQL("update IO_Control set Control_STATUS=" + Model.CGeneralFunction.TASKDELETE + " where Control_ID=" + fid);
                                }
                                else//完成FSTATUS=999
                                {
                                    dboM.ExceSQL("update IO_Control set Control_STATUS=" + Model.CGeneralFunction.TASKFINISH + " where Control_ID=" + fid);
                                }
                            }
                        }
                        else if (mti == 4)
                        {
                            cap = "手工任务";
                        }
                        else
                        {
                            cap = "临时任务";
                        }
                        //回写管理表
                        if (ClearZero == Model.CGeneralFunction.TASKDELETE)//调度撤销删除调度任务900
                        {
                            ReturnManageInfo(fid, mti, cap, false);
                        }
                        else
                        {
                            ReturnManageInfo(fid, mti, cap, true);
                        }
                    }

                }
                #region AGV向输送机放货增加逻辑有物20100710
                if ((AgvNextConveyor > 0)&&(order==2))
                {
                    dbo.ExceSQL("update T_Base_Device set F_HaveGoods=1 where F_DeviceIndex=" + AgvNextConveyor + " ");
                }
                #endregion

                //被这个任务号锁定的设备全部解锁
                dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_LockedState=" + TaskIdx);
                //dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + DeviceIdx);
                dbo.ExceSQL("update T_Base_Device set F_CreateLock='0' where F_DeviceIndex=" + DeviceIdx);
                
                if (ClearZero == 1)
                {
                    
                    if (mti == 1)
                    {
                        dboM.ExceSQL("UPDATE IO_CONTROL  SET  ERROR_TEXT =''  WHERE Control_ID=" + fid + " and Control_STATUS<900");
                    }
                }

                dbo.ExceSQL("delete from T_Monitor_Task   where F_MonitorIndex=" + TaskIdx);


            }
            catch (Exception ex)
            {
                _tcpServerError = "CListenAGVState.ActionComplete:" + ex.Message;
            }
            finally
            {//20100127
                dv = null;
            }
        }
        static void ReturnManageInfo(int fid, int mti, string cap, bool IFOK)
        {
            //20100127
            DataView dv;
            try
            {
                //200906240111增加货位记录:入库1-结束位置有货；出库2-起始位置无货；倒库3-起始位置无货，结束位置有货
                //20100127
                dv = dbo.ExceSQL("SELECT FID, F_ManageTaskKindIndex,FCONTROLTASKTYPE, FSTARTDEVICE,FSTARTCELL, FENDDEVICE,FENDCELL FROM T_Manage_Task where F_ManageTaskKindIndex=" + mti + " and FID=" + fid + "").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    switch (dv[0]["FCONTROLTASKTYPE"].ToString())
                    {
                        case "1":
                            dbo.ExceSQL("UPDATE ST_CELL SET FCELLSTATUS = 1 WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + " and FCELLCODE = '" + dv[0]["FENDCELL"] + "')");
                            break;
                        case "2":
                            dbo.ExceSQL("UPDATE ST_CELL SET FCELLSTATUS =0 WHERE (FLaneWay=" + dv[0]["FSTARTDEVICE"] + " and FCELLCODE = '" + dv[0]["FSTARTCELL"] + "')");
                            break;
                        case "3":
                            dbo.ExceSQL("UPDATE ST_CELL SET FCELLSTATUS = 1 WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + " and FCELLCODE = '" + dv[0]["FENDCELL"] + "')");
                            dbo.ExceSQL("UPDATE ST_CELL SET FCELLSTATUS =0 WHERE (FLaneWay=" + dv[0]["FSTARTDEVICE"] + " and FCELLCODE = '" + dv[0]["FSTARTCELL"] + "')");
                            break;
                        default:
                            break;
                    }

                }
                //20101028
                string dtime = DateTime.Now.ToString("u");//20101028
                dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                dbo.ExceSQL("update T_Manage_Task set FSTATUS=999,FENDTIME='" + dtime + "'  where  FID=" + fid + " and F_ManageTaskKindIndex= " + mti);
                //20101028
             //   dbo.ExecuteSql("INSERT INTO T_Manage_Task_BAK SELECT * FROM T_Manage_Task where  FID=" + fid + " and F_ManageTaskKindIndex<>1");
                
                dbo.ExceSQL("delete from T_Manage_Task   where  FID=" + fid + " and F_ManageTaskKindIndex= " + mti);
                //FrmMain.FormInstance.notifyIcon1.BalloonTipText = "系统提示" + cap + "调度任务索引：" + fid + "已经搬运完成！";
                //FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(5000, "系统提示", "【" + cap + "】" + "调度任务索引：" + fid + "已经搬运完成！", System.Windows.Forms.ToolTipIcon.Info);
            }
            catch (Exception ex)
            {//20100127
                throw ex;
            }
            finally
            {//20100127
                dv = null;
            }

        }
        public static int GetDeviceKindIdx(int devIdx)
        {
            try
            {
                
                string strSql = "SELECT F_DeviceIndex, F_DeviceKindIndex FROM T_Base_Device WHERE F_DeviceIndex=" + devIdx;
                DataSet ds = dbo.ExceSQL(strSql);
                DataView dv = ds.Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_DeviceKindIndex"]);
                }
                else
                    return 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static int GetManageTaskIndexfromMonitor(int monitorIdx)
        {
            //20100127
            DataView dv;
            try
            {//20100127
                dv = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIdx + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_ManageTaskIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {//20100127
                throw ex;
            }
            finally
            {//20100127
                dv = null;
            }
        }
        public static int GetManageTaskKindIndexFromMonitor(int monitorIdx)
        {
           //20100127
            DataView dv;
            try
            {//20100127
                dv = dbo.ExceSQL("SELECT F_ManageTaskKindIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIdx + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {//20100127
                dv = null;
            }
        }
        public static int GetDeviceOrderFromMonitor(int MonitorIndex)
        {
            //20100127
            DataView dv;
            try
            {
                string sql = "select F_DeviceCommandIndex from T_Monitor_Task where (F_DeviceCommandIndex IS NOT NULL) and F_MonitorIndex=" + MonitorIndex;
                //20100127
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_DeviceCommandIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {//20100127
                dv = null;
            }
        }
        public static int GetExceptionNOFromManageTask(int FID, int ManTaskKind)
        {
            //20100127
            DataTable dt;
            try
            {
                string sql = "SELECT FID, F_ManageTaskKindIndex, FExceptionNO FROM T_Manage_Task WHERE (FID = " + FID + ") AND (F_ManageTaskKindIndex = " + ManTaskKind + ") ";
                //20100127
                dt = dbo.ExceSQL(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["FExceptionNO"] == DBNull.Value)
                    {
                        return -1;
                    }
                    else
                    {

                        return Convert.ToInt32(dt.Rows[0]["FExceptionNO"]);
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {//20100127
                throw ex;
            }
            finally
            {//20100127
                dt = null;
            }

        }
        static int GetDeviceIndexFromAgvActive(int AgvActive)
        {
            //20100127AGV
            DataView dva;
            try
            {
                //20100127
                dva = dbo.ExceSQL("SELECT F_AGVGateDeviceIndex,F_Active, F_Address FROM T_Base_AGV_Gate WHERE (F_Active = " + AgvActive + ") ").Tables[0].DefaultView;
                if (dva.Count > 0)
                {
                    return Convert.ToInt32(dva[0]["F_AGVGateDeviceIndex"]);
                }
                else
                {
                    return 0;
                }
            }
            
            catch (Exception ex)
            {//20100127
                throw ex;
            }
            finally
            {//20100127
                dva = null;
            }
        }
        static int GetDeviceIndexFromAgvAddress(int AgvAddress)
        {
            //20100127AGV
            DataView dva;
            try
            {
                //20100127
                dva = dbo.ExceSQL("SELECT F_AGVGateDeviceIndex,F_Active, F_Address FROM T_Base_AGV_Gate WHERE (F_Address = " + AgvAddress + ") ").Tables[0].DefaultView;
                if (dva.Count > 0)
                {
                    return Convert.ToInt32(dva[0]["F_AGVGateDeviceIndex"]);
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {//20100127
                throw ex;
            }
            finally
            {//20100127
                dva = null;
            }
        }
    }
}
