using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DBFactory;
using CommLayerFactory;
using ICommLayer;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 通用函数类库
    /// </summary>
    public class CCommonFunction
    {
        string _DisassembleTaskError="";
        public string DisassembleTaskError
        {
            get { return _DisassembleTaskError; }
            set { _DisassembleTaskError = value; }
        }
        DBOperator dboM = CStaticClass.dboM;
        DBOperator dbo = CStaticClass.dbo;
        Model.MDevice devinfo;
        public CCommonFunction()
        {

        }
        #region 拆分设备指令
        /// <summary>
        /// 创建设备指令是否成功
        /// 
        /// 生成设备指令单信息:由F_AssociateDeviceIndex分解预先执行任务;由F_Orders分解当前任务
        /// F_AssociateDeviceIndex的内容"8-6;7-1"表示先执行设备8的6命令,然后执行设备7的1命令
        /// F_Orders的内容"5;2;6"表示先执行当前设备的5命令,然后2命令,然后6命令
        /// </summary>
        /// <param name="drv">指定F_RouteKindIndex的T_Base_Route_Detail表的行视图</param>
        /// <param name="managerTaskIndex">管理索引</param>
        /// <param name="managerTaskKindIndex">管理类型</param>
        /// <returns></returns>
        public bool CreateMonitorTask(DataRowView drv, int managerTaskIndex, int managerTaskKindIndex)
        {
            
            try
            {
                char[] cc = new char[1];
                cc[0] = ';';
                char[] ccc = new char[1] { '-'};
                string[] Orders = drv["F_Orders"].ToString().Split(cc);
                int MonitorIndex = 0;
                DataView dv;
                DataView dvM;
                int[] coo = new int[6];
                int[] Agvcoo = new int[6];
                string strparm,sql;
                int _endnode, _iotype;
                string strIn;
                string[] bdevorder;
                #region 判断是否有阻挡设备和命令存在
                string bo = GetBlockDevice(Convert.ToInt32(drv["F_DetailIndex"]));
                if ((bo != null) && (bo!= ""))
                {
                    //判断同一个managerTaskIndex, managerTaskKindIndex不可能有一个以上的相同的设备和命令
                    sql = "SELECT F_ManageTaskIndex, F_ManageTaskKindIndex, F_DetailIndex FROM T_Monitor_Task Where F_ManageTaskIndex=" + managerTaskIndex + " and F_ManageTaskKindIndex=" + managerTaskKindIndex + " and F_DeviceIndex=" + Convert.ToInt32(bo[0]) + " and F_DeviceCommandIndex=" + Convert.ToInt32(bo[1]);
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }
                    bdevorder = bo.Split(ccc);
                    MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                    if (MonitorIndex > 0)
                    {
                        strIn = "INSERT INTO T_Monitor_Task " +
                            "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                            " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime) VALUES " +
                            "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt32(bdevorder[0])
                            + "," + Convert.ToInt32(bdevorder[1]) + ",0,0,0,'" + DateTime.Now + "')";
                        dbo.ExceSQL(strIn);
                        
                    }
                    else
                    {
                        
                        this._DisassembleTaskError = "分解设备指令时，无法获得设备指令索引！";
                        return false;
                    }
                }
                #endregion
                #region 判断是否有提前触发设备和命令存在
                bo = GetAheadTriggerDevice(Convert.ToInt32(drv["F_DetailIndex"]));
                if ((bo != null) && (bo != ""))
                {
                    //判断同一个managerTaskIndex, managerTaskKindIndex不可能有一个以上的相同的设备和命令
                    sql = "SELECT F_ManageTaskIndex, F_ManageTaskKindIndex, F_DetailIndex FROM T_Monitor_Task Where F_ManageTaskIndex=" + managerTaskIndex + " and F_ManageTaskKindIndex=" + managerTaskKindIndex + " and F_DeviceIndex=" + Convert.ToInt32(bo[0]) + " and F_DeviceCommandIndex=" + Convert.ToInt32(bo[1]);
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }
                    bdevorder = bo.Split(ccc);
                    MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                    if (MonitorIndex > 0)
                    {
                        strIn = "INSERT INTO T_Monitor_Task " +
                            "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                            " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime) VALUES " +
                            "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt32(bdevorder[0])
                            + "," + Convert.ToInt32(bdevorder[1]) + ",0,0,0,'" + DateTime.Now + "')";
                        dbo.ExceSQL(strIn);

                    }
                    else
                    {

                        this._DisassembleTaskError = "分解设备指令时，无法获得设备指令索引！";
                        return false;
                    }
                }
                #endregion
                #region 关联设备和命令处理
                
                
                string ao = this.GetAssociateDevice(Convert.ToInt32( drv["F_DetailIndex"]));
                if ((ao != null) && (ao!= ""))
                {
                    //判断同一个managerTaskIndex, managerTaskKindIndex不可能有一个以上的相同的设备和命令
                    sql = "SELECT F_ManageTaskIndex, F_ManageTaskKindIndex, F_DetailIndex FROM T_Monitor_Task Where F_ManageTaskIndex=" + managerTaskIndex + " and F_ManageTaskKindIndex=" + managerTaskKindIndex + " and F_DeviceIndex=" + Convert.ToInt32(ao[0]) + " and F_DeviceCommandIndex=" + Convert.ToInt32(ao[1]);
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }
                    bdevorder = ao.Split(ccc);
                    MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                    if (MonitorIndex > 0)
                    {
                        strIn = "INSERT INTO T_Monitor_Task " +
                            "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                            " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime) VALUES " +
                            "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt32(bdevorder[0])
                            + "," + Convert.ToInt32(bdevorder[1]) + ",0,0,0,'" + DateTime.Now + "')";
                        dbo.ExceSQL(strIn);

                    }
                    else
                    {
                        
                        this._DisassembleTaskError = "分解设备指令时，无法获得设备指令索引！";
                        return false;
                    }
                }
                #endregion
                #region 设备和命令组
                for (int i = Orders.GetLowerBound(0); i <= Orders.GetUpperBound(0); i++)
                {
                    //判断同一个managerTaskIndex, managerTaskKindIndex不可能有一个以上的相同的设备和命令
                    sql = "SELECT F_ManageTaskIndex, F_ManageTaskKindIndex, F_DetailIndex FROM T_Monitor_Task Where F_ManageTaskIndex=" + managerTaskIndex + " and F_ManageTaskKindIndex=" + managerTaskKindIndex + " and F_DeviceIndex=" + Convert.ToInt32(drv["F_DeviceIndex"]) + " and F_DeviceCommandIndex=" + Convert.ToInt32(Orders[i]);
                    dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }

                    //根据堆垛机设备索引和出入库类型查询出取货和送货ｘ、ｙ、ｚ坐标
                    if (GetDeviceKindIdx(Convert.ToInt32(drv["F_DeviceIndex"])) == 1)
                    {
                        //在T_Base_StackInfo表判断货叉是单叉还是双叉；单进伸还是双进伸
                        //

                        coo = GetCoordinate(drv, managerTaskIndex, managerTaskKindIndex);
                        ////////
                        if (coo == null)
                        {
                            this._DisassembleTaskError = "分解堆垛机任务时，无法获得堆垛机设备的取、送地址坐标！";
                            //dbo.TransRollback();
                            return false;
                        }
                        MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        if (MonitorIndex > 0)
                        {
                            
                            strIn = "INSERT INTO T_Monitor_Task " +
                                "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                                " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6) VALUES " +
                                "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                                + "," + Convert.ToInt16(Orders[i]) + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now +
                                "'," + coo[0] + "," + coo[1] + "," + coo[2] + "," + coo[3] + "," + coo[4] + "," + coo[5] + ")";
                            dbo.ExceSQL(strIn);
                        }
                        else
                        {
                            //dbo.TransRollback();
                            this._DisassembleTaskError = "分解堆垛机任务时，无法获得设备指令索引！";
                            return false;
                        }
                    }

                    else if (GetDeviceKindIdx(Convert.ToInt32(drv["F_DeviceIndex"])) == 6)
                    {//ＡＧＶ取得起始地址和结束位置，分别写到F_NumParam2，F_NumParam5
                        Agvcoo = GetAGVCoordinate(drv, managerTaskIndex, managerTaskKindIndex);
                        //////
                        if (Agvcoo == null)
                        {
                            this._DisassembleTaskError = "分解AGV任务时，无法获得AGV设备的取、送地址坐标！";
                            //dbo.TransRollback();
                            return false;
                        }
                        MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        if (MonitorIndex > 0)
                        {
                            strIn = "INSERT INTO T_Monitor_Task " +
                                "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                                " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6) VALUES " +
                                "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                                + "," + Convert.ToInt16(Orders[i]) + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now +
                                "'," + Agvcoo[0] + "," + Agvcoo[1] + "," + Agvcoo[2] + "," + Agvcoo[3] + "," + Agvcoo[4] + "," + Agvcoo[5] + ")";
                            dbo.ExceSQL(strIn);
                        }
                        else
                        {
                            this._DisassembleTaskError = "分解ＡＧＶ任务时，无法获得设备指令索引！";
                            //dbo.TransRollback();
                            return false;
                        }
                    }
                    else if (GetDeviceKindIdx(Convert.ToInt32(drv["F_DeviceIndex"])) == 4)
                    {//RGV取得起始地址和结束位置，分别写到F_NumParam2，F_NumParam5
                        Agvcoo = GetRGVCoordinate(drv, managerTaskIndex, managerTaskKindIndex);
                        //////
                        if (Agvcoo == null)
                        {
                            this._DisassembleTaskError = "分解RGV任务时，无法获得RGV设备的取、送地址坐标！";
                            //dbo.TransRollback();
                            return false;
                        }
                        MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        if (MonitorIndex > 0)
                        {
                            strIn = "INSERT INTO T_Monitor_Task " +
                                "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                                " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6) VALUES " +
                                "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                                + "," + Convert.ToInt16(Orders[i]) + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now +
                                "'," + Agvcoo[0] + "," + Agvcoo[1] + "," + Agvcoo[2] + "," + Agvcoo[3] + "," + Agvcoo[4] + "," + Agvcoo[5] + ")";
                            dbo.ExceSQL(strIn);
                        }
                        else
                        {
                            this._DisassembleTaskError = "分解RGV任务时，无法获得设备指令索引！";
                            //dbo.TransRollback();
                            return false;
                        }
                    }
                    else if (GetDeviceKindIdx(Convert.ToInt32(drv["F_DeviceIndex"])) == 7)
                    {//条码比对003：在IO_CONTROLDETAIL表读取条码到F_TxtParam字段
                        strparm = GetStringParm(managerTaskIndex, managerTaskKindIndex, "003");
                        if (strparm == "")
                        {
                            this._DisassembleTaskError = "调度任务没有给条码设备下达条码比对信息！";
                            //dbo.TransRollback();
                            return false;
                        }
                        MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        if (MonitorIndex > 0)
                        {
                            strIn = "INSERT INTO T_Monitor_Task " +
                                "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                                " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime,F_TxtParam) VALUES " +
                                "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                                + "," + Convert.ToInt16(Orders[i]) + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now + "','" + strparm + "')";
                            dbo.ExceSQL(strIn);
                        }
                        else
                        {
                            //dbo.TransRollback();
                            this._DisassembleTaskError = "分解条码比对任务时，无法获得设备指令索引！";
                            return false;
                        }
                    }
                    else if (GetDeviceKindIdx(Convert.ToInt32(drv["F_DeviceIndex"])) == 17)
                    {//码盘机器人
                        MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        if (MonitorIndex > 0)
                        {
                            strIn = "INSERT INTO T_Monitor_Task " +
                                "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                                " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime) VALUES " +
                                "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                                + "," + Convert.ToInt16(Orders[i]) + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now + "')";
                            dbo.ExceSQL(strIn);


                        }
                        else
                        {
                            this._DisassembleTaskError = "分解设备指令时，无法获得设备指令索引！";
                            return false;
                        }
                        ////判断是否为最后一个货物码盘任务,如果是就追加一个Orders[i].Substring(0,1)+"2"的任务
                        //if (IFLastStackPalletTask(managerTaskKindIndex, managerTaskIndex) == true)
                        //{
                        //    MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        //    if (MonitorIndex > 0)
                        //    {
                        //        strIn = "INSERT INTO T_Monitor_Task " +
                        //            "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                        //            " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime) VALUES " +
                        //            "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                        //            + "," + Convert.ToInt16(Orders[i].Substring(0, 1) + "2") + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now + "')";
                        //        dbo.ExceSQL(strIn);
                        //    }
                        //    else
                        //    {
                        //        this._DisassembleTaskError = "分解设备指令时，无法获得设备指令索引！";
                        //        return false;
                        //    }
                        //}

                    }

                    else
                    {

                        //获得指定调度任务的设备指令索引
                        //命令字为“－１”的是虚命令，不生成设备指令
                        if (Convert.ToInt16(Orders[i]) == -1)
                        {
                            if (CStaticClass.RouteSearchMode == "1")
                            {
                                dvM = dbo.ExceSQL("SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE, FENDDEVICE FROM T_Manage_Task where FID=" + managerTaskIndex + " and F_ManageTaskKindIndex=" + managerTaskKindIndex).Tables[0].DefaultView;
                                if (dvM.Count > 0)
                                {
                                    dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + managerTaskIndex
                                    + " and F_ManageTaskKindIndex=" + managerTaskKindIndex);
                                    _endnode = Convert.ToInt32(dvM[0]["FENDDEVICE"]);
                                    _iotype = Convert.ToInt32(GetIOType(dvM[0]["FCONTROLTASKTYPE"].ToString()));
                                    StepsRouteSearch(false, managerTaskIndex, managerTaskKindIndex, _iotype, Convert.ToInt32(drv["F_DeviceIndex"]), _endnode);
                                }
                            }

                            continue;
                        }
                        MonitorIndex = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);
                        if (MonitorIndex > 0)
                        {
                            strIn = "INSERT INTO T_Monitor_Task " +
                                "(F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex,  F_MonitorTaskLevel, F_DeviceIndex," +
                                " F_DeviceCommandIndex,F_DetailIndex,F_Status, F_DeviceStateIndex, F_StartTime) VALUES " +
                                "(" + managerTaskIndex + "," + managerTaskKindIndex + "," + MonitorIndex + ",1," + Convert.ToInt16(drv["F_DeviceIndex"])
                                + "," + Convert.ToInt16(Orders[i]) + "," + Convert.ToInt16(drv["F_DetailIndex"]) + ",0,0,'" + DateTime.Now + "')";
                            dbo.ExceSQL(strIn);

                        }
                        else
                        {
                            //dbo.TransRollback();
                            this._DisassembleTaskError = "分解设备指令时，无法获得设备指令索引！";
                            return false;
                        }
                    }
                }
                
                return true;
                #endregion
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "创建设备指令失败！" + ex.Message;
                //dbo.TransRollback();
                throw ex;
                //return false;
            }
        }
        /// <summary>
        /// 获得绑定在主设备的探物光电设备索引
        /// </summary>
        /// <param name="devinx">主设备索引</param>
        /// <returns></returns>
        public string GetBindingDeviceIndex(int devinx)
        {
            //20101118
            devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
            if (devinfo.BindingDevice == null) return "";
            return devinfo.BindingDevice;
        }
        /// <summary>
        /// 获得输送机设备的出库口探物光电的设备索引值
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        public string  GetBindingDeviceIndexOut(int devinx)
        {
            //20101118
            devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
            if (devinfo.BindingDeviceOut == null) return "";
            return devinfo.BindingDeviceOut;
        }
        /// <summary>
        /// 发送设备的送出指令时，需要检测的光电开关设备索引
        /// </summary>
        /// <param name="devinx">输送设备索引</param>
        /// <returns></returns>
        public  string  GetSendOutDetect(int devinx)
        {
            //20101118
            devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
            if (devinfo.SendOutDetect==null) return "";
            return devinfo.SendOutDetect;

        }
        public string GetBeDetectedDevices(int devinx)
        {
            devinfo= Model.CGetInfo.GetDeviceInfo(devinx);
            return devinfo.BeDetected;
            //string sql = "SELECT F_BeDetected FROM T_Base_Device WHERE (F_DeviceIndex = " + devinx + ") and F_BeDetected is not null";
            //DataView db = dbo.ExceSQL(sql).Tables[0].DefaultView;
            //if (db.Count > 0)
            //{
            //    return db[0]["F_BeDetected"].ToString();
            //}
            //else
            //    return "";
        }
        public int GetUpAndDownDevices(int devinx,int DB1Address)//20101220
        {
            string sql =string.Format( "SELECT F_DeviceIndex FROM T_Base_Device WHERE (F_DeviceIndex != {0}) and F_DBW1Address ={1}",devinx,DB1Address);
            object ob = dbo.GetSingle(sql);
            if (ob != null)
            {
                return Convert.ToInt32(ob);
            }
            else
            {
                return -1;
            }

        }
        public string GetIfCorrelDoubleFork(int devinx)//20101220
        {
 
            devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
            if (devinfo == null)
            {
                return "0";
            }
            else
            {
                return devinfo.IfCorrelDoubleFork;
            }

        }
        /// <summary>
        /// //获得指定调度任务的设备指令索引
        /// </summary>
        /// <param name="managerTaskIndex"></param>
        /// <param name="managerTaskKindIndex"></param>
        /// <returns>设备指令索引值１－－32000</returns>
        public int GetMonitorIndex(int managerTaskIndex, int managerTaskKindIndex)
        {
            //20100108
            DataView dvMt;
            try
            {
                int maxIdx = 0;
                string sql = "SELECT F_MonitorIndex FROM T_Base_Monitor_Task_Index";
                //20100108
                dvMt = dbo.ExceSQL(sql).Tables[0].DefaultView;

                if (dvMt.Count > 0 && dvMt[0]["F_MonitorIndex"] != DBNull.Value)
                {

                    maxIdx = (Convert.ToInt32(dvMt[0]["F_MonitorIndex"]) + 1);

                    if (maxIdx >= 32000)//预留2000个给接近上限的拆分任务
                    {
                        maxIdx = 1;

                    }

                }
                else//现在没有该管理的设备指令记录
                {
                    maxIdx = 1;
                }

                //判断调度任务表是否有重复值
                if (IFExitMonitorIndex(maxIdx) == true)
                {
                    UpdateMonitorIndex(maxIdx);
                    maxIdx = GetMonitorIndex(managerTaskIndex, managerTaskKindIndex);

                }

                UpdateMonitorIndex(maxIdx);
                return maxIdx;
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "获得指定调度任务的设备指令索引失败！" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dvMt = null;
            }

        }
        public void UpdateMonitorIndex(int MonitorIndex)
        {
            dbo.ExceSQL("update T_Base_Monitor_Task_Index set F_MonitorIndex=" + MonitorIndex );
        }
        /// <summary>
        /// 计算该路径的设备占用情况和路径和
        /// [0]路径索引[1]设备被占用数量[2]路径和
        /// </summary>
        /// <param name="dv"></param>
        /// <returns>[0]路径索引[1]设备被占用数量[2]路径和</returns>
        public int[] SearchRoute(DataRow dr)
        {
            int[] sr = new int[3] { 0, 0, 0 };
            //找到被停用的设备
            string sql1 = "SELECT T_Base_Device.F_DeviceIndex " +
            " FROM T_Base_Device,T_Base_Route_Detail  where  T_Base_Device.F_DeviceIndex = T_Base_Route_Detail.F_DeviceIndex " +
            " and T_Base_Device.F_LockedState =-1  AND  T_Base_Route_Detail.F_RouteKindIndex = " + Convert.ToInt32(dr["F_RouteKindIndex"]);
            DataSet ds1 = dbo.ExceSQL(sql1);
            DataView dv1 = ds1.Tables[0].DefaultView;
            if (dv1.Count > 0)
            {
                sr[1] = -1;
                return sr;
            }

            string sql = "SELECT COUNT(T_Base_Device.F_DeviceIndex) AS Expr1" +
            " FROM T_Base_Device,T_Base_Route_Detail  where  T_Base_Device.F_DeviceIndex = T_Base_Route_Detail.F_DeviceIndex " +
            " and T_Base_Device.F_LockedState > 0  AND  T_Base_Route_Detail.F_RouteKindIndex = " + Convert.ToInt32(dr["F_RouteKindIndex"]) +
            " GROUP BY T_Base_Device.F_LockedState,T_Base_Route_Detail.F_RouteKindIndex";
            DataSet ds = dbo.ExceSQL(sql);
            DataView dv = ds.Tables[0].DefaultView;
            sr[0] = Convert.ToInt32(dr["F_RouteKindIndex"]);
            if (dv.Count > 0)
            {
                sr[1] = Convert.ToInt32(dv[0]["Expr1"]);
            }
            else
            {
                sr[1] = 0;
            }
            //路径和
            sr[2] = 0;
            return sr;
        }
        public int GetLaneWay(int StackDeviceIndex)
        {
            DataView dv = dbo.ExceSQL("SELECT F_LaneDeviceIndex FROM T_Base_LaneInfo WHERE (F_StackIndex = " + StackDeviceIndex + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0][0]);
            }
            else
            {
                return -1;
            }
        }

        public string GetStackCoordinateFromLaneGate(int Laneway, int device)
        {
            DataView dv = dbo.ExceSQL("SELECT F_ZXY FROM T_Base_Lane_Gate WHERE (F_LaneGateDeviceIndex = "+device+") AND (F_LaneIndex = "+Laneway +")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return dv[0][0].ToString();
            }
            else
            {
                return "-";
            }
        }

        /// <summary>
        /// 在调度任务中根据堆垛机设备索引和出入库类型查询出取货和送货ｚ-ｘ-ｙ坐标
        /// 出库或者入库在T_Base_Lane_Gate表中获得一部分；盘库直接在调度任务获得全部
        /// </summary>
        /// <param name="drv">调度任务行视图</param>
        /// <param name="managerTaskIndex">调度任务索引</param>
        /// <param name="managerTaskKindIndex">调度任务类型</param>
        /// <returns>取货和送货ｚ-ｘ-ｙ坐标</returns>
        public int[] GetCoordinate(DataRowView drv, int managerTaskIndex, int managerTaskKindIndex)
        {
            string FIntoStepOK;
            if (CStaticClass.RouteSearchMode == "0")
            {
                FIntoStepOK = "FIntoStepOK=0";
            }
            else if (CStaticClass.RouteSearchMode == "1")
            {
                FIntoStepOK = "FIntoStepOK=1";
            }
            else
            {
                FIntoStepOK = "FIntoStepOK=0";
            }

            string sql = "select * from T_Manage_Task WHERE " +
                " (FID=" + managerTaskIndex + ") and ("+FIntoStepOK+")  and (F_ManageTaskKindIndex=" + managerTaskKindIndex + ")";
            DataSet ds = dbo.ExceSQL(sql);
            DataView dv = ds.Tables[0].DefaultView;
            DataSet dsm;
            DataSet dsl;
            DataSet dsdev;

            int[] rt = new int[6];
            if (dv.Count > 0)
            {
                int IOtype = 0;
                string iot = GetIOType(dv[0]["FCONTROLTASKTYPE"].ToString());
                if (iot == "")
                {
                    _DisassembleTaskError = "调度任务中的搬运任务类型在监控搬运任务类型表中没有记忆！";
                    return null;
                }
                if (iot.Length == 2)
                {
                    iot = iot.Substring(1);
                }
                IOtype = Convert.ToInt32(iot);
                //20100305
                char[] cc = new char[1] { '-' };
                string[] split;
                switch (IOtype)
                {
                    case 1 ://入库：找堆垛机上一个设备索引（F_RouteDetailIndex值小于它之中最大的那个）
                        dsm = dbo.ExceSQL("select max(F_RouteDetailIndex) as maxx from t_base_route_detail,T_Base_Device,T_Base_Device_Kind  " +
                            " where T_Base_Route_Detail.F_DeviceIndex = T_Base_Device.F_DeviceIndex and  F_RouteDetailIndex <" +
                            Convert.ToInt32(drv["F_RouteDetailIndex"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]) +
                            " and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Kind.F_DeviceKindIndex and F_GoodsMoveKindIndex = 1");
                        if (dsm.Tables[0].DefaultView.Count > 0)
                        {
                            dsdev = dbo.ExceSQL("select F_DeviceIndex from t_base_route_detail" +
                            " where F_RouteDetailIndex =" + Convert.ToInt32(dsm.Tables[0].DefaultView[0]["maxx"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]));
                            if (dsdev.Tables[0].DefaultView.Count > 0)
                            {
                                //T_Base_Lane_Gate中找到取货地址坐标
                                dsl = dbo.ExceSQL("select * from T_Base_Lane_Gate where F_LaneGateDeviceIndex=" + Convert.ToInt32(dsdev.Tables[0].DefaultView[0]["F_DeviceIndex"]));
                                if (dsl.Tables[0].DefaultView.Count > 0)
                                {
                                    //20100305
                                    split = dsl.Tables[0].DefaultView[0]["F_ZXY"].ToString().Split(cc);

                                    rt[0] = Convert.ToInt32(split[0]);//排Z
                                    rt[1] = Convert.ToInt32(split[1]);//列X
                                    rt[2] = Convert.ToInt32(split[2]);//层Y
                                    //20100305

                                }
                                else
                                    return null;
                            }
                            else
                                return null;

                        }
                        else
                            return null;

                        //FENDCELL送货坐标
                        cc[0] = '-';
                        split = dv[0]["FENDCELL"].ToString().Split(cc);
                        for (int i = 0; i <= 2; i++)
                        {
                            rt[i + 3] = Convert.ToInt32(split[i]);
                        }

                        break;
                    case 2 ://出库：找堆垛机下一个设备索引（F_RouteDetailIndex值大于它之中最小的那个）
                        dsm = dbo.ExceSQL("select min(F_RouteDetailIndex) as mmin from t_base_route_detail,T_Base_Device,T_Base_Device_Kind  " +
                            " where T_Base_Route_Detail.F_DeviceIndex = T_Base_Device.F_DeviceIndex and  F_RouteDetailIndex >" +
                            Convert.ToInt32(drv["F_RouteDetailIndex"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]) +
                            " and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Kind.F_DeviceKindIndex and F_GoodsMoveKindIndex = 1");
                        if (dsm.Tables[0].DefaultView.Count > 0)
                        {
                            dsdev = dbo.ExceSQL("select F_DeviceIndex from t_base_route_detail" +
                            " where F_RouteDetailIndex =" + Convert.ToInt32(dsm.Tables[0].DefaultView[0]["mmin"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]));
                            if (dsdev.Tables[0].DefaultView.Count > 0)
                            {
                                //T_Base_Lane_Gate中找到送货地址坐标
                                dsl = dbo.ExceSQL("select * from T_Base_Lane_Gate where F_LaneGateDeviceIndex=" + Convert.ToInt32(dsdev.Tables[0].DefaultView[0]["F_DeviceIndex"]));
                                if (dsl.Tables[0].DefaultView.Count > 0)
                                {
                                    //20100305
                                    split = dsl.Tables[0].DefaultView[0]["F_ZXY"].ToString().Split(cc);

                                    rt[3] = Convert.ToInt32(split[0]);//排Z
                                    rt[4] = Convert.ToInt32(split[1]);//列X
                                    rt[5] = Convert.ToInt32(split[2]);//层Y
                                    //20100305
                                }
                                else
                                    return null;
                            }
                            else
                            {
                                return null;
                            }
                        }
                        else
                            return null;
                        //FSTARTCELL取货坐标
                        cc[0] = '-';
                        split = dv[0]["FSTARTCELL"].ToString().Split(cc);
                        for (int i = 0; i <= 2; i++)
                        {
                            rt[i] = Convert.ToInt32(split[i]);
                        }
                        break;
                    case 3://倒库：直接获得FSTARTCELL取货坐标，FENDCELL送货坐标
                        //FSTARTCELL取货坐标
                        cc[0] = '-';
                        split = dv[0]["FSTARTCELL"].ToString().Split(cc);
                        for (int i = 0; i <= 2; i++)
                        {
                            rt[i] = Convert.ToInt32(split[i]);
                        }
                        //FENDCELL送货坐标
                        cc[0] = '-';
                        split = dv[0]["FENDCELL"].ToString().Split(cc);
                        for (int i = 0; i <= 2; i++)
                        {
                            rt[i + 3] = Convert.ToInt32(split[i]);
                        }
                        break;
                    default://其它
                        break;
                }
                //
                return rt;
            }
            else
                return null;
        }

        public int GetAGVChannelsIndex(int AGVGateDeviceIndex)
        {
            DataView dv = dbo.ExceSQL("SELECT F_ChannelsIndex FROM T_Base_AGV_Gate where F_AGVGateDeviceIndex="+AGVGateDeviceIndex+"").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return  Convert.ToInt32(dv[0][0]);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 获得AGV坐标
        /// </summary>
        /// <param name="drv"></param>
        /// <param name="managerTaskIndex"></param>
        /// <param name="managerTaskKindIndex"></param>
        /// <returns></returns>
        public int[] GetAGVCoordinate(DataRowView drv, int managerTaskIndex, int managerTaskKindIndex)
        {
            try
            {
                string FIntoStepOK;
                if (CStaticClass.RouteSearchMode == "0")
                {
                    FIntoStepOK = "FIntoStepOK=0";
                }
                else if (CStaticClass.RouteSearchMode == "1")
                {
                    FIntoStepOK = "FIntoStepOK=1";
                }
                else
                {
                    FIntoStepOK = "FIntoStepOK=0";
                }
                string sql = "select * from T_Manage_Task WHERE " +
                    " (FID=" + managerTaskIndex + ") and ("+FIntoStepOK +")  and (F_ManageTaskKindIndex=" + managerTaskKindIndex + ")";
                DataSet ds = dbo.ExceSQL(sql);
                DataView dv = ds.Tables[0].DefaultView;
                DataSet dsm;
                DataSet dsl;
                DataSet dsdev;
                int[] rt = new int[6] { 1, 1, 1, 1, 1, 1 };
                string[] addr = null; char[] cc = new char[1] { ';'};
                if (dv.Count > 0)
                {
                    //取货坐标：找AGV上一个设备索引（F_RouteDetailIndex值小于它之中最大的那个）
                    dsm = dbo.ExceSQL("select max(F_RouteDetailIndex) as maxx from t_base_route_detail,T_Base_Device,T_Base_Device_Kind  " +
                                " where T_Base_Route_Detail.F_DeviceIndex = T_Base_Device.F_DeviceIndex and  F_RouteDetailIndex <" +
                                Convert.ToInt32(drv["F_RouteDetailIndex"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]) +
                                " and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Kind.F_DeviceKindIndex and F_GoodsMoveKindIndex = 1");

                    if (dsm.Tables[0].DefaultView.Count > 0)
                    {
                        dsdev = dbo.ExceSQL("select F_DeviceIndex from t_base_route_detail" +
                        " where F_RouteDetailIndex =" + Convert.ToInt32(dsm.Tables[0].DefaultView[0]["maxx"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]));
                        if (dsdev.Tables[0].DefaultView.Count > 0)
                        {
                            //T_Base_ＡＧＶ_Gate中找到取货地址坐标
                            dsl = dbo.ExceSQL("select * from T_Base_AGV_Gate where F_AGVGateDeviceIndex=" + Convert.ToInt32(dsdev.Tables[0].DefaultView[0]["F_DeviceIndex"]));
                            if (dsl.Tables[0].DefaultView.Count > 0)
                            {
                                addr = dsl.Tables[0].DefaultView[0]["F_Address"].ToString().Split(cc);
                                rt[0] = Convert.ToInt32(addr[0]);
                                rt[1] = Convert.ToInt32(addr[1]);
                                rt[2] = Convert.ToInt32(addr[2]);
                            }
                            else
                                return null;
                        }
                        else
                            return null;

                    }
                    else
                        return null;



                    //送货地址坐标:找AGV下一个设备索引（F_RouteDetailIndex值大于它之中最小的那个）
                    dsm = dbo.ExceSQL("select min(F_RouteDetailIndex) as mmin from t_base_route_detail,T_Base_Device,T_Base_Device_Kind  " +
                                " where T_Base_Route_Detail.F_DeviceIndex = T_Base_Device.F_DeviceIndex and  F_RouteDetailIndex >" +
                                Convert.ToInt32(drv["F_RouteDetailIndex"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]) +
                                " and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Kind.F_DeviceKindIndex and F_GoodsMoveKindIndex = 1");

                    if (dsm.Tables[0].DefaultView.Count > 0)
                    {
                        dsdev = dbo.ExceSQL("select F_DeviceIndex from t_base_route_detail" +
                        " where F_RouteDetailIndex =" + Convert.ToInt32(dsm.Tables[0].DefaultView[0]["mmin"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]));
                        if (dsdev.Tables[0].DefaultView.Count > 0)
                        {
                            //T_Base_AGV_Gate中找到送货地址坐标
                            dsl = dbo.ExceSQL("select * from T_Base_AGV_Gate where F_AGVGateDeviceIndex=" + Convert.ToInt32(dsdev.Tables[0].DefaultView[0]["F_DeviceIndex"]));
                            if (dsl.Tables[0].DefaultView.Count > 0)
                            {
                                addr = dsl.Tables[0].DefaultView[0]["F_Address"].ToString().Split(cc);
                                rt[3] = Convert.ToInt32(addr[0]);
                                rt[4] = Convert.ToInt32(addr[1]);
                                rt[5] = Convert.ToInt32(addr[2]);

                            }
                            else
                                return null;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                        return null;

                    return rt;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 获取AGV控制台分配的任务号
        /// </summary>
        /// <param name="monitor">调度任务号</param>
        /// <returns></returns>
        public int GetAGVTask(int monitor)
        {
            DataView dv = dbo.ExceSQL("SELECT F_AgvNo, F_AgvTask FROM T_Monitor_Task WHERE (F_MonitorIndex = "+monitor +")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0]["F_AgvTask"] == DBNull.Value) return -1;
                return Convert.ToInt32(dv[0]["F_AgvTask"]);
            }
            else
            {
                return -1;
            }
        }
        /// <summary>
        /// 获得RGV坐标
        /// </summary>
        /// <param name="drv"></param>
        /// <param name="managerTaskIndex"></param>
        /// <param name="managerTaskKindIndex"></param>
        /// <returns></returns>
        public int[] GetRGVCoordinate(DataRowView drv, int managerTaskIndex, int managerTaskKindIndex)
        {
            try
            {
                string FIntoStepOK;
                if (CStaticClass.RouteSearchMode == "0")
                {
                    FIntoStepOK = "FIntoStepOK=0";
                }
                else if (CStaticClass.RouteSearchMode == "1")
                {
                    FIntoStepOK = "FIntoStepOK=1";
                }
                else
                {
                    FIntoStepOK = "FIntoStepOK=0";
                }
                string sql = "select * from T_Manage_Task WHERE " +
                    " (FID=" + managerTaskIndex + ") and (" + FIntoStepOK + ")  and (F_ManageTaskKindIndex=" + managerTaskKindIndex + ")";
                DataSet ds = dbo.ExceSQL(sql);
                DataView dv = ds.Tables[0].DefaultView;
                DataSet dsm;
                DataSet dsl;
                DataSet dsdev;
                int[] rt = new int[6] { 0, 0, 0, 0, 0, 0 };
                if (dv.Count > 0)
                {
                    //取货坐标：找RGV上一个设备索引（F_RouteDetailIndex值小于它之中最大的那个）
                    dsm = dbo.ExceSQL("select max(F_RouteDetailIndex) as maxx from t_base_route_detail,T_Base_Device,T_Base_Device_Kind  " +
                                " where T_Base_Route_Detail.F_DeviceIndex = T_Base_Device.F_DeviceIndex and  F_RouteDetailIndex <" +
                                Convert.ToInt32(drv["F_RouteDetailIndex"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]) +
                                " and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Kind.F_DeviceKindIndex and F_GoodsMoveKindIndex = 1");

                    if (dsm.Tables[0].DefaultView.Count > 0)
                    {
                        dsdev = dbo.ExceSQL("select F_DeviceIndex from t_base_route_detail" +
                        " where F_RouteDetailIndex =" + Convert.ToInt32(dsm.Tables[0].DefaultView[0]["maxx"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]));
                        if (dsdev.Tables[0].DefaultView.Count > 0)
                        {
                            //T_Base_RGV_Gate中找到取货地址坐标
                            dsl = dbo.ExceSQL("select * from T_Base_RGV_Gate where F_RGVGateDeviceIndex=" + Convert.ToInt32(dsdev.Tables[0].DefaultView[0]["F_DeviceIndex"]));
                            if (dsl.Tables[0].DefaultView.Count > 0)
                            {
                                rt[1] = Convert.ToInt32(dsl.Tables[0].DefaultView[0]["F_Address"]);

                            }
                            else
                                return null;
                        }
                        else
                            return null;

                    }
                    else
                        return null;



                    //送货地址坐标:找RGV下一个设备索引（F_RouteDetailIndex值大于它之中最小的那个）
                    dsm = dbo.ExceSQL("select min(F_RouteDetailIndex) as mmin from t_base_route_detail,T_Base_Device,T_Base_Device_Kind  " +
                                " where T_Base_Route_Detail.F_DeviceIndex = T_Base_Device.F_DeviceIndex and  F_RouteDetailIndex >" +
                                Convert.ToInt32(drv["F_RouteDetailIndex"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]) +
                                " and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Kind.F_DeviceKindIndex and F_GoodsMoveKindIndex = 1");

                    if (dsm.Tables[0].DefaultView.Count > 0)
                    {
                        dsdev = dbo.ExceSQL("select F_DeviceIndex from t_base_route_detail" +
                        " where F_RouteDetailIndex =" + Convert.ToInt32(dsm.Tables[0].DefaultView[0]["mmin"]) + " and F_RouteKindIndex=" + Convert.ToInt32(drv["F_RouteKindIndex"]));
                        if (dsdev.Tables[0].DefaultView.Count > 0)
                        {
                            //T_Base_RGV_Gate中找到送货地址坐标
                            dsl = dbo.ExceSQL("select * from T_Base_RGV_Gate where F_RGVGateDeviceIndex=" + Convert.ToInt32(dsdev.Tables[0].DefaultView[0]["F_DeviceIndex"]));
                            if (dsl.Tables[0].DefaultView.Count > 0)
                            {
                                rt[4] = Convert.ToInt32(dsl.Tables[0].DefaultView[0]["F_Address"]);

                            }
                            else
                                return null;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                        return null;

                    return rt;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        
        /// <summary>
        /// 获得附加信息：取、送坐标；条码比对，承重等
        /// </summary>
        /// <param name="managerTaskIndex"></param>
        /// <param name="managerTaskKindIndex"></param>
        /// <param name="Order"></param>
        /// <returns></returns>
        public string GetStringParm(int managerTaskIndex, int managerTaskKindIndex, string Order)
        {
            try
            {
                DataSet ds = dbo.ExceSQL("select * from IO_CONTROLDETAIL where F_ManageTaskKindIndex="
                    + managerTaskKindIndex + " and FCONTROLID=" + managerTaskIndex + " and FKIND='" + Order + "'");
                DataView dv = ds.Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["FVALUE"] != DBNull.Value)
                        return dv[0]["FVALUE"].ToString();
                }
                return "";
            }
            catch (Exception ex)
            {
                throw ex;
                //return "";
            }
        }
        /// <summary>
        /// 获得搬运路径类型
        /// </summary>
        /// <param name="FCONTROLTASKTYPE">调度任务下发的搬运任务类型</param>
        /// <returns></returns>
        public string GetIOType(string FCONTROLTASKTYPE)
        {
            //20100108
            DataSet ds;
            try
            {
                //20100108
                ds = dbo.ExceSQL("SELECT FCODE, FINTERCODE FROM T_ITEMTASKTYPE where FCODE='" + FCONTROLTASKTYPE + "'");
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    return ds.Tables[0].DefaultView[0]["FINTERCODE"].ToString();
                }
                else
                    return "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds = null;
            }
        }
        /// <summary>
        /// 固定路径搜索
        /// </summary>
        /// <param name="dr">一行管理记录数据</param>
        /// <param name="IOtype">搬运类型</param>
        /// <returns>拆分的记录数</returns>
        public int SettledRouteSearch(DataRowView dr, int IOtype)
        {
            try
            {
                //0，按照最优路径选择固定路线；
                //FSTARTDEVICE起点；FENDDEVICE终点
                int RecCount = 0;
                int managerTaskIndex = Convert.ToInt32(dr["FID"]);
                int managerTaskKindIndex = Convert.ToInt32(dr["F_ManageTaskKindIndex"]);
                string strDetail1 = "select * from V_RouteDetail where F_routeKind=" + IOtype + " and F_DeviceIndex=" + Convert.ToInt32(dr["FSTARTDEVICE"]) + " and F_EndNode='1'  order by F_RouteKindIndex asc ";
                DataSet dsDetail1 = dbo.ExceSQL(strDetail1);
                DataView dvDetail1 = dsDetail1.Tables[0].DefaultView;
                string strDetail2 = "";
                DataSet dsDetail2 = new DataSet();
                DataView dvDetail2 = new DataView();
                int[] Isearch = new int[3] { 0, 0, 0 };//Isearch[0]代表F_RouteKindIndex；Isearch[1]代表设备组被占用的个数；Isearch[2]代表设备组路径和
                List<int[]> mlist = new List<int[]>();
                int min = 0;
                int stationidx;
                if (dvDetail1.Count > 0)
                {
                    #region 找到最优路径
                    //找到多条路径，根据当前设备占用状态和优化路径选择一条最优路径F_RouteKindIndex的唯一值
                    for (int i = 0; i < dvDetail1.Count; i++)
                    {
                        strDetail2 = "select * from V_RouteDetail where F_routeKind=" + IOtype +
                        " and F_RouteKindIndex=" + Convert.ToInt32(dvDetail1[i]["F_RouteKindIndex"])
                        + " and F_DeviceIndex=" + Convert.ToInt32(dr["FENDDEVICE"]) + " and F_EndNode='1' order by F_RouteKindIndex asc ";
                        dsDetail2 = dbo.ExceSQL(strDetail2);
                        dvDetail2 = dsDetail2.Tables[0].DefaultView;
                        if (dvDetail2.Count > 0)
                        {


                            for (int j = 0; j < dvDetail2.Count; j++)
                            {
                                //返回该路径的设备占用情况和路径和
                                Isearch = SearchRoute(dvDetail2[j].Row);
                                if (Isearch[1] == -1) continue;
                                //如果FSTARTDEVICE起点或者FENDDEVICE终点是巷道，
                                //需要根据FSTARTCELL起点或者FENDCELL计算采用１＃或者２＃站台
                                if ((GetDeviceKindIdx(Convert.ToInt32(dr["FENDDEVICE"])) == 10) && ((Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 3) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 4) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 7) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 8)))
                                {
                                    stationidx = GetStationIdx(dr["FENDCELL"].ToString());
                                    if (IFContainStation(stationidx, Isearch[0]) == true)
                                    {
                                        mlist.Add(Isearch);
                                    }

                                }
                                //else if ((GetDeviceKindIdx(Convert.ToInt32(dr["FSTARTDEVICE"])) == 10) && (Convert.ToInt32(dr["FENDDEVICE"]) == 12))
                                //{
                                //    stationidx = GetStationIdx(dr["FSTARTCELL"].ToString());
                                //    if (IFContainStation(stationidx, Isearch[0]) == true)
                                //    {
                                //        mlist.Add(Isearch);
                                //    }

                                //}
                                else
                                {
                                    mlist.Add(Isearch);
                                }

                            }


                        }
                        else
                        {
                            continue;
                        }

                    }
                    //计算mlist里的设备占有数最小值
                    if (mlist.Count == 0)
                    {
                        _DisassembleTaskError = "在路径明细表中没有检索到终点记录！";
                        return 0;
                    }
                    int oo = mlist[0][1];//设备被用数量
                    min = mlist[0][0];//路径索引

                    foreach (int[] a in mlist)
                    {
                        if (a[1] == -1) continue;
                        if (a[1] < oo)
                        {

                            min = a[0];

                        }

                    }

                    #endregion


                    #region 监控分解任务

                    //根据F_RouteKindIndex的值在T_Base_Route_Detail表中分解任务
                    DataSet dsRK = dbo.ExceSQL("select * from T_Base_Route_Detail where F_RouteKindIndex=" + min + " order by F_RouteDetailIndex asc ");
                    DataView dvRK = dsRK.Tables[0].DefaultView;
                    if (dvRK.Count > 0)
                    {
                        dbo.TransBegin();
                        try
                        {
                            for (int k = 0; k < dvRK.Count; k++)
                            {
                                //生成设备指令单信息:由F_AssociateDeviceIndex分解预先执行任务;由F_Orders分解当前任务
                                //F_AssociateDeviceIndex的内容"8-6;7-1"表示先执行设备8的6命令,然后执行设备7的1命令
                                //F_Orders的内容"5;2;6"表示先执行当前设备的5命令,然后2命令,然后6命令
                                if (CreateMonitorTask(dvRK[k], managerTaskIndex, managerTaskKindIndex) == true)
                                {
                                    RecCount++;
                                }
                                else
                                {
                                    dbo.TransRollback();
                                    return 0;
                                }
                            }


                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                            dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + managerTaskIndex
                            + " and F_ManageTaskKindIndex=" + managerTaskKindIndex);
                            dbo.TransCommit();
                            //刷新监控显示列表RefreshControlMonitor
                            if (CStaticClass.RealRefresh == true)
                            {
                                FrmControlMonitor.FormInstance.MonitorRefresh(
                                    dbo.ExceSQL("select * from V_Monitor_Task where "+CStaticClass.Monstatus).Tables[0].DefaultView);
                            }
                        }
                        catch (Exception ex)
                        {
                            dbo.TransRollback();
                            throw ex;
                        }
                    }

                    #endregion
                    return RecCount;

                }
                else
                {
                    _DisassembleTaskError = "在路径明细表中没有检索到起点记录！";
                    return 0;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 查看用户指定的任务优先级原则：0，按照调度任务优先级；1，入库优先，携带符合执行条件的出库任务；
        /// 2，出库优先，携带符合执行条件的入库任务；3，单纯入库优先，执行完所有入库任务后再执行出库任务；
        /// 4，单纯出库优先，执行完所有出库任务后再执行入库任务。
        /// </summary>
        /// <returns>优先级索引值0--4</returns>
        public int SelectTaskPriPrecept()
        {
            //20100108
            DataView dv;
            try
            {
                string sql = "SELECT F_PRINo , F_PRIName , F_IfChecked FROM T_Base_PRI WHERE (F_IfChecked = '1')";
                //20100108
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_PRINo"]);
                }
                else
                {
                    return 0;//默认值0：按照调度任务优先级
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108

                dv=null;

            }
        }

        public int GetLaneWayFromLaneInfo(int stackIndex)
        {
            DataView dv = dbo.ExceSQL("SELECT F_LaneDeviceIndex FROM T_Base_LaneInfo WHERE (F_StackIndex = "+stackIndex+")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0][0]);
            }
            else
            {
                return -1;
            }

        }

        /// <summary>
        /// 每个正在工作的节点作为起始点，向末端节点重新搜索下一个最优路径的节点
        /// </summary>
        /// <param name="IfStartNode">是否是起始节点设备</param>
        /// <param name="manageFid">调度任务索引</param>
        /// <param name="manageKindIndex">调度任务类型索引</param>
        /// <param name="ioType">搬运路径类型</param>
        /// <param name="nowDevice">正在工作的节点设备</param>
        /// <param name="endDevice">路径末端节点设备</param>
        /// <returns>拆分记录数</returns>
        public int StepsRouteSearch(bool IfStartNode, int manageFid,int manageKindIndex,int ioType,int nowDevice,int endDevice)
        {

            //1，每个正在工作的节点作为起始点，向末端节点重新搜索下一个最优路径的节点
            //FSTARTDEVICE起点；FENDDEVICE终点
            int RecCount = 0;
            int managerTaskIndex = manageFid;
            int managerTaskKindIndex = manageKindIndex;

            string sql11 = "select * from T_Manage_Task WHERE " +
                    " (FID=" + managerTaskIndex + ") " +
                    " and (F_ManageTaskKindIndex=" + managerTaskKindIndex + ") order by F_ManageTaskKindIndex desc,FID asc";
            DataView dv11 = dbo.ExceSQL(sql11).Tables[0].DefaultView;
            DataRow dr;
            if (dv11.Count > 0)
            {
                dr = dv11[0].Row ;
            }
            else
            {
                return 0;
            }

            string strDetail1 = "select * from V_RouteDetail where F_routeKind=" + ioType + " and F_DeviceIndex=" + nowDevice + "  order by F_RouteKindIndex asc ";
            DataSet dsDetail1 = dbo.ExceSQL(strDetail1);
            DataView dvDetail1 = dsDetail1.Tables[0].DefaultView;
            string strDetail2 = "";
            DataSet dsDetail2 = new DataSet();
            DataView dvDetail2 = new DataView();
            int[] Isearch = new int[3] { 0, 0, 0 };//Isearch[0]代表F_RouteKindIndex；Isearch[1]代表设备组被占用的个数；Isearch[2]代表设备组路径和
            List<int[]> mlist = new List<int[]>();
            int min = 0;
            int stationidx;
            if (dvDetail1.Count > 0)
            {
                #region 找到最优路径
                //找到多条路径，根据当前设备占用状态和优化路径选择一条最优路径F_RouteKindIndex的唯一值
                for (int i = 0; i < dvDetail1.Count; i++)
                {
                    strDetail2 = "select * from V_RouteDetail where F_routeKind=" + ioType +
                    " and F_RouteKindIndex=" + Convert.ToInt32(dvDetail1[i]["F_RouteKindIndex"])
                    + " and F_DeviceIndex=" + endDevice + " and F_EndNode='1' order by F_RouteKindIndex asc";
                    dsDetail2 = dbo.ExceSQL(strDetail2);
                    dvDetail2 = dsDetail2.Tables[0].DefaultView;
                    if (dvDetail2.Count > 0)
                    {
                        

                        for (int j = 0; j < dvDetail2.Count; j++)
                        {
                            //返回该路径的设备占用情况和路径和
                            Isearch = SearchRoute(dvDetail2[j].Row);
                            if (Isearch[1] == -1) continue;
                            //如果FSTARTDEVICE起点或者FENDDEVICE终点是巷道，
                            //需要根据FSTARTCELL起点或者FENDCELL计算采用１＃或者２＃站台
                            if ((GetDeviceKindIdx(Convert.ToInt32(dr["FENDDEVICE"])) == 10) && ((Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 3) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 4) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 5) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 6) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 7) || (Convert.ToInt32(dvDetail2[0]["F_RouteKindIndex"]) == 8)))
                            {
                                stationidx = GetStationIdx(dr["FENDCELL"].ToString());
                                if (IFContainStation(stationidx, Isearch[0]) == true)
                                {
                                    mlist.Add(Isearch);
                                }

                            }
                            else if ((GetDeviceKindIdx(Convert.ToInt32(dr["FSTARTDEVICE"])) == 10) && (Convert.ToInt32(dr["FENDDEVICE"]) == 12))
                            {
                                stationidx = GetStationIdx(dr["FSTARTCELL"].ToString());
                                if (IFContainStation(stationidx, Isearch[0]) == true)
                                {
                                    mlist.Add(Isearch);
                                }

                            }
                            else
                            {
                                mlist.Add(Isearch);
                            }
                        }
                        
                    }
                    else
                    {
                        continue;
                    }

                }
                //计算mlist里的设备占有数最小值
                if (mlist.Count == 0)
                {
                    _DisassembleTaskError = "在路径明细表中没有检索到终点记录！";
                    return 0;
                }
                int oo = mlist[0][1];//设备被用数量
                min = mlist[0][0];//路径索引

                foreach (int[] a in mlist)
                {

                    if (a[1] == -1) continue;
                    if (a[1] < oo)
                    {
                        min = a[0];
                    }

                }

                        #endregion

                #region 监控分解任务
                string sql, strsql;
                if (IfStartNode == true)
                {//是起始节点设备
                    sql = "select * from T_Base_Route_Detail where F_RouteKindIndex=" + min + " order by F_RouteDetailIndex asc ";
                }
                else
                {//正在执行的中间环节设备，需要找到此路径的下一个设备
                    //找到F_RouteDetailIndex值比当前值大的之中最小的那一个设备
                    strsql = "select F_RouteKindIndex,F_RouteDetailIndex,F_DeviceIndex from T_Base_Route_Detail where F_RouteKindIndex=" + min + " and F_DeviceIndex=" + nowDevice + " order by F_RouteDetailIndex asc ";
                    DataSet dss = dbo.ExceSQL(strsql);
                    DataView dvv = dss.Tables[0].DefaultView;
                    if (dvv.Count > 0)
                    {
                        sql = "select * from T_Base_Route_Detail where F_Orders<>'-1' and  F_RouteKindIndex=" + min + " and F_RouteDetailIndex>" + Convert.ToInt32(dvv[0]["F_RouteDetailIndex"]) + " order by F_RouteDetailIndex asc ";
                    }
                    else//如何判断路径结束？？？？
                    {
                        return 9999;
                    }
                }
                //根据F_RouteKindIndex的值在T_Base_Route_Detail表中分解任务
                DataSet dsRK = dbo.ExceSQL(sql);
                DataView dvRK = dsRK.Tables[0].DefaultView;
                if (dvRK.Count > 0)
                {

                    //dbo.TransBegin();
                    try
                    {
                        //生成设备指令单信息:由F_AssociateDeviceIndex分解预先执行任务;由F_Orders分解当前任务
                        //F_AssociateDeviceIndex的内容"8-6;7-1"表示先执行设备8的6命令,然后执行设备7的1命令
                        //F_Orders的内容"5;2;6"表示先执行当前设备的5命令,然后2命令,然后6命令
                        if (CreateMonitorTask(dvRK[0], managerTaskIndex, managerTaskKindIndex) == true)
                        {
                            RecCount++;
                        }
                        else
                        {
                            //dbo.TransRollback();
                            return 0;
                        }
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + managerTaskIndex
                        + " and F_ManageTaskKindIndex=" + managerTaskKindIndex);
                        //dbo.TransCommit();
                        //刷新监控显示列表RefreshControlMonitor
                        if (CStaticClass.RealRefresh == true)
                        {
                            FrmControlMonitor.FormInstance.MonitorRefresh(
                                dbo.ExceSQL("select * from V_Monitor_Task where "+CStaticClass.Monstatus).Tables[0].DefaultView);
                        }
                    }
                    catch (Exception ex)
                    {
                        //dbo.TransRollback();
                        throw ex;
                    }
                    if ((Convert.ToInt32(dvRK[0]["F_DeviceIndex"]) == endDevice) && (dvRK[0]["F_EndNode"].ToString() == "1"))
                    {
                        return 9999;
                    }
                }
                else
                {
                    return 9999;
                }
                #endregion
                return RecCount;

            }
            else
            {
                _DisassembleTaskError = "在路径明细表中没有检索到起点记录！";
                return 0;
            }


        }
        /// <summary>
        /// 根据货架编号获得入库站台信息
        /// </summary>
        /// <param name="site"></param>
        /// <returns></returns>
        public int GetStationIdx(string site)
        {
            char[] cc = new char[1] { '-' };
            string[] split = site.Split(cc);
            int ll = Convert.ToInt32(split[1]);
            DataView dv = dbo.ExceSQL("SELECT F_StationIndex, F_StartSite, F_EndSite FROM T_Base_Station_Site where F_StartSite<=" + ll + " and F_EndSite>=" + ll ).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_StationIndex"]);
            }
            else
            {
                return -1;
            }
        }
        /// <summary>
        /// rkindIdx的所有详细路径信息记录中是否包含stationDevIdx
        /// </summary>
        /// <param name="stationDevIdx"></param>
        /// <param name="rkindIdx"></param>
        /// <returns></returns>
        public bool IFContainStation(int stationDevIdx, int rkindIdx)
        {
            return dbo.Exists("SELECT F_DeviceIndex, F_RouteKindIndex FROM T_Base_Route_Detail where F_DeviceIndex=" + stationDevIdx + " and F_RouteKindIndex="+rkindIdx);
        }
        /// <summary>
        /// 判断调度任务号在队列中是否存在，true已经存在；false不存在
        /// </summary>
        /// <param name="Monitorindex"></param>
        /// <returns></returns>
        public bool IFExitMonitorIndex(int Monitorindex)
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + Monitorindex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;
            }
        }
    
        /// <summary>
        /// 20101220 是否存在该设备指令 
        /// </summary>
        /// <param name="deviceindex">设备索引</param>
        /// <param name="Monitorindex">设备指令</param>
        /// <returns></returns>
        public int GetEndTransDevice(int deviceindex, int Monitorindex)
        {
            object ob = dbo.GetSingle("SELECT  F_NumParam4  FROM T_Monitor_Task WHERE (F_MonitorIndex = " + Monitorindex + ") And (F_DeviceIndex = " + deviceindex + ")");
            if (ob != null)
            {
                return Convert.ToInt32(ob);
            }
            else
            {

                return 0;
            }
        }
        //20101220
        public string  GetBarCodeFromMonitor(int Monitorindex)
        {
            object ob = dbo.GetSingle("SELECT  F_TxtParam  FROM T_Monitor_Task WHERE (F_MonitorIndex = " + Monitorindex + ")");
            if (ob != null)
            {
                return ob.ToString();
            }
            else
            {

                return "0";
            }
        }
        public bool IFExitTempManageIndex(int fid)
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT fid FROM T_Manage_Task WHERE (F_ManageTaskKindIndex=2 and fid = " + fid + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {//20100108
            throw ex;
        }
        finally
        {//20100108
            dv = null;
        }
        }
        /// <summary>
        /// 查找需要关联的辅助设备指令索引
        /// </summary>
        /// <param name="mankind">任务类型</param>
        /// <param name="fid">主调度任务索引</param>
        /// <param name="devIdx">设备索引</param>
        /// <param name="devOrder">设备指令</param>
        /// <returns></returns>
        public int GetBeRelativeMonitorIndex(int mankind, int fid,int devIdx,int devOrder)
        {
            DataView dv;
            try
            {
                string sql = "SELECT F_MonitorIndex 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]["F_MonitorIndex"]);
                }
                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 int GetRelativeMainMonitorIndex(int mankind, int fid, int devIdx, int devOrder)
        {
            DataView dv;
            try
            {
                string sql = "SELECT F_MonitorIndex 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 ( 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]["F_MonitorIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }
       
        
        #endregion
        #region 控制设备（发送命令）

        /// <summary>
        /// 根据前面得到的F_MonitorIndex值获得被锁定的设备索引
        /// </summary>
        /// <returns>以“；”隔开的设备索引组字符串</returns>
        public string GetLockedDeviceIndex(int MonitorIndex)
        {
            //20100108
            DataSet ds;
            try
            {
                string sql = "select F_RunningLock from T_Monitor_Task where F_MonitorIndex=" + MonitorIndex;
                //20100108
                ds = dbo.ExceSQL(sql);
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    return ds.Tables[0].DefaultView[0]["F_RunningLock"].ToString();
                }
                else
                    return "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {//20100108
                ds = null;
            }
        }

        /// <summary>
        /// 根据前面得到的MonitorIndex值取得"关联设备索引-命令"
        /// </summary>
        /// <returns>关联设备索引-命令，null表示没有</returns>
        public string GetAssociateDevice(int MonitorIndex)
        {
            //20100108
            DataView dv;
            DataView dvv;
            try
            {
                string sql = "select F_Associate from T_Monitor_Task where (F_Associate IS NOT NULL) and F_MonitorIndex=" + MonitorIndex;

                //20100108
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                    string sql1 = "select F_DeviceIndex,F_DeviceCommandIndex from T_Monitor_Task where F_MonitorIndex=" + dv[0]["F_Associate"];
                    //20100108
                    dvv = dbo.ExceSQL(sql1).Tables[0].DefaultView;
                    if (dvv.Count > 0)
                    {
                        return dvv[0]["F_DeviceIndex"].ToString() + "-" + dvv[0]["F_DeviceCommandIndex"].ToString();
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
                dvv = null;
            }
        }
        /// <summary>
        /// 根据前面得到的MonitorIndex值取得"关联调度任务"
        /// </summary>
        /// <returns>关联调度任务索引，0表示没有</returns>
        public int GetAssociateMonitor(int MonitorIndex)
        {
            //20100108
            DataView dv;
            DataView dvv;
            try
            {
                string sql = "select F_Associate from T_Monitor_Task where (F_Associate IS NOT NULL) and F_MonitorIndex=" + MonitorIndex;
                //20100108
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                    string sql1 = "select F_MonitorIndex from T_Monitor_Task where F_MonitorIndex=" + dv[0]["F_Associate"];
                    //20100108
                    dvv = dbo.ExceSQL(sql1).Tables[0].DefaultView;
                    if (dvv.Count > 0)
                    {
                        return Convert.ToInt32(dvv[0]["F_MonitorIndex"].ToString());
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //20100108
                dv = null;
                dvv = null;
            }
        }

        /// <summary>
        /// 根据前面得到的关联调度任务值取得"调度任务索引"
        /// </summary>
        /// <returns>调度任务索引，0表示没有</returns>
        public int GetMonitorFromAssociate(int AssociateMonitor)
        {
            //20100108
            DataView dv;
            try
            {
                string sql = "select F_MonitorIndex from T_Monitor_Task where  F_Associate=" + AssociateMonitor;
                //20100108
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_MonitorIndex"]);

                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }
        /// <summary>
        /// 根据前面得到的_DetailIndex值取得"阻挡设备索引"-"命令"
        /// </summary>
        /// <returns>阻挡设备索引和命令，null表示没有</returns>
        public string GetBlockDevice(int detailIndex)
        {
            //20100108
            DataSet ds;
            try
            {
                string sql = "select F_BlockDevice from T_Base_Route_Detail where (F_BlockDevice IS NOT NULL) and F_DetailIndex=" + detailIndex;
                //20100108
                ds = dbo.ExceSQL(sql);
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    return ds.Tables[0].DefaultView[0]["F_BlockDevice"].ToString();
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds = null;
            }
        }
        /// <summary>
        /// 根据前面得到的_DetailIndex值取得"提前触发设备索引"-"命令"
        /// </summary>
        /// <returns>提前触发设备索引和命令，null表示没有</returns>
        public string GetAheadTriggerDevice(int detailIndex)
        {
            //20100108
            DataSet ds;
            try
            {
                string sql = "select F_AheadTrigger from T_Base_Route_Detail where (F_AheadTrigger IS NOT NULL) and (F_AheadTrigger <> '') and F_DetailIndex=" + detailIndex;
                //20100108
                ds = dbo.ExceSQL(sql);
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    return ds.Tables[0].DefaultView[0]["F_AheadTrigger"].ToString();
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds = null;
            }
        }
        /// <summary>
        /// 在设备指令信息中获得堆垛机的
        /// 取货点Z坐标（站在堆垛机上，面向操作面板：左侧-1，右侧-2）
        /// 取货点X坐标（沿轨道方向）
        /// 取货点Y坐标（沿高度方向）
        /// 送货点Z坐标（站在堆垛机上，面向操作面板：左侧-1，右侧-2）
        /// 送货点X坐标（沿轨道方向）
        /// 送货点Y坐标（沿高度方向）
        /// </summary>
        /// <param name="TaskIdx">设备指令索引</param>
        /// <returns>0--5六个数组分别依次代表６个坐标</returns>
        public int[] GetCoordinatesFromMonitorTask(int TaskIdx)
        {
            //20100108
            DataView dv;
            int[] gc;
            try
            {
                //20100108
                dv = dbo.ExceSQL("select * from T_Monitor_Task where F_MonitorIndex=" + TaskIdx).Tables[0].DefaultView;
                gc = new int[6];

                
                //F_NumParam1--z,x--2,y--3;F_NumParam4--z,5--x,6--y
                if (dv.Count > 0)
                {
                    gc[0] = Convert.ToInt32(dv[0]["F_NumParam1"]);
                    gc[1] = Convert.ToInt32(dv[0]["F_NumParam2"]);
                    gc[2] = Convert.ToInt32(dv[0]["F_NumParam3"]);
                    gc[3] = Convert.ToInt32(dv[0]["F_NumParam4"]);
                    gc[4] = Convert.ToInt32(dv[0]["F_NumParam5"]);
                    gc[5] = Convert.ToInt32(dv[0]["F_NumParam6"]);
                    return gc;
                }
                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
                gc = null;
            }
        }
        /// <summary>
        /// 获得设备类型索引
        /// </summary>
        /// <param name="devIdx">设备索引</param>
        /// <returns>设备类型索引</returns>
        public int GetDeviceKindIdx(int devIdx)
        {
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(devIdx);
                return devinfo.DeviceKind;
                //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;
            }
        }
        
        /// <summary>
        /// 在调度队列中找到设备命令
        /// </summary>
        /// <param name="MonitorIndex">调度所引</param>
        /// <returns></returns>
        public 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;
            }
        }
        /// <summary>
        /// 码盘区请求空托盘
        /// </summary>
        /// <param name="DeviceIndex">码盘区工位设备索引</param>
        public void AskBlankPallet(int DeviceIndex)
        {

        }
        /// <summary>
        /// 成功发送命令后的处理信息
        /// </summary>
        /// <param name="taskKindIndex">调度任务类型</param>
        /// <param name="Managefid">调度任务索引</param>
        /// <param name="MonirotIdx">设备指令索引</param>
        /// <param name="deviceidx">设备索引</param>
        /// <param name="detailidx">详细路径步骤索引</param>
        public void SendOrderSuccess(int taskKindIndex, int Managefid, int MonirotIdx, int deviceidx, int detailidx)
        {
            string AssociateDevice = "";//关联设备
            string LockedDeviceIndex = "";//被锁定的设备索引组，以“；”分隔
            char[] sep = new char[1];
            string[] split;
            DataView dvs;
            try
            {
                int devKind = GetDeviceKindIdx(deviceidx);
                int order = GetDeviceOrderFromMonitor(MonirotIdx);


                //8：更改作业记录的状态F_Status为1,更改设备为占用状态（T_Base_device的F_LockedState=设备指令单）

                string dtime = DateTime.Now.ToString("u");//20110603
                dtime = dtime.Substring(0, dtime.Length - 1);
                dbo.ExceSQL("update T_Monitor_Task set F_StartTime='" + dtime + "',F_Status=1,F_SendCount=F_SendCount+1 where F_Status=0 and F_MonitorIndex=" + MonirotIdx);//20100905
                if (taskKindIndex != 4)//20100610
                {
                    //20101220AGV和输送机送出指令不需要锁定设备
                    if (devKind != 5 && devKind != 6 && (devKind != 2 && order != 6))
                    {
                        dbo.ExceSQL("update T_Base_device set F_LockedState=" + MonirotIdx +
                            " where   F_DeviceIndex=" + deviceidx + "");
                    }
                    #region 20101220注释
                    
                    //else
                    //{
                    //    //完成应答3
                    //    if (order == 3)
                    //    {
                    //        string[] df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(MonirotIdx, 1001);
                    //        //bool snyc = Model.CGeneralFunction.DoubleForkIfSync(MonirotIdx, 1001, 6);
                    //        Model.CGeneralFunction.ActionComplete(1001, MonirotIdx, 0);
                    //        #region 双叉关联任务，能同步的同时报告完成；异步的直接执行关联的命令
                    //        //20100323
                    //        devinfo = Model.CGetInfo.GetDeviceInfo(1001);
                    //        if ((devinfo.IfCorrelDoubleFork == "1") && (df != null))//20100702
                    //        {

                    //            //if (snyc == true)//20100702
                    //            //{
                    //                Model.CGeneralFunction.ActionComplete(1001, Convert.ToInt32(df[0]), 0);
                                    

                    //            //}
                                
                    //        }
                    //        #endregion
                            

                    //    }
                    //    else
                    //    {
                    //        dvs = dbo.ExceSQL("SELECT F_AgvNo FROM T_Monitor_Task WHERE (F_AgvNo IS NOT NULL) AND (F_MonitorIndex = " + MonirotIdx + ")").Tables[0].DefaultView;
                    //        if (dvs.Count > 0)
                    //        {
                    //            dbo.ExceSQL("update T_Base_device set F_LockedState=" + MonirotIdx +
                    //               " where   F_DeviceIndex=" + dvs[0][0] + "");
                    //        }
                    //    }
                    //}
                    #endregion
                }
                if (devKind == 1)
                {
                    //修改T_Manage_Task的FLANEWAY，FSTACK
                    //20100108
                    dvs = dbo.ExceSQL("SELECT F_LaneDeviceIndex,F_StackIndex  FROM T_Base_LaneInfo where F_StackIndex=" + deviceidx + "").Tables[0].DefaultView;
                    int laneway = 0;
                    if (dvs.Count > 0)
                    {
                        laneway = Convert.ToInt32(dvs[0]["F_LaneDeviceIndex"]);

                    }
                    dbo.ExceSQL("update T_Manage_Task set FLANEWAY=" + laneway + ",FSTACK=" + deviceidx + " where F_ManageTaskKindIndex=" + taskKindIndex + " and FID=" + Managefid);

                }
                if (taskKindIndex != 4)
                {
                    //如果是RGV、堆垛机的将取（运行）命令需要增加调度任务预约锁F_ManTaskReserve   && (order == 7))  && ((order == 2) || (order == 4))
                    if ((devKind == 4)  || (devKind == 1) )//20100610
                    {////RGV运到到输送机//堆垛机将取
                        dbo.ExceSQL("UPDATE T_Base_Device SET F_ManTaskReserve = " + (taskKindIndex.ToString() + Managefid.ToString()) + " WHERE (F_DeviceIndex = " + deviceidx + ")");
                    }
                }
                //9：给调度任务表回写调度任务IO_Control的正在执行状态FSTATUS=1;T_Manage_Task的正在执行状态FSTATUS=1
                dbo.ExceSQL("update T_Manage_Task set FSTATUS='1' where F_ManageTaskKindIndex=" + taskKindIndex + " and FID=" + Managefid);
                if (taskKindIndex == 1)//调度任务
                {
                    //20100905聊城RFID比对发送时，不修改调度任务状态
                    if ((devinfo.DeviceIndex == 1605) || (devinfo.DeviceIndex == 1606) || (devinfo.DeviceIndex == 1607) || (devinfo.DeviceIndex == 1608))
                    {
                    }
                    else
                    {
                        dboM.ExceSQL("update IO_Control set Control_STATUS=" + Model.CGeneralFunction.TASKRUN + " where Control_ID=" + Managefid + " and Control_STATUS<>" + Model.CGeneralFunction.TASKRUN + " and Control_STATUS<>" + Model.CGeneralFunction.TASKSINGLEFORKRUN + " ");//20110504
                    }
                }
                //10:调度任务表里的F_RunningLock所有对应设备索引加锁，但是F_AssociateDeviceIndex关联设备不加锁
                AssociateDevice = GetAssociateDevice(MonirotIdx);
                if (AssociateDevice == "") AssociateDevice = null;
                if (AssociateDevice != null)
                {
                    sep[0] = '-';
                    split = AssociateDevice.Split(sep);
                    AssociateDevice = split[0];
                }

                sep[0] = ';';
                LockedDeviceIndex = GetLockedDeviceIndex(MonirotIdx);
                if (LockedDeviceIndex != "")
                {
                    split = LockedDeviceIndex.Split(sep);
                    for (int m = split.GetLowerBound(0); m <= split.GetUpperBound(0); m++)
                    {
                        dbo.ExceSQL("update T_Base_device set F_LockedState=" + MonirotIdx +
                            " where F_DeviceIndex=" + Convert.ToInt32(split[m]) + "and F_DeviceIndex<>" + Convert.ToInt32(AssociateDevice));
                    }
                }
                //20110416
                //叠盘申请离开的任务在发送成功后立即完成
                if (deviceidx == 34002 || deviceidx == 24001)
                {

                    Model.CGeneralFunction.ActionComplete(deviceidx, MonirotIdx, 0);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sep =null;
                split=null;
                dvs=null ;
            }
            
            
        }
        public 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 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;
        
            }

        
        }
        public int GetManageIDFromManageTask(int taskKindIndex, int Managefid)
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT FMANAGEID FROM T_Manage_Task WHERE (FID = " + Managefid + ") AND (F_ManageTaskKindIndex = " + taskKindIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["FMANAGEID"] == DBNull.Value) return -1;
                    return Convert.ToInt32(dv[0]["FMANAGEID"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;

            }
        }
        public int GetFCONTROLTASKTYPEFromManageTask(int taskKindIndex, int Managefid)
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                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)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;

            }
        }
        /// <summary>
        /// 在调度任务表获得最大码盘数量
        /// </summary>
        /// <param name="taskKindIndex">调度任务类型</param>
        /// <param name="Managefid">调度任务索引</param>
        /// <param name="ManageID">ManageID</param>
        /// <returns></returns>
        public int GetMaxGoodsAmountFromManageTask(int taskKindIndex, int Managefid, int ManageID)
        {
            DataView dv = dbo.ExceSQL("SELECT FREMARK FROM T_Manage_Task WHERE (FID = " + Managefid + ") AND (F_ManageTaskKindIndex = "+taskKindIndex+") AND (FMANAGEID = "+ManageID+")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["FREMARK"]);
            }
            else
            {
                return 0;
            }
        }
        public bool IFCanStackPallet(int ManageID,int DeviceOrder)
        {
            DataView dv = dbo.ExceSQL("SELECT * FROM T_BASE_STACK_ROBOT WHERE ((F_ManageID IS NULL) or (F_ManageID=" + ManageID + ") or (F_ManageID=0)) and F_DeviceOrder=" + DeviceOrder + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool IFLastStackPalletTask(int taskKindIndex, int Managefid)
        {
            DataView dv = dbo.ExceSQL("SELECT FREMARK FROM T_Manage_Task WHERE (FID = "+ Managefid  +") AND (F_ManageTaskKindIndex = "+taskKindIndex +") AND (FREMARK = '1')").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 是否需要优化调度
        /// </summary>
        /// <param name="DeviceIdx"></param>
        /// <returns></returns>
        public bool NeedOptimize(int DeviceIdx)
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT F_DeviceIndex, F_NeedOptimize FROM T_Base_Device where F_DeviceIndex=" + DeviceIdx + " and  F_NeedOptimize='1'").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;

            }
        }
        /// <summary>
        /// 根据设备指令索引MonitorIndex检索出需要向T_Monitor_Task_Child插入的纪录，并且完成插入工作
        /// </summary>
        /// <param name="MonitorIndex"></param>
        public void InsertMonitorOptimizeChildTask(int MonitorIndex)
        {
            try
            {//20100108
                //起始x坐标，列-沿轨道方向
                // 起始y坐标，层-高度方向
                // 起始z坐标，排-面向堆垛机操作面板，1-左侧，2-右侧
                //F_NumParam1--z,x--2,y--3;F_NumParam4--z,5--x,6--y
                string sql;
                int[] childInfo = GetMonitorChildIndex(MonitorIndex);
                sql = "INSERT INTO T_Monitor_Task_Child(F_Child_Index, F_TargetX, F_TargetY, F_TargetZ, F_OriginX, F_OriginY, F_OriginZ, F_Order,F_DeviceKindIndex,F_DummyDeviceIndex,F_MonitorIndex, F_Status)" +
                    "VALUES (" + childInfo[0] + "," + childInfo[2] + "," + childInfo[3] + "," + childInfo[1] + "," + childInfo[5] + "," + childInfo[6] + "," + childInfo[4] + "," + childInfo[7] + "," + childInfo[8] + "," + childInfo[9] + "," + MonitorIndex + ",0,)";
                dbo.ExceSQL(sql);
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
        }
        
        /// <summary>
        /// //获得需要优化调度设备指令的子任务索引
        ///conInfo[9]=设备索引 ;
        ///conInfo[8]=设备种类索引 ;
        ///conInfo[7]=命令 ;
        ///conInfo[1] = ["F_NumParam1"];
        ///conInfo[2] = ["F_NumParam2"];
        ///conInfo[3] = ["F_NumParam3"];
        ///conInfo[4] = ["F_NumParam4"];
        ///conInfo[5] = ["F_NumParam5"];
        ///conInfo[6] = ["F_NumParam6"];
        /// </summary>
        /// <param name="monitorTaskIndex"></param>
        /// <returns>子任务索引值１－－６５５３５</returns>
        public int[] GetMonitorChildIndex(int monitorTaskIndex)
        {
            //20100108
            DataView dvMt;
            int[] conInfo = new int[10];
            DataView dv;

            try
            {
                int devKindIndex;

                //20100108
                dv = dbo.ExceSQL("SELECT T_Base_Device.F_DeviceIndex,T_Base_Device.F_DeviceKindIndex,T_Monitor_Task.F_DeviceCommandIndex," +
                    "F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task" +
                    " WHERE (T_Monitor_Task.F_MonitorIndex = " + monitorTaskIndex + ") and " +
                    " (T_Monitor_Task.F_DeviceIndex = T_Base_Device.F_DeviceIndex)").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    devKindIndex = Convert.ToInt32(dv[0]["F_DeviceKindIndex"]);
                    conInfo[9] = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                    conInfo[8] = devKindIndex;
                    conInfo[7] = Convert.ToInt32(dv[0]["F_DeviceCommandIndex"]);
                    conInfo[1] = Convert.ToInt32(dv[0]["F_NumParam1"]);
                    conInfo[2] = Convert.ToInt32(dv[0]["F_NumParam2"]);
                    conInfo[3] = Convert.ToInt32(dv[0]["F_NumParam3"]);
                    conInfo[4] = Convert.ToInt32(dv[0]["F_NumParam4"]);
                    conInfo[5] = Convert.ToInt32(dv[0]["F_NumParam5"]);
                    conInfo[6] = Convert.ToInt32(dv[0]["F_NumParam6"]);
                }
                else
                {

                    return null;
                }
                string sql = "SELECT F_Child_Index FROM T_Monitor_Task_Child_Index";
                //20100108
                dvMt = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvMt.Count > 0 && dvMt[0]["F_Child_Index"] != DBNull.Value)
                {
                    int maxIdx;
                    maxIdx = (Convert.ToInt32(dvMt[0]["F_Child_Index"]) + 1);
                    if (maxIdx >= 64000)
                    {
                        UpdateMonitorChildIndex(Convert.ToInt32(devKindIndex.ToString() + "0" + "1"));
                        conInfo[0] = Convert.ToInt32(devKindIndex.ToString() + "0" + "1");
                        return conInfo;
                    }
                    else
                    {
                        UpdateMonitorChildIndex(maxIdx);
                        conInfo[0] = maxIdx;
                        return conInfo;
                    }
                }
                else//现在没有该设备指令子任务记录
                {
                    UpdateMonitorIndex(Convert.ToInt32(devKindIndex.ToString() + "0" + "1"));
                    conInfo[0] = Convert.ToInt32(devKindIndex.ToString() + "0" + "1");
                    return conInfo;
                }
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "获得指定调度任务的设备指令索引失败！" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dv = null;
                dvMt = null;
                conInfo = null;
            }

        }
        public void UpdateMonitorChildIndex(int MonitorChildIndex)
        {
            dbo.ExceSQL("update T_Monitor_Task_Child_Index set F_Child_Index=" + MonitorChildIndex);
        }
        /// <summary>
        /// 增加对表T_Monitor_Task_Child的监控，产生不同设备优选算法，完成优化调度
        /// 优化原则：调度路径和最小者（空闲设备的当前位置与起始位置的“路径模差”的绝对值 
        /// 加上 起始位置与终点位置的“路径模差”的绝对值
        /// 路径模差：此路径上总共有n个站点，如果（n1-n2）的绝对值大于或等于(n/2),则
        /// 路径模差=Math.Abs(n1-n2）-n；否则，路径模差=Math.Abs（n1-n2）
        /// </summary>
        public void OptimizeControlDevice()
        {
            
        }

        /// <summary>
        /// 获得设备指令任务的关联对等设备索引：堆垛机的取货指令任务的取货站台的双叉对等关联站台
        /// 返回值“-1”表示无关联站台；“0”表示自关联站台；其它值表示关联站台设备索引
        /// </summary>
        /// <param name="MonitorTask">设备指令索引</param>
        /// <param name="DeviceIndex">设备索引</param>
        /// <returns></returns>
        public int GetCorrel_DeviceIndex(int MonitorTask)
        {

            int[] zxy = GetCoordinatesFromMonitorTask(MonitorTask);
            string zxystr = "";
            if (zxy != null)
            {
                zxystr = (zxy[0].ToString().Length == 1 ? "0" + zxy[0].ToString() : zxy[0].ToString()) + "-" +
                    ((zxy[1].ToString().Length == 1) ? ("0" + zxy[1].ToString()) : (zxy[1].ToString())) + "-" +
                    ((zxy[2].ToString().Length == 1) ? ("0" + zxy[2].ToString()) : (zxy[2].ToString()));
                DataView dv = dbo.ExceSQL("SELECT F_LaneGateDeviceIndex,F_CorrelDeviceIndex FROM T_Base_Lane_Gate where (T_Base_Lane_Gate.F_ZXY = '" + zxystr + "')").Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                    if (dv[0]["F_LaneGateDeviceIndex"].ToString() == dv[0]["F_CorrelDeviceIndex"].ToString())
                    {
                        return 0;
                    }
                    else
                    {
                        return int.Parse(dv[0]["F_CorrelDeviceIndex"].ToString());
                    }
                }
            }
            return -1;
        }
        /// <summary>
        /// 根据设备指令索引获得设备信息：【0】设备索引【1】顶升高位检测【2】顶升低位检测
        /// 【3】有物检测【4】运行监测【5】近巷道2列有物检测【6】远巷道1列有物检测【7】是否使用远货叉【8】关联设备索引
        /// </summary>
        /// <param name="MonitorTask"></param>
        /// <returns></returns>
        public string[] GetCorrel_DeviceInfo(int MonitorTask)
        {
            string[] rr = new string[9];

            int[] zxy = GetCoordinatesFromMonitorTask(MonitorTask);
            string zxystr = "";
            if (zxy != null)
            {
                zxystr = (zxy[0].ToString().Length == 1 ? "0" + zxy[0].ToString() : zxy[0].ToString()) + "-" +
                    ((zxy[1].ToString().Length == 1) ? ("0" + zxy[1].ToString()) : (zxy[1].ToString())) + "-" +
                    ((zxy[2].ToString().Length == 1) ? ("0" + zxy[2].ToString()) : (zxy[2].ToString()));
                DataView dv = dbo.ExceSQL("SELECT * FROM T_Base_Lane_Gate where (T_Base_Lane_Gate.F_ZXY = '" + zxystr + "')").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    rr[0] = dv[0]["F_LaneGateDeviceIndex"].ToString();
                    rr[1] = dv[0]["F_HighDetect"].ToString();
                    rr[2] = dv[0]["F_LowDetect"].ToString();
                    rr[3] = dv[0]["F_HavingDetect"].ToString();
                    rr[4] = dv[0]["F_RunDetect"].ToString();
                    rr[5] = dv[0]["F_NearDetect"].ToString();
                    rr[6] = dv[0]["F_FarDetect"].ToString();
                    rr[7] = dv[0]["F_UseAwayFork"].ToString();
                    rr[8] = dv[0]["F_CorrelDeviceIndex"].ToString();
                    return rr;
                }

            }
            return null;
        }
        public string[] GetCorrelOther_DeviceInfo(int device)
        {
            string[] rr = new string[9];

            
                DataView dv = dbo.ExceSQL("SELECT * FROM T_Base_Lane_Gate where (F_LaneIndex=1801 and T_Base_Lane_Gate.F_LaneGateDeviceIndex = " + device + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    rr[0] = dv[0]["F_LaneGateDeviceIndex"].ToString();
                    rr[1] = dv[0]["F_HighDetect"].ToString();
                    rr[2] = dv[0]["F_LowDetect"].ToString();
                    rr[3] = dv[0]["F_HavingDetect"].ToString();
                    rr[4] = dv[0]["F_RunDetect"].ToString();
                    rr[5] = dv[0]["F_NearDetect"].ToString();
                    rr[6] = dv[0]["F_FarDetect"].ToString();
                    rr[7] = dv[0]["F_UseAwayFork"].ToString();
                    rr[8] = dv[0]["F_CorrelDeviceIndex"].ToString();
                    return rr;
                }
                else
            
                    return null;
        }
        /// <summary>
        /// 获得设备索引的关联对等设备索引：堆垛机的取货指令任务的取货站台的双叉对等关联站台或者顶升
        /// 返回值“-1”表示无关联站台；“0”表示自关联站台；其它值表示关联站台设备索引
        /// </summary>
        /// <param name="DeviceIndex"></param>
        /// <returns></returns>
        public int GetCorrel_DeviceIndex(int DeviceIndex, bool ownCorrel)
        {


            return -1;
            DataView dv = dbo.ExceSQL("SELECT F_LaneGateDeviceIndex,F_CorrelDeviceIndex FROM T_Base_Lane_Gate where F_LaneGateDeviceIndex = " + DeviceIndex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {

                if (dv[0]["F_LaneGateDeviceIndex"].ToString() == dv[0]["F_CorrelDeviceIndex"].ToString())
                {
                    return 0;
                }
                else
                {
                    return int.Parse(dv[0]["F_CorrelDeviceIndex"].ToString());
                }
            }

            return -1;
        }
        /// <summary>
        /// 根据设备索引获得关联设备信息：【0】设备索引【1】顶升高位检测【2】顶升低位检测
        /// 【3】有物检测【4】运行监测【5】近巷道2列有物检测【6】远巷道1列有物检测【7】是否使用远货叉【8】关联设备索引【9】顶升中位检测
        /// </summary>
        /// <param name="DeviceIndex">设备索引</param>
        /// <param name="ownCorrel">是否自关联</param>
        /// <returns></returns>
        public string[] GetCorrel_DeviceInfo(int DeviceIndex, bool ownCorrel)
        {
            string[] rr = new string[4];

            // 顶升设备是为普通的输送机处理  2011//11/16
            DataView dv = dbo.ExceSQL("SELECT * FROM T_Base_Lane_Gate  where  F_CorrelDeviceIndex = " + DeviceIndex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                //rr[0] = dv[0]["F_LaneGateDeviceIndex"].ToString();
                //rr[1] = dv[0]["F_HighDetect"].ToString();
                //rr[2] = dv[0]["F_LowDetect"].ToString();
                //rr[3] = dv[0]["F_HavingDetect"].ToString();
                //rr[4] = dv[0]["F_RunDetect"].ToString();
                //rr[5] = dv[0]["F_NearDetect"].ToString();
                //rr[6] = dv[0]["F_FarDetect"].ToString();
                //rr[7] = dv[0]["F_UseAwayFork"].ToString();
                //rr[8] = dv[0]["F_CorrelDeviceIndex"].ToString();
                //rr[9] = dv[0]["F_MiddleDetect"].ToString();//20101220 升降站台中位检测
                rr[0] = dv[0]["F_LaneGateDeviceIndex"].ToString();
                rr[1] = dv[0]["F_HighDetect"].ToString();
                rr[2] = dv[0]["F_LowDetect"].ToString();
                rr[3] = dv[0]["F_CorrelDeviceIndex"].ToString();
               // rr[4] = dv[0]["F_RunDetect"].ToString();

                if (ownCorrel == true)
                {
                    if (dv[0]["F_LaneGateDeviceIndex"].ToString() == DeviceIndex.ToString())
                    {
                        return rr;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return rr;
           
                }
            }


            return null;
        }
       
        /// <summary>
        /// 根据设备指令索引反馈堆垛机的送货坐标是否为极限货位
        /// </summary>
        /// <param name="TaskIdx"></param>
        /// <returns></returns>
        public bool IfLimitCellCode(int TaskIdx)
        {
            int[] zxy = GetCoordinatesFromMonitorTask(TaskIdx);
            //if (zxy != null)
            //{
            //    object ob = dbo.GetSingle("SELECT F_LaneDeviceIndex FROM T_Base_LaneInfo WHERE (F_ForwardLimitX = " + zxy[4] + ") OR (F_BackLimitX =  " + zxy[4] + ")");
            //    if (ob != null)
            //    {
            //        return true;
            //    }

            //}
            return false;
        }

#endregion
        #region 读取设备状态
        public string ShowConveyorError(int ConveyorNo)
        {
            int  DeviceIdx;
            IGetDeviceState gds;
            int[] States;
            DataView dv1 = dbo.ExceSQL("SELECT * FROM T_Base_ConveyorError where F_ConveyorNo=" + ConveyorNo ).Tables[0].DefaultView;
            if (dv1.Count > 0)
            {
                DeviceIdx = Convert.ToInt32(dv1[0]["F_DeviceIndex"]);
            }
            else
            {
                return null;
            }
            gds = CommModeCreate.CreateGetDeviceState(DeviceIdx);
            States = gds.GetDeviceState(DeviceIdx, 64777);//1完成,2任务号,5设备号
            if (States == null)
            {
                return null;
            }
            if ((States[2] != 64777) || (States[5] != DeviceIdx))
            {
                return null;
            }
            DataView dv = dbo.ExceSQL("SELECT * FROM T_Base_ConveyorError where F_ConveyorNo=" + ConveyorNo + " and F_ErrorIndex="+States[1] ).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return dv[0]["F_ErrorName"].ToString();
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 根据ManageID的值把F_GoodsAmount减一，F_GoodsAmount如果大于“０”
        /// </summary>
        /// <param name="ManageID"></param>
        /// <returns>F_GoodsAmount减一的结果</returns>
        public int GetLeftGoodsAmount(int ManageID)
        {
            dbo.ExceSQL("update T_BASE_STACK_ROBOT set F_GoodsAmount=F_GoodsAmount-1 where F_GoodsAmount>0 and F_ManageID="+ManageID+"");
            DataView dv = dbo.ExceSQL("SELECT F_GoodsAmount FROM T_BASE_STACK_ROBOT WHERE (F_ManageID = " + ManageID + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_GoodsAmount"]);
            }
            else
            {
                return -1;
            }
        }
        public int GetStackPalletOrderOver(int ManageID)
        {
            DataView dv = dbo.ExceSQL("SELECT F_DeviceOrder FROM T_BASE_STACK_ROBOT WHERE (F_ManageID = "+ManageID+")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_DeviceOrder"].ToString().Substring(0, 1) + "2");
            }
            else
                return 0;
        }
        public int GetExceptionNOFromManageTask(int FID,int ManTaskKind)
        {
            //20100108
            DataTable dt;
            try
            {
                string sql = "SELECT FID, F_ManageTaskKindIndex, FExceptionNO FROM T_Manage_Task WHERE (FID = " + FID + ") AND (F_ManageTaskKindIndex = " + ManTaskKind + ") ";
                //20100108
                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)
            {
                _DisassembleTaskError = "获得指定调度任务的异常代码：" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dt = null;
                
            }
        }
        
        #endregion
        #region 获得调度任务
        /// <summary>
        /// 获取调度生成的调度任务的索引
        /// </summary>
        /// <returns></returns>
        public int GetTempManageIdx()
        {
            //20100108
            DataSet ds;
            try
            {
                int maxIdx = 10001;
                //20100108
                ds = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Base_Manage_Task_Index_Temp_Task");
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(ds.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1) >= 19998)
                    {
                        maxIdx = 10001;
                    }
                    else
                    {
                        maxIdx = (Convert.ToInt32(ds.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1);
                    }
                }
                else
                {
                    maxIdx = 10001;
                }
                //判断临时调度任务表是否有重复值
                if (IFExitTempManageIndex(maxIdx) == true)
                {
                    RecordMaxTempManageTaskFID(maxIdx);
                    maxIdx = GetTempManageIdx();
                    return maxIdx;
                }

                RecordMaxTempManageTaskFID(maxIdx);
                return maxIdx;
            }
            catch (Exception ex)
            {//20100108
                _DisassembleTaskError = "获得指定调度任务的临时任务索引失败，" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                ds= null;
            }

        }
        /// <summary>
        /// 获得库房索引
        /// </summary>
        /// <returns></returns>
        public string  GetWarehouseIndex()
        {
            //20100108
            DataView dv;
            try
            {
                //20100108
                dv = dbo.ExceSQL("select F_WarehouseIndex from   T_Warehouse").Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                    return dv[0]["F_WarehouseIndex"].ToString();

                }
                else
                {
                    return "1";
                }
            }
            catch (Exception ex)
            {//20100108
                _DisassembleTaskError = "获得指定库房索引失败，" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dv = null;
            }

        }
        /// <summary>
        /// 记录调度生成的调度任务的索引的最大值
        /// </summary>
        /// <param name="fid">调度生成的调度任务的索引</param>
        public void RecordMaxTempManageTaskFID(int fid)
        {//20100108
            DataView dv;
            try
            {//20100108
                dv = dbo.ExceSQL("select F_ManageTaskIndex from T_Base_Manage_Task_Index_Temp_Task").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    //if (fid == 19998)
                    //{
                    //    dbo.ExceSQL("UPDATE T_Base_Manage_Task_Index_Temp_Task SET F_ManageTaskIndex =10001");
                    //    return;
                    //}
                    //if (fid > Convert.ToInt32(dv[0]["F_ManageTaskIndex"]))
                    //{
                    dbo.ExceSQL("UPDATE T_Base_Manage_Task_Index_Temp_Task SET F_ManageTaskIndex =" + fid);
                    return;
                    //}
                }
                else
                {
                    dbo.ExceSQL("INSERT INTO T_Base_Manage_Task_Index_Temp_Task (F_ManageTaskIndex)VALUES (" + fid + ")");
                    return;
                }
            }
            catch (Exception ex)
            {//20100108
                _DisassembleTaskError = "获得记录调度任务最大任务索引失败，" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dv = null;
            }
        }
        /// <summary>
        /// 判断这个货位在ST_CELL是否存在
        /// </summary>
        /// <param name="FWAREHOUSE"></param>
        /// <param name="FLaneWay"></param>
        /// <param name="FCELLCODE"></param>
        /// <returns></returns>
        public bool QueryCellIfExit(string FWAREHOUSE, int FLaneWay, string FCELLCODE)
        {
            
            
            char[] cc = new char[1] { '-' };
            string[] fcc = FCELLCODE.Split(cc);
            if (fcc.GetUpperBound(0) < 2) return false;
            int[] fcci = new int[fcc.GetUpperBound(0) + 1];
            //20100108
            DataView dv;
            try
            {
                for (int i = fcc.GetLowerBound(0); i <= fcc.GetUpperBound(0); i++)
                {
                    fcci[i] = Convert.ToInt32(fcc[i]);
                }
                //20100108
                dv = dbo.ExceSQL("SELECT FWAREHOUSE, FCELLCODE, FCELLSTATUS " +
                        " FROM ST_CELL Where FWAREHOUSE='" + FWAREHOUSE + "'  and FLaneWay=" + FLaneWay + "  and F_Z=" +
                        fcci[0] + " and F_X=" + fcci[1] + " and F_Y=" + fcci[2] + "  ").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {//20100108
                _DisassembleTaskError = "查询货位是否存在失败，" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dv = null;
                cc =null ;
                fcc =null ;
                fcci = null;
            }
        }

        /// <summary>
        /// 查询货位状态是否满足入库或者出库条件
        /// </summary>
        /// <param name="FWAREHOUSE">库房编号</param>
        /// <param name="FCELLCODE">货位编号</param>
        /// <param name="IOType">"1"：入库（放货）；"2"：出库（取货）</param>
        /// <returns></returns>
        public bool QueryCellStatusIfAccord(string FWAREHOUSE,int FLaneWay, string FCELLCODE, string IOType)
        {

            char[] cc = new char[1] { '-' };
            string[] fcc = FCELLCODE.Split(cc);
            if (fcc.GetUpperBound(0) < 2) return false;
            int[] fcci = new int[fcc.GetUpperBound(0) + 1];
            //20100108
            DataView dv;
            try
            {
                for (int i = fcc.GetLowerBound(0); i <= fcc.GetUpperBound(0); i++)
                {
                    fcci[i] = Convert.ToInt32(fcc[i]);
                }
                if (IOType == "1")//入库（放货）
                {
                    //20100108
                    dv = dbo.ExceSQL("SELECT FWAREHOUSE, FCELLCODE, FCELLSTATUS " +
                        " FROM ST_CELL Where FWAREHOUSE='" + FWAREHOUSE + "'  and FLaneWay=" + FLaneWay + "  and F_Z=" +
                        fcci[0] + " and F_X=" + fcci[1] + " and F_Y=" + fcci[2] + "  and FCELLSTATUS='0'").Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else//if (IOType == "2")//出库（取货）
                {
                    //20100108
                    dv = dbo.ExceSQL("SELECT FWAREHOUSE, FCELLCODE, FCELLSTATUS " +
                        " FROM ST_CELL Where FWAREHOUSE='" + FWAREHOUSE + "'  and FLaneWay=" + FLaneWay + "  and F_Z='" +
                        fcci[0] + "' and F_X='" + fcci[1] + "' and F_Y='" + fcci[2] + "'  and FCELLSTATUS='1'").Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {//20100108
                _DisassembleTaskError = "查询货位状态失败，" + ex.Message;
                throw ex;
                //return 0;
            }
            finally
            {//20100108
                dv = null;
                cc = null;
                fcc = null;
                fcci = null;
            }
        }
        /// <summary>
        /// 设置货位状态
        /// </summary>
        /// <param name="FWAREHOUSE"></param>
        /// <param name="FCELLCODE"></param>
        /// <param name="FCELLSTATUS"></param>
        public void SetCellStatus(string FWAREHOUSE, int FLaneWay, string FCELLCODE, string FCELLSTATUS)
        {
            char[] cc = new char[1] { '-' };
            string[] fcc = FCELLCODE.Split(cc);
            int[] fcci = new int[fcc.GetUpperBound(0) + 1];
            try
            {//20100108
                for (int i = fcc.GetLowerBound(0); i <= fcc.GetUpperBound(0); i++)
                {
                    fcci[i] = Convert.ToInt32(fcc[i]);
                }
                dbo.ExceSQL("UPDATE ST_CELL SET  FCELLSTATUS ='" + FCELLSTATUS + "' where  FWAREHOUSE='" + FWAREHOUSE + "'  and FLaneWay=" + FLaneWay + "  and F_Z='" +
                        fcci[0] + "' and F_X='" + fcci[1] + "' and F_Y='" + fcci[2] + "' ");
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                cc = null;
                fcc = null;
                fcci = null;
            }
        }
        /// <summary>
        /// 查询运行状态是否符合条件
        /// </summary>
        /// <param name="FWAREHOUSE"></param>
        /// <param name="FCELLCODE"></param>
        /// <returns></returns>
        public bool QueryRunStatusIfAccord(string FWAREHOUSE, int FLaneWay, string FCELLCODE)
        {
            char[] cc = new char[1] { '-' };
            string[] fcc = FCELLCODE.Split(cc);
            int[] fcci = new int[fcc.GetUpperBound(0) + 1];
            DataView dv;//20100108
            try
            {//20100108
                for (int i = fcc.GetLowerBound(0); i <= fcc.GetUpperBound(0); i++)
                {
                    fcci[i] = Convert.ToInt32(fcc[i]);
                }
                //20100108
                dv = dbo.ExceSQL("SELECT FWAREHOUSE, FCELLCODE, FCELLSTATUS " +
                        " FROM ST_CELL Where FWAREHOUSE='" + FWAREHOUSE + "' and FLaneWay=" + FLaneWay + "  and F_Z='" +
                        fcci[0] + "' and F_X='" + fcci[1] + "' and F_Y='" + fcci[2] + "' and FRUNSTATUS='0'").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                cc = null;
                fcc = null;
                fcci = null;
                dv = null;
            }
        }
        /// <summary>
        /// 设置货位运行状态
        /// </summary>
        /// <param name="FWAREHOUSE"></param>
        /// <param name="FCELLCODE"></param>
        /// <param name="FRUNSTATUS"></param>
        public void SetRunStatus(string FWAREHOUSE, int FLaneWay, string FCELLCODE, string FRUNSTATUS)
        {
            char[] cc = new char[1] { '-' };
            string[] fcc = FCELLCODE.Split(cc);
            int[] fcci = new int[fcc.GetUpperBound(0) + 1];
            try
            {//20100108
                for (int i = fcc.GetLowerBound(0); i <= fcc.GetUpperBound(0); i++)
                {
                    //20121009
                    return;
                    fcci[i] = Convert.ToInt32(fcc[i]);
                }
                dbo.ExceSQL("UPDATE ST_CELL SET  FRUNSTATUS  ='" + FRUNSTATUS + "' where  FWAREHOUSE='" + FWAREHOUSE + "' and FLaneWay=" + FLaneWay + " and F_Z='" +
                        fcci[0] + "' and F_X='" + fcci[1] + "' and F_Y='" + fcci[2] + "'");
            }
             
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                cc = null;
                fcc = null;
                fcci = null;
            }
        }

        public int GetSerialNumberFromRouteDevice(int RouteIDSub, int DeviceIndex)
        {
            DataView dv;//20100108
            try
            {
                //20100108
                dv = dbo.ExceSQL("SELECT F_SerialNumber FROM T_Base_Route_Device WHERE (F_RouteIDSub = " + RouteIDSub + ") AND (F_DeviceIndex = " + DeviceIndex + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return (int)dv[0]["F_SerialNumber"];
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {//20100108
                throw ex;
            }
            finally
            {//20100108
                dv = null;
            }
        }
        #endregion

        public string GetAvailableCellCode(int StartDeviceIndex)
        {
            string strCellCode = string.Empty;
            DataView dvTask = new DataView();
            DataView dvCell = new DataView();

            int iShortOfEmptyCell = 0;
            int iBusyLevel = 0;

            DataView dvRoute = dbo.ExceSQL("SELECT * FROM T_Base_Route WHERE (F_EndDevice LIKE '1800%') AND (F_RouteKind = 1) AND (F_Status = 1) AND (F_StartDevice = " + StartDeviceIndex.ToString() + ")").Tables[0].DefaultView;
            if ((dvRoute != null) && (dvRoute.Count > 0))//可到达的路径
            {
                do
                {
                    for (int i = 0; i < dvRoute.Count; i++)
                    {
                        dvTask = dbo.ExceSQL("SELECT * FROM T_Manage_Task WHERE (FENDDEVICE = " + Convert.ToInt32(dvRoute[i]["F_EndDevice"]).ToString() + ")").Tables[0].DefaultView;
                        if (dvTask != null && dvTask.Count > iBusyLevel)//此路径已有任务
                        {
                            continue;
                        }
                        else
                        {
                            if (StartDeviceIndex == 12100)
                            {
                                //dvCell = dbo.ExceSQL("SELECT top 1 * FROM ST_CELL WHERE (FLaneWay = " + Convert.ToInt32(dvRoute[i]["F_EndDevice"]).ToString() + ") AND (FCELLSTATUS = 0) AND(FRunStatus = 0) AND(F_Y = 1) AND(F_X > 9) ORDER BY F_Z, F_Y, F_X").Tables[0].DefaultView;
                                dvCell = dbo.ExceSQL("SELECT top 1 * FROM ST_CELL WHERE (FLaneWay = " + Convert.ToInt32(dvRoute[i]["F_EndDevice"]).ToString() + ") AND (FCELLSTATUS = 0) AND(FRunStatus = 0) AND(F_Y = 2)AND(F_X > 3) ORDER BY F_Z, F_Y, F_X").Tables[0].DefaultView;
                            }
                            else
                            {
                                dvCell = dbo.ExceSQL("SELECT top 1 * FROM ST_CELL WHERE (FLaneWay = " + Convert.ToInt32(dvRoute[i]["F_EndDevice"]).ToString() + ") AND (FCELLSTATUS = 0) AND(FRunStatus = 0) AND(F_Y = 2)AND(F_X > 3) ORDER BY F_Z, F_Y, F_X").Tables[0].DefaultView;
                            }
                            if (dvCell != null && dvCell.Count > 0)
                            {
                                strCellCode = dvCell[0]["fcellcode"].ToString().Trim();

                                //将货位置为选中状态
                                dbo.ExceSQL("update ST_CELL set FRunStatus = 1 where fcellcode = '" + strCellCode + "'");

                                break;
                            }
                            else
                            {
                                iShortOfEmptyCell++;
                                continue;
                            }
                        }
                    }

                    if (strCellCode == string.Empty)//有可用路径且没有分配到货位
                    {
                        if (iShortOfEmptyCell == dvRoute.Count)//No empty Cell
                        {
                            //System.Windows.Forms.MessageBox.Show("No empty Cell！！！");
                            break;
                        }
                    }

                    iBusyLevel++;
                } while (strCellCode == string.Empty);

            }
            return strCellCode;
        }

        public string GetBarCode(string strHead)
        {
            string strBarCode = string.Empty;
            int iCode = -1;
            string strBase = "00000000";

            DataView dv = dbo.ExceSQL("SELECT TOP 1 F_BarCode FROM T_Base_BarCode").Tables[0].DefaultView;

            if (dv != null && dv.Count > 0)
            {
                iCode = Convert.ToInt32(dv[0]["F_BarCode"]);

                System.Diagnostics.Trace.Assert(iCode > 0 && iCode < 30001);//1到30000

                strBase = strBase.Substring(dv[0]["F_BarCode"].ToString().Trim().Length);

                strBarCode = strHead + strBase + iCode.ToString().Trim();
            }

            dbo.ExceSQL("update T_Base_BarCode set F_BarCode =" + ((iCode % 30000 + 1)).ToString());

            return strBarCode;
        }

        public int GetLanewayFromCellCode(string strCellCode)
        {
            int iLaneway = -1;

            if (strCellCode != string.Empty)
            {
                DataView dv = dbo.ExceSQL("SELECT FLaneWay FROM ST_CELL WHERE (FCELLCODE = '"+ strCellCode +"')").Tables[0].DefaultView;
                if (dv != null && dv.Count > 0)
                {
                    iLaneway = Convert.ToInt32(dv[0]["FLaneWay"].ToString());
                }
            }

            return iLaneway;
        }
        public void ReportDeviceState()
        {
            foreach (Model.MDevice devinfo in Model.CGetInfo.DeviceInfo.Values)
            {
                if (devinfo.DeviceKind == 1 || devinfo.DeviceKind == 2 || devinfo.DeviceKind == 3 || devinfo.DeviceKind==5)
               {     
                    int  CurRunState=0;
                    if (devinfo.RunState == 0 || devinfo.RunState == 5)
                    {
                        CurRunState = 0;
                    }
                    else
                        if (devinfo.RunState == 4)
                        {
                            CurRunState = 3;
                        }
                        else
                        {
                            CurRunState = devinfo.RunState;
                        }


                    if (devinfo.LastRunState != CurRunState)
                    {
                   
                        try
                        { 
                          //上报设备状态和当前时间
                            string dtime = DateTime.Now.ToString("u");
                            dtime = dtime.Substring(0, dtime.Length - 1);
                          //  int  CurRunState= devinfo.RunState==


                            //string sql = string.Format("Update DEVICE_MONITOR set DEVICE_CUR_STATUS={0}, DEVICE_PRE_STATUS={1},UPDATE_TIME='{2}' where DEVICE_CODE ={3}", CurRunState,devinfo.LastRunState,dtime, devinfo.DeviceIndex);
                           // string sql = string.Format("Update DEVICE_MONITOR set DEVICE_CUR_STATUS={0},UPDATE_TIME='{1}' where DEVICE_CODE ={2}", CurRunState, dtime, devinfo.DeviceIndex);
                            devinfo.LastRunState = CurRunState;
                            Model.CGetInfo.SetDeviceLastRunState(devinfo);

                       //     dboM.ExceSQL(sql);
                        
                        //更新LastRunState


                        }
                        catch (Exception ex)
                        {
                            _DisassembleTaskError = string.Format("上报设备{0}的设备状态时发生错误:{1}",devinfo.DeviceIndex, ex.Message);

                            
                        }

                    }

                }
            }

        }
        /// <summary>
        /// 返回设备所在路径
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public int GetRouteIDsub(int device)
        {
            DataView dv = dbo.ExceSQL("SELECT TOP 1 F_RouteIDSub, F_DeviceIndex, F_RouteID FROM T_Base_Route_Device where F_DeviceIndex=" + device + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_RouteIDSub"]);
            }
            else
            {
                return -1;
            }
        }

        public void GetApplyID(out int ApplyID, out int ControlID)
        {
            ApplyID  =0 ;
            ControlID =0;
            DataView dvApplyID =  dboM.ExceSQL("select IO_CONTROL_APPLY_SEQ.NEXTVAL as apply_id FROM DUAL").Tables[0].DefaultView;
            DataView dvControlID =dboM.ExceSQL("select IO_CONTROL_SEQ.NEXTVAL as CONTROL_ID FROM DUAL").Tables[0].DefaultView ;
            ApplyID =Convert .ToInt32  (dvApplyID [0]["apply_id"]);
            ControlID = Convert.ToInt32(dvControlID[0]["CONTROL_ID"]);
        }
        public int GetTransDeviceGoodsCounts(string Devices)//20190712
        {
            int goodscount = 0;//货物数量
            if (Devices == "")
            { return goodscount; }
            try
            {
                char[] cc = new char[1] { ';' };
                string[] sp;
                sp = Devices.Split(cc);
                int count = sp.Length;//设备数量

                for (int i = 0; i < count; i++)
                {
                    int deviceindex = Convert.ToInt32(sp[i]);
                    devinfo = Model.CGetInfo.GetDeviceInfo(deviceindex);
                    if (devinfo != null)
                    {
                        goodscount += devinfo.SplitByte_0;
                        goodscount += devinfo.SplitByte_1;
                        if (devinfo.SplitByte_0 == 0 && devinfo.SplitByte_1 == 0)//20191221
                        {
                            if (devinfo.RunState != 0)
                            {
                                goodscount += 1;
                            }

                        }

                    }

                }
                return goodscount;



            }
            catch (Exception ex)
            {
                return goodscount;
            }


        }
    }
}
