using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DBFactory;
using CommonClassLib;
using Microsoft.VisualBasic;
using System.Threading;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 任务拆分类
    /// 选取调度任务时以保障设备利用率最大化为原则：1、每个路径端头的入库站台要有一个任务；
    /// 2、每个堆垛机要有一个任务（以优先方式决定先执行哪种任务）；
    /// 3、组合优先方式时，在调度任务完成时调整已拆分任务优先级为最高级9，进行优先执行。
    /// 
    /// 把调度任务分解成多个监控搬运任务
    /// 分解原则：把一个调度任务按照出入库路径的设备索引排出多个步骤的设备指令
    /// </summary>


    //20091107增加对五个调度策略SelectTask_ManPRI();SelectTask_OnlyIn();SelectTask_InSubjoinOut();
    //SelectTask_OnlyOut();SelectTask_OutSubjoinIn();的优先级相同时根据下达时间的升序执行order by FTASKLEVEL desc,FBEGTIME asc

    public static  class CDisassembleTask
    {
        static Thread mythread;
        static bool exitThread = false;//20091107
        private static void BeginListen()
        {//20091107
            while (!exitThread )
            {
                try
                {
                    MyTaskIntoSteps();

                }
                catch (Exception ex)
                {
                    _DisassembleTaskError = ex.Message;
                }
            }
        }
        public static void EndListen()
        {//20091107
            exitThread = true;

            if (mythread != null)
            {

                dbo.Close();
                
                mythread.Abort();
                mythread = null;
            }
        }
        public static void StartListen()
        {
            exitThread = false;
            mythread = new Thread(new ThreadStart(BeginListen));
            mythread.IsBackground = true;
            mythread.Start();
        }
        static string _DisassembleTaskError="";
        public static string DisassembleTaskError
        {
            get { return _DisassembleTaskError; }
            set { _DisassembleTaskError = value; }
        }
        static DBOperator dbo = new DBOperator() ;
        static DBOperator dboM = new DBOperator("ManConnString", "ManDBFactory");
        static CCommonFunction ccf = new CCommonFunction();

        static  Model.MDevice devinfo;

        /// <summary>
        /// 拆分调度任务，不包括手工任务（直接生成存入调度T_Monitor_Task表）
        /// </summary>
        public static void MyTaskIntoSteps()
        {
            try
            {
                int Pri = ccf.SelectTaskPriPrecept();
                switch (Pri)
                {
                    case 0://按照调度任务优先级
                        SelectTask_ManPRI();
                        break;
                    case 1://单纯入库优先
                        SelectTask_OnlyIn();
                        break;
                    case 12://入库优先携带附带运行条件的出库任务
                        SelectTask_InSubjoinOut();
                        break;
                    case 2://单纯出库优先
                        SelectTask_OnlyOut();
                        break;
                    case 21://出库优先携带附带运行条件的入库任务
                        SelectTask_OutSubjoinIn();
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.MyTaskIntoSteps时发生错误:" + ex.Message;
            }
        }
        /// <summary>
        /// 按照调度任务优先级拆分任务
        /// </summary>
        static void SelectTask_ManPRI()
        {
            try
            {
                string sql = "select * from T_Manage_Task where " +
                    " FIntoStepOK='0' order by FTASKLEVEL desc,F_ManageTaskKindIndex asc,FBEGTIME asc, FID asc ";
                DataView dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;
                DataView dv = new DataView();//20091107
                DataView dv1 = new DataView();//20091107
                Model.MDevice deviceInfo;
                for (int i = 0; i < dvM.Count; i++)
                {
                    
                    
                    if (dvM[i]["FCONTROLTASKTYPE"].ToString() == "1")
                    //如果是入库任务：判断起点设备是否有调度命令在执行或者被锁定
                    {
                        //sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                        //    " where F_ManageTASKKINDINDEX=" + dvM[i]["F_ManageTASKKINDINDEX"] + " and F_DeviceIndex=" + dvM[i]["FSTARTDEVICE"] + " and F_Status>=1";
                        //dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        //if (dv.Count > 0)
                        //{
                        //    continue;
                        //}
                        //被锁定
                        sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["FSTARTDEVICE"] + " and F_LockedState>0";
                        dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;//20091107
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                    }

                    if (dvM[i]["FCONTROLTASKTYPE"].ToString() == "2")
                    //如果是出库任务：判断堆垛机是否有调度命令在执行或者被锁定
                    {
                        sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                            " where F_ManageTASKKINDINDEX=" + dvM[i]["F_ManageTASKKINDINDEX"] +
                            " and F_DeviceIndex=" + dvM[i]["FSTACK"] + " and F_Status>0 ";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            continue;
                        }
                        //被锁定20091009
                        sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["FSTACK"] + " and (F_LockedState>0 or F_ManTaskReserve>0)";
                        dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;//20091107
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                        //20091128
                        //判断将要被拆分的出库任务是否在已拆分的队列中有终点相同的出库任务，没有就找一个拆分
                        sql = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dvM[i]["FENDDEVICE"] + ") and (FSTACK = " +
                            dvM[i]["FSTACK"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                        dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32( dvM[i]["FSTACK"])) ;
                        if (deviceInfo != null)
                        {
                            if (deviceInfo.IfCorrelDoubleFork == "1")
                            {
                                GetOutDoubleForkTask(dvM[i]);
                            }
                        }
                    }
                    //选择最短调度路径并且判断此路径上是否有设备发生故障
                    int routeid = MinRouteID(Convert.ToInt32(dvM[i]["FSTARTDEVICE"]), Convert.ToInt32(dvM[i]["FENDDEVICE"]));
                    if (routeid == -1)
                    {
                        if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                        {//20091107
                            GetUsableDestination(dvM[i]);
                        }
                        continue;
                    }
                    

                    if (CreateMonitor(Convert.ToInt32( dvM[i]["F_ManageTaskKindIndex"]),Convert.ToInt32( dvM[i]["FID"]), routeid,dvM[i],0) > 0)
                    {
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvM[i]["FID"]
                        + " and F_ManageTaskKindIndex=" + dvM[i]["F_ManageTaskKindIndex"]);
                        //20100323
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32( dvM[i]["FSTACK"])) ;
                        if (deviceInfo != null)
                        {
                            if (deviceInfo.IfCorrelDoubleFork == "1")
                            {
                                CreateRelativeMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]));
                            }
                        }
                    }
                    
                }
                //20091107
                dvM = null;
                dv = null;
                dv1 = null;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.SelectTask_ManPRI时发生错误:" + ex.Message;
            }
        }
        /// <summary>
        /// 单纯拆分入库任务，没有入库任务时再拆分出库任务
        /// </summary>
        static void SelectTask_OnlyIn()
        {
            try
            {
                Model.MDevice deviceInfo;
                string sql = "select * from T_Manage_Task where " +
                    " FIntoStepOK='0' order by FCONTROLTASKTYPE asc, F_ManageTaskKindIndex asc,FBEGTIME asc, FID asc ";
                DataView dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;

                for (int i = 0; i < dvM.Count; i++)
                {
                    DataView dv;

                    if (dvM[i]["FCONTROLTASKTYPE"].ToString() == "1")
                    //如果是入库任务：判断起点设备是否有调度命令在执行或者被锁定
                    {
                        //sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                        //    " where F_ManageTASKKINDINDEX=" + dvM[i]["F_ManageTASKKINDINDEX"] + " and F_DeviceIndex=" + dvM[i]["FSTARTDEVICE"] + " and F_Status>0";
                        //dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        //if (dv.Count > 0)
                        //{
                        //    continue;
                        //}
                        //被锁定
                        sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["FSTARTDEVICE"] + " and F_LockedState>0";
                        DataView dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                    }

                    if (dvM[i]["FCONTROLTASKTYPE"].ToString() == "2")
                    //如果是出库任务：判断堆垛机是否有调度命令在执行或者被锁定
                    {
                        sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                            " where F_ManageTASKKINDINDEX=" + dvM[i]["F_ManageTASKKINDINDEX"] +
                            " and F_DeviceIndex=" + dvM[i]["FSTACK"] + " and F_Status>0";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            continue;
                        }
                        //被锁定20091009
                        sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["FSTACK"] + " and (F_LockedState>0 or F_ManTaskReserve>0)";
                        DataView dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                        ////20091128
                        //判断将要被拆分的出库任务是否在已拆分的队列中有终点相同的出库任务，没有就找一个拆分
                        sql = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dvM[i]["FENDDEVICE"] + ") and (FSTACK = " +
                            dvM[i]["FSTACK"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                        dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dvM[i]["FSTACK"]));
                        if (deviceInfo != null)
                        {
                            if (deviceInfo.IfCorrelDoubleFork == "1")
                            {
                                GetOutDoubleForkTask(dvM[i]);
                            }
                        }
                    }
                    //选择最短调度路径并且判断此路径上是否有设备发生故障
                    int routeid = MinRouteID(Convert.ToInt32(dvM[i]["FSTARTDEVICE"]), Convert.ToInt32(dvM[i]["FENDDEVICE"]));
                    if (routeid == -1)
                    {
                        if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                        {//20091107
                            GetUsableDestination(dvM[i]);
                        }
                        continue;
                    }
                    

                    if (CreateMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]), routeid, dvM[i],0) > 0)
                    {
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvM[i]["FID"]
                        + " and F_ManageTaskKindIndex=" + dvM[i]["F_ManageTaskKindIndex"]);
                        //20100323
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32( dvM[i]["FSTACK"])) ;
                        if (deviceInfo != null)
                        {
                            if (deviceInfo.IfCorrelDoubleFork == "1")
                            {
                                CreateRelativeMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]));
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.SelectTask_OnlyIn时发生错误:" + ex.Message;
            }
        }
        /// <summary>
        /// 入库优先附带符合运行条件的出库任务
        /// 具体实现：判断T_Manage_Task表中是否有此堆垛机任务正在执行：如果没有，则挑选一个入库任务；
        /// 如果有堆垛机正在执行入库任务，并且队列中没有等待执行的堆垛机出库任务，挑选一个此堆垛机的出库任务优先级设为9；
        /// 
        /// </summary>
        static void SelectTask_InSubjoinOut()
        {
            try
            {
                string sql = "SELECT F_StackIndex FROM T_Base_StackInfo";
                DataView dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;
                DataView dv = new DataView();//20091107
                DataView dv12 = new DataView();
                DataView dvv = new DataView();
                DataView dv0 = new DataView();
                DataView dv1 = new DataView();
                DataView dv00 = new DataView();
                Model.MDevice deviceInfo;
                int routeid = -1;
                for (int i = 0; i < dvM.Count; i++)
                {
                    //首先选择此堆垛机所有入库任务，判断那个能执行
                    #region 首先选择此堆垛机所有入库任务，判断那个能执行

                    string sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTATUS = 0) AND (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                    dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;//20091107
                    for (int j = 0; j < dv.Count;j++ )//有这个堆垛机的入库任务等待拆分
                    {
                        //选择最短调度路径并且判断此路径上是否有设备发生故障
                        routeid = MinRouteID(Convert.ToInt32(dv[j]["FSTARTDEVICE"]), Convert.ToInt32(dv[j]["FENDDEVICE"]), dv[j]["FUseAwayFork"]);
                        if (routeid == -1)
                        {
                            if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                            {//20091107
                                GetUsableDestination(dv[j]);
                            }
                            continue;
                        }
                        if (CreateMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]), routeid, dv[j],0) > 0)
                        {
                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                            dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dv[j]["FID"]
                            + " and F_ManageTaskKindIndex=" + dv[j]["F_ManageTaskKindIndex"]);
                            //20100323
                            //20101028增加出库关联
                            deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                            if (deviceInfo != null)
                            {
                                if (deviceInfo.IfCorrelDoubleFork == "1")
                                {
                                    CreateRelativeMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]));
                                }
                            }
                        }
                    }

                    #endregion

                    #region 然后给正在执行的入库堆垛机任务配上一个出库任务


                    //然后给正在执行的入库堆垛机任务配上一个出库任务 
                    sqlstr = "SELECT T_Monitor_Task.F_MonitorIndex FROM T_Monitor_Task ,T_Manage_Task WHERE "+
                        " (T_Monitor_Task.F_ManageTaskIndex = T_Manage_Task.FID AND "+
                        " T_Monitor_Task.F_ManageTASKKINDINDEX = T_Manage_Task.F_ManageTaskKindIndex)"+
                        " And  (T_Monitor_Task.F_Status = 1 OR T_Monitor_Task.F_Status = 2) AND  F_DeviceCommandIndex=5 and " +
                        "(T_Monitor_Task.F_DeviceIndex = " + dvM[i]["F_StackIndex"] + ") AND (T_Manage_Task.FCONTROLTASKTYPE = 1)";
                    dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                    if (dv.Count > 0)//有这个堆垛机的入库任务在执行
                    {
                        #region 有这个堆垛机的入库任务在执行准备携带出库任务
                        //20091013
                        sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] +
                            ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                        dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                        if (dv.Count <= 0)//没有此堆垛机的出库任务在排队
                        {
                            #region 挑选此堆垛机的出库任务


                            sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                            dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                            if (dv.Count > 0)//挑选此堆垛机的出库任务
                            {

                                routeid = MinRouteID(Convert.ToInt32(dv[0]["FSTARTDEVICE"]), Convert.ToInt32(dv[0]["FENDDEVICE"]), dv[0]["FUseAwayFork"]);
                                if (routeid == -1)
                                {
                                    if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                    {//20091107
                                        GetUsableDestination(dv[0]);
                                    }
                                    continue;
                                }
                                //20101028增加出库关联
                                deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[0]["FSTACK"]));
                                if (deviceInfo != null)
                                {
                                    if (deviceInfo.IfCorrelDoubleFork == "1")
                                    {
                                        GetOutDoubleForkTask(dv[0]);
                                    }
                                }
                                if (CreateMonitor(Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[0]["FID"]), routeid, dv[0], 0) > 0)
                                {
                                    //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                    int level = Convert.ToInt32(dv[0]["FTASKLEVEL"]) == 100 ? 100 : 9;

                                    dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1',FTASKLEVEL=" + level + " where  FID=" + dv[0]["FID"]
                                    + " and F_ManageTaskKindIndex=" + dv[0]["F_ManageTaskKindIndex"]);
                                    dbo.ExceSQL("update dbo.T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                        dv[0]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dv[0]["FID"] + "");
                                    //20100323
                                    //20101028增加出库关联
                                    if (deviceInfo != null)
                                    {
                                        if (deviceInfo.IfCorrelDoubleFork == "1")
                                        {
                                            CreateRelativeMonitor(Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[0]["FID"]));
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {//20091014
                            sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] +
                                ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                            dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                            if (dv.Count > 0)//挑选此堆垛机的出库任务
                            {
                                //20091102
                                for (int j = 0; j < dv.Count; j++)
                                {
                                    //判断将要被拆分的出库任务是否在已拆分的队列中有终点相同的出库任务，没有就找一个拆分
                                    sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dv[j]["FENDDEVICE"] + ") and (FSTACK = " +
                                        dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc";
                                    dv12 = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;//20091107
                                    if (dv12.Count <= 0)
                                    {
                                        routeid = MinRouteID(Convert.ToInt32(dv[j]["FSTARTDEVICE"]), Convert.ToInt32(dv[j]["FENDDEVICE"]), dv[j]["FUseAwayFork"]);
                                        if (routeid == -1)
                                        {
                                            if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                            {//20091107
                                                GetUsableDestination(dv[j]);
                                            }
                                            continue;
                                        }
                                        //20101028增加出库关联
                                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                                        if (deviceInfo != null)
                                        {
                                            if (deviceInfo.IfCorrelDoubleFork == "1")
                                            {
                                                GetOutDoubleForkTask(dv[j]);
                                            }
                                        }
                                        if (CreateMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]), routeid, dv[j], 0) > 0)
                                        {
                                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                            int level = Convert.ToInt32(dv[j]["FTASKLEVEL"]) == 100 ? 100 : 9;

                                            dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1',FTASKLEVEL=" + level + " where  FID=" + dv[j]["FID"]
                                            + " and F_ManageTaskKindIndex=" + dv[j]["F_ManageTaskKindIndex"]);

                                            dbo.ExceSQL("update T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                                dv[j]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dv[j]["FID"] + "");
                                            //20100323
                                            //20101028增加出库关联
                                            if (deviceInfo != null)
                                            {
                                                if (deviceInfo.IfCorrelDoubleFork == "1")
                                                {
                                                    CreateRelativeMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //20091107
                                dvv = dbo.ExceSQL("select * from T_Manage_Task  WHERE (FSTACK = " +
                                    dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0)").Tables[0].DefaultView;
                                for (int aa = 0; aa < dvv.Count; aa++)
                                {
                                    dbo.ExceSQL("update T_Manage_Task set FTASKLEVEL=9 WHERE (FTASKLEVEL<>100) and  F_ManageTASKKINDINDEX=" +
                                                dvv[aa]["F_ManageTaskKindIndex"] + " and FID=" + dvv[aa]["FID"] + "");
                                    dbo.ExceSQL("update T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                                dvv[aa]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dvv[aa]["FID"] + "");
                                }
                            }
                        }
                        #endregion
                    }
                    else//没有此堆垛机任务
                    {
                        #region 没有此堆垛机任务
                        sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FIntoStepOK = '0')  order by FTASKLEVEL desc, FCONTROLTASKTYPE asc,FBEGTIME asc";
                        dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                        //20091102
                        for(int j=0;j<dv.Count;j++)
                        //if (dv.Count > 0)//随便挑选一个此堆垛机的任务
                        {
                            if (dv[j]["FCONTROLTASKTYPE"].ToString() == "2")
                            //如果是出库任务：判断堆垛机是否有调度命令在执行或者被锁定
                            {//20091014
                                sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE="+dv[j]["FENDDEVICE"]+") and (FSTACK = " + 
                                    dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc";
                                dv00 = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;//20091107
                                if (dv00.Count > 0)//有此堆垛机的出库任务而且终点相同，在排队就不拆分了
                                {
                                    continue;
                                }
                                sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                                    " where F_DeviceIndex=" + dv[j]["FSTACK"] + " and F_Status>0 ";
                                dv0 = dbo.ExceSQL(sql).Tables[0].DefaultView;//20091107
                                if (dv0.Count > 0)
                                {
                                    continue;
                                }
                                //被锁定20091009
                                sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dv[j]["FSTACK"] + " and (F_LockedState>0 or F_ManTaskReserve>0)";
                                dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;//220091007
                                if (dv1.Count > 0)
                                {
                                    continue;
                                }
                                //20101028增加出库关联
                                
                                    deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                                if (deviceInfo != null)
                                {
                                    if (deviceInfo.IfCorrelDoubleFork == "1")
                                    {
                                        GetOutDoubleForkTask(dv[j]);
                                    }
                                }
                            }
                            routeid = MinRouteID(Convert.ToInt32(dv[j]["FSTARTDEVICE"]), Convert.ToInt32(dv[j]["FENDDEVICE"]), dv[j]["FUseAwayFork"]);
                            if (routeid == -1)
                            {
                                if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                {//20091107
                                    GetUsableDestination(dv[j]);
                                }
                                continue;
                            }
                            if (CreateMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]), routeid, dv[j], 0) > 0)
                            {
                                //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dv[j]["FID"]
                                + " and F_ManageTaskKindIndex=" + dv[j]["F_ManageTaskKindIndex"]);
                                //20100323
                                //20101028增加出库关联
                                deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                                if (deviceInfo != null)
                                {
                                    if (deviceInfo.IfCorrelDoubleFork == "1")
                                    {
                                        CreateRelativeMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]));
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion
                }
                sql = "SELECT * FROM T_Manage_Task WHERE ((FSTACK <= 0)or(FCONTROLTASKTYPE = 3)) AND (FIntoStepOK = '0')  order by FTASKLEVEL desc, FCONTROLTASKTYPE asc,FBEGTIME asc";
                dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;
                for (int i = 0; i < dvM.Count; i++)//挑选没有堆垛机参与的任务
                {
                    //选择最短调度路径并且判断此路径上是否有设备发生故障
                    routeid = MinRouteID(Convert.ToInt32(dvM[i]["FSTARTDEVICE"]), Convert.ToInt32(dvM[i]["FENDDEVICE"]), dvM[i]["FUseAwayFork"]);
                    if (routeid == -1)
                    {
                        if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                        {//20091107
                            GetUsableDestination(dvM[i]);
                        }
                        continue;
                    }
                    if (CreateMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]), routeid, dvM[i], 0) > 0)
                    {
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvM[i]["FID"]
                        + " and F_ManageTaskKindIndex=" + dvM[i]["F_ManageTaskKindIndex"]);
                        //20100323
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dvM[i]["FSTACK"]));
                        if (deviceInfo != null)
                        {
                            if (deviceInfo.IfCorrelDoubleFork == "1")
                            {
                                CreateRelativeMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]));
                            }
                        }
                    }
                }
                //20091107
                dvM=null;
                dv = null;
                dv12 = null;
                dvv = null;
                dv0 = null;
                dv1 = null;
                dv00 = null;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.SelectTask_InSubjoinOut时发生错误:" + ex.Message;
            }
        }
        /// <summary>
        /// 单纯拆分出库任务，没有出库任务时再拆分入库任务
        /// </summary>
        static void SelectTask_OnlyOut()
        {
            try
            {
                string sql = "select * from T_Manage_Task where " +
                    " FIntoStepOK='0' order by FCONTROLTASKTYPE decs, F_ManageTaskKindIndex asc,FBEGTIME asc, FID asc ";
                DataView dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;
                Model.MDevice deviceInfo;
                for (int i = 0; i < dvM.Count; i++)
                {
                    DataView dv;

                    if (dvM[i]["FCONTROLTASKTYPE"].ToString() == "1")
                    //如果是入库任务：判断起点设备是否有调度命令在执行或者被锁定
                    {
                        //sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                        //    " where F_ManageTASKKINDINDEX=" + dvM[i]["F_ManageTASKKINDINDEX"] + " and F_DeviceIndex=" + dvM[i]["FSTARTDEVICE"] + " and F_Status>0";
                        //dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        //if (dv.Count > 0)
                        //{
                        //    continue;
                        //}
                        //被锁定
                        sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["FSTARTDEVICE"] + " and F_LockedState>0";
                        DataView dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                    }

                    if (dvM[i]["FCONTROLTASKTYPE"].ToString() == "2")
                    //如果是出库任务：判断堆垛机是否有调度命令在执行或者被锁定
                    {
                        sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                            " where F_ManageTASKKINDINDEX=" + dvM[i]["F_ManageTASKKINDINDEX"]
                            + " and F_DeviceIndex=" + dvM[i]["FSTACK"] + " and F_Status>0 ";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            continue;
                        }
                        //被锁定20091009
                        sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["FSTACK"] + " and (F_LockedState>0 or F_ManTaskReserve>0)";
                        DataView dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                        //20091128
                        //判断将要被拆分的出库任务是否在已拆分的队列中有终点相同的出库任务，没有就找一个拆分
                        sql = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dvM[i]["FENDDEVICE"] + ") and (FSTACK = " +
                            dvM[i]["FSTACK"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                        dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            continue;
                        }
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dvM[i]["FSTACK"]));
                        if (deviceInfo != null)
                        {
                            if (deviceInfo.IfCorrelDoubleFork == "1")
                            {
                                GetOutDoubleForkTask(dvM[i]);
                            }
                        }
                    }
                    //选择最短调度路径并且判断此路径上是否有设备发生故障
                    int routeid = MinRouteID(Convert.ToInt32(dvM[i]["FSTARTDEVICE"]), Convert.ToInt32(dvM[i]["FENDDEVICE"]));
                    if (routeid == -1)
                    {
                        if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                        {//20091107
                            GetUsableDestination(dvM[i]);
                        }
                        continue;
                    }
                    if (CreateMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]), routeid, dvM[i], 0) > 0)
                    {
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvM[i]["FID"]
                        + " and F_ManageTaskKindIndex=" + dvM[i]["F_ManageTaskKindIndex"]);
                        //20100323
                        //20101028增加出库关联
                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dvM[i]["FSTACK"]));
                        if (deviceInfo.IfCorrelDoubleFork== "1")
                        {
                            CreateRelativeMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.SelectTask_OnlyOut时发生错误:" + ex.Message;
            }
        }
        /// <summary>
        /// 出库优先附带符合运行条件的入库任务
        /// 具体实现：在收到出库任务的完成时，挑选一个可以执行的入库任务把优先级设成最高9
        /// </summary>
        static void SelectTask_OutSubjoinIn()
        {
            try
            {
                Model.MDevice deviceInfo;
                string sql = "SELECT F_StackIndex FROM T_Base_StackInfo";
                DataView dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;
                int routeid = -1;
                for (int i = 0; i < dvM.Count; i++)
                {//20090928
                    #region 首先选择此堆垛机所有入库任务，判断那个能执行

                    string sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTATUS = 0) AND (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                    DataView dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                    for ( int j = 0; j < dv.Count; j++)//有这个堆垛机的入库任务等待拆分
                    {
                        //选择最短调度路径并且判断此路径上是否有设备发生故障
                        routeid = MinRouteID(Convert.ToInt32(dv[j]["FSTARTDEVICE"]), Convert.ToInt32(dv[j]["FENDDEVICE"]),dv[j]["FUseAwayFork"]);
                        if (routeid == -1)
                        {
                            if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                            {//20091107
                                GetUsableDestination(dv[j]);
                            }
                            continue;
                        }
                        if (CreateMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]), routeid, dv[j], 0) > 0)
                        {
                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                            dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dv[j]["FID"]
                            + " and F_ManageTaskKindIndex=" + dv[j]["F_ManageTaskKindIndex"]);
                            //20100323
                            //20101028增加出库关联
                            deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                            if (deviceInfo != null)
                            {
                                if (deviceInfo.IfCorrelDoubleFork == "1")
                                {
                                    CreateRelativeMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]));
                                }
                            }
                        }
                    }

                    #endregion
                    //20091005
                    #region 然后给正在执行的入库堆垛机任务配上一个出库任务


                    //然后给正在执行的入库堆垛机任务配上一个出库任务 
                    sqlstr = "SELECT T_Monitor_Task.F_MonitorIndex FROM T_Monitor_Task ,T_Manage_Task WHERE " +
                        " (T_Monitor_Task.F_ManageTaskIndex = T_Manage_Task.FID AND " +
                        " T_Monitor_Task.F_ManageTASKKINDINDEX = T_Manage_Task.F_ManageTaskKindIndex)" +
                        " And  (T_Monitor_Task.F_Status = 1 OR T_Monitor_Task.F_Status = 2) AND F_DeviceCommandIndex=5 and " +
                        "(T_Monitor_Task.F_DeviceIndex = " + dvM[i]["F_StackIndex"] + ") AND (T_Manage_Task.FCONTROLTASKTYPE = 1)";
                    dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                    if (dv.Count > 0)//有这个堆垛机的入库任务在执行
                    {
                        #region 有这个堆垛机的入库任务在执行
                        //20091013
                        sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                        dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                        if (dv.Count <= 0)//没有此堆垛机的出库任务在排队或者执行
                        {
                            #region 挑选此堆垛机的出库任务


                            sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                            dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                            if (dv.Count > 0)//挑选此堆垛机的出库任务
                            {

                                routeid = MinRouteID(Convert.ToInt32(dv[0]["FSTARTDEVICE"]), Convert.ToInt32(dv[0]["FENDDEVICE"]), dv[0]["FUseAwayFork"]);
                                if (routeid == -1)
                                {
                                    if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                    {//20091107
                                        GetUsableDestination(dv[0]);
                                    }
                                    continue;
                                }
                                //20101028增加出库关联
                                deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[0]["FSTACK"]));
                                if (deviceInfo != null)
                                {
                                    if (deviceInfo.IfCorrelDoubleFork == "1")
                                    {
                                        GetOutDoubleForkTask(dv[0]);
                                    }
                                }
                                if (CreateMonitor(Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[0]["FID"]), routeid, dv[0], 0) > 0)
                                {
                                    //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                    dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dv[0]["FID"]
                                    + " and F_ManageTaskKindIndex=" + dv[0]["F_ManageTaskKindIndex"]);
                                    dbo.ExceSQL("update dbo.T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                        dv[0]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dv[0]["FID"] + "");
                                    //20100323
                                    //20101028增加出库关联
                                    deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[0]["FSTACK"]));
                                    if (deviceInfo != null)
                                    {
                                        if (deviceInfo.IfCorrelDoubleFork == "1")
                                        {
                                            CreateRelativeMonitor(Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[0]["FID"]));
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {//20091014
                            sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvM[i]["F_StackIndex"] +
                                ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                            dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                            if (dv.Count > 0)//挑选此堆垛机的出库任务
                            {
                                //20091102
                                for (int j = 0; j < dv.Count; j++)
                                {
                                    //判断将要被拆分的出库任务是否在已拆分的队列中有终点相同的出库任务，没有就找一个拆分
                                    sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dv[j]["FENDDEVICE"] + ") and (FSTACK = " +
                                        dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                                    DataView dv12 = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                                    if (dv12.Count <= 0)
                                    {
                                        routeid = MinRouteID(Convert.ToInt32(dv[j]["FSTARTDEVICE"]), Convert.ToInt32(dv[j]["FENDDEVICE"]), dv[j]["FUseAwayFork"]);
                                        if (routeid == -1)
                                        {
                                            if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                            {//20091107
                                                GetUsableDestination(dv[j]);
                                            }
                                            continue;
                                        }
                                        //20101028增加出库关联
                                        deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                                        if (deviceInfo != null)
                                        {
                                            if (deviceInfo.IfCorrelDoubleFork == "1")
                                            {
                                                GetOutDoubleForkTask(dv[j]);
                                            }
                                        }
                                        if (CreateMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]), routeid, dv[j], 0) > 0)
                                        {
                                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                            int level = Convert.ToInt32(dv[j]["FTASKLEVEL"]) == 100 ? 100 : 9;

                                            dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1',FTASKLEVEL=" + level + " where  FID=" + dv[j]["FID"]
                                            + " and F_ManageTaskKindIndex=" + dv[j]["F_ManageTaskKindIndex"]);

                                            dbo.ExceSQL("update T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                                dv[j]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dv[j]["FID"] + "");
                                            //20100323
                                            //20101028增加出库关联
                                            if (deviceInfo != null)
                                            {
                                                if (deviceInfo.IfCorrelDoubleFork == "1")
                                                {
                                                    CreateRelativeMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                DataView dvv = dbo.ExceSQL("select * from T_Manage_Task  WHERE (FSTACK = " +
                                    dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0)").Tables[0].DefaultView;
                                for (int aa = 0; aa < dvv.Count; aa++)
                                {
                                    dbo.ExceSQL("update T_Manage_Task set FTASKLEVEL=9 WHERE (FTASKLEVEL<>100) and  F_ManageTASKKINDINDEX=" +
                                                dvv[aa]["F_ManageTaskKindIndex"] + " and FID=" + dvv[aa]["FID"] + "");
                                    dbo.ExceSQL("update T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                                dvv[aa]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dvv[aa]["FID"] + "");
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion
                    //20091005
                    else
                    {

                        //首先选择此堆垛机一个出库任务
                        #region 首先选择此堆垛机一个出库任务
                        
                        //20091014
                        sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTATUS = 0) AND (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                        dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                        //20091102
                        for(int j=0;j<dv.Count;j++)
                        //if (dv.Count > 0)//有这个堆垛机的出库任务等待拆分
                        {//20091014
                            sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dv[j]["FENDDEVICE"] + 
                                ") and (FSTACK = " + dvM[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc";
                            DataView dv112 = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                            if (dv112.Count > 0)//有此堆垛机的出库任务而且终点相同在排队就不拆分了
                            {
                                continue;
                            }


                            //判断堆垛机是否有调度命令在执行或者被锁定
                            //20090928
                            sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                                " where F_DeviceIndex=" + dvM[i]["F_StackIndex"] + " and F_Status>0 ";
                            DataView dv0 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                            if (dv0.Count > 0)
                            {
                                continue;
                            }
                            //被锁定20091009
                            sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvM[i]["F_StackIndex"] + " and (F_LockedState>0 or F_ManTaskReserve>0)";
                            DataView dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;
                            if (dv1.Count > 0)
                            {
                                continue;
                            }

                            //选择最短调度路径并且判断此路径上是否有设备发生故障
                            routeid = MinRouteID(Convert.ToInt32(dv[j]["FSTARTDEVICE"]), Convert.ToInt32(dv[j]["FENDDEVICE"]), dv[j]["FUseAwayFork"]);
                            if (routeid == -1)
                            {
                                if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                {//20091107
                                    GetUsableDestination(dv[j]);
                                }
                                continue;
                            }
                            //20101028增加出库关联
                            deviceInfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[j]["FSTACK"]));
                            if (deviceInfo != null)
                            {
                                if (deviceInfo.IfCorrelDoubleFork == "1")
                                {
                                    GetOutDoubleForkTask(dv[j]);
                                }
                            }
                            if (CreateMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]), routeid, dv[j], 0) > 0)
                            {
                                //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dv[j]["FID"]
                                + " and F_ManageTaskKindIndex=" + dv[j]["F_ManageTaskKindIndex"]);
                                //20100323
                                //20101028增加出库关联
                                if (deviceInfo != null)
                                {
                                    if (deviceInfo.IfCorrelDoubleFork == "1")
                                    {
                                        CreateRelativeMonitor(Convert.ToInt32(dv[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dv[j]["FID"]));
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                    

                }
                //add 20131219 16003任务为特殊任务（控制群读16003滑块动作）
                sql = "SELECT * FROM T_Manage_Task WHERE ((FSTACK <= 0)or(FCONTROLTASKTYPE = 3)) AND (FIntoStepOK = '0')  and (FSTARTDEVICE <>16003) order by FTASKLEVEL desc, FCONTROLTASKTYPE asc,FBEGTIME asc";
                dvM = dbo.ExceSQL(sql).Tables[0].DefaultView;
                for (int i = 0; i < dvM.Count; i++)//挑选没有堆垛机参与的任务
                {
                    //选择最短调度路径并且判断此路径上是否有设备发生故障
                    routeid = MinRouteID(Convert.ToInt32(dvM[i]["FSTARTDEVICE"]), Convert.ToInt32(dvM[i]["FENDDEVICE"]), dvM[i]["FUseAwayFork"]);
                    if (routeid == -1)
                    {
                        if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                        {//20091107
                            GetUsableDestination(dvM[i]);
                        }
                        continue;
                    }
                    if (CreateMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]), routeid, dvM[i], 0) > 0)
                    {
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvM[i]["FID"]
                        + " and F_ManageTaskKindIndex=" + dvM[i]["F_ManageTaskKindIndex"]);
                        //20100323
                        CreateRelativeMonitor(Convert.ToInt32(dvM[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvM[i]["FID"]));
                        
                    }
                }

            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.SelectTask_OutSubjoinIn时发生错误:" + ex.Message;
            }
        }
        /// <summary>
        /// 根据调度任务的起点和终点设备索引查找路径最短的RouteIDSub
        /// </summary>
        /// <param name="startdevice">起点设备索引</param>
        /// <param name="enddevice">终点设备索引</param>
        /// <returns></returns>
        public static int MinRouteID(int startdevice,int enddevice)
        {
            try
            {
                //选择最短调度路径并且判断此路径上是否有设备发生故障
                string sql = "SELECT distinct(T_Base_Route_Device.F_RouteIDSub) FROM T_Base_Device,T_Base_Route_Device," +
                    "T_Base_Route where T_Base_Route_Device.F_RouteID = T_Base_Route.F_RouteID and " +
                    " T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex and " +
                    " F_StartDevice=" + startdevice + " and F_EndDevice=" + enddevice + " and F_Status=1";
                DataView dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                List<double> minroute=new List<double>() ;//0,routIDSub；1，路径最小值
                if (dv.Count == 0)
                {
                    
                    return -1;
                }
                for (int i = 0; i < dv.Count; i++)
                {
                    DataView dvd = dbo.ExceSQL("SELECT F_RouteIDSub, F_LockedState FROM T_Base_Device,T_Base_Route_Device WHERE "+
                        " T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex  and (T_Base_Route_Device.F_RouteIDSub = " + 
                        dv[i]["F_RouteIDSub"] + ") AND  (T_Base_Device.F_LockedState = - 1)").Tables[0].DefaultView;
                    if (dvd.Count > 0)
                    {
                        continue;
                    }

                    List<double> route = new List<double>();//0,routIDSub；1,步长；2，路径使用频率；3，路径设备任务数
                    //路径步长（设备总数）最短（权重0.3），路径使用频率最小（权重0.3）的路径，路径设备任务数（权重0.3）

                    route.Add(Convert.ToDouble(dv[i]["F_RouteIDSub"]));//RouteIDSub
                    DataView dv1 = dbo.ExceSQL("select count(F_DeviceIndex) as steps from T_Base_Route_Device where F_RouteIDSub="
                        + dv[i]["F_RouteIDSub"] + "").Tables[0].DefaultView;
                    if (dv1.Count > 0)
                    {
                        //route.Add(Convert.ToDouble(dv1[0]["steps"]));//步长
                        route.Add(0);
                    }
                    else
                    {
                        continue;
                    }
                    //路径使用频率：路径执行调度任务的数量

                    string runsql = "SELECT COUNT(DISTINCT F_ManageTaskIndex) AS ManCount FROM T_Monitor_Task GROUP BY F_RouteID HAVING (F_RouteID = " + dv[i]["F_RouteIDSub"]+")";
                    DataView dv2 = dbo.ExceSQL(runsql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["ManCount"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["ManCount"]));//路径使用频率
                        }
                        else
                        {
                            route.Add(0);//路径使用频率
                        }
                    }
                    else
                    {
                        route.Add(0);//路径使用频率
                    }
                    //路径设备任务数
                    string monisql = "SELECT COUNT(T_Monitor_Task.F_MonitorIndex) AS mtask FROM T_Monitor_Task ,T_Base_Route_Device where  (T_Monitor_Task.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex) and  (T_Base_Route_Device.F_RouteIDSub = " + dv[i]["F_RouteIDSub"] + ")";
                    dv2 = dbo.ExceSQL(monisql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["mtask"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["mtask"]));//路径设备任务数
                        }
                        else
                        {
                            route.Add(0);//路径设备任务数
                        }
                    }
                    else
                    {
                        route.Add(0);//路径设备任务数
                    }

                    //求最短路径（（路径步长*0.3+路径使用频率*0.3+设备占有数*0.3）的最小值）
                    if (minroute.Count == 0)
                    {
                        minroute.Add(route[0]);
                        minroute.Add(route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                    }
                    else
                    {
                        if (minroute[1] > (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3))
                        {
                            minroute[0] = route[0];
                            minroute[1] = (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                        }
                    }
                }
                if (minroute.Count > 0)
                {
                    return Convert.ToInt32(minroute[0]);
                }
                else
                {
                    
                    return -1;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.MinRouteID时发生错误:" + ex.Message;
                return -1;
            }

        }
        /// <summary>
        /// 20091005
        /// 根据调度任务的起点和终点设备索引查找路径最短的RouteIDSub
        /// </summary>
        /// <param name="startdevice">起点设备索引</param>
        /// <param name="enddevice">终点设备索引</param>
        /// /// <param name="enddevice">当前设备索引</param>
        /// <returns></returns>
        public static int MinRouteID(int startdevice, int enddevice,int nowdevice)
        {
            try
            {
                //选择最短调度路径并且判断此路径上是否有设备发生故障
                string sql = "SELECT distinct(T_Base_Route_Device.F_RouteIDSub) FROM T_Base_Device,T_Base_Route_Device," +
                    "T_Base_Route where T_Base_Route_Device.F_RouteID = T_Base_Route.F_RouteID and " +
                    " T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex and " +
                    " F_StartDevice=" + startdevice + " and F_EndDevice=" + enddevice + " and F_Status=1 and T_Base_Device.F_DeviceIndex ="+ nowdevice  +"";
                DataView dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                List<double> minroute = new List<double>();//0,routIDSub；1，路径最小值
                if (dv.Count == 0)
                {

                    return -1;
                }
                for (int i = 0; i < dv.Count; i++)
                {
                    DataView dvd = dbo.ExceSQL("SELECT F_RouteIDSub, F_LockedState FROM T_Base_Device,T_Base_Route_Device WHERE " +
                        " T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex  and (T_Base_Route_Device.F_RouteIDSub = " +
                        dv[i]["F_RouteIDSub"] + ") AND  (T_Base_Device.F_LockedState = - 1)").Tables[0].DefaultView;
                    if (dvd.Count > 0)
                    {
                        continue;
                    }

                    List<double> route = new List<double>();//0,routIDSub；1,步长；2，路径使用频率；3，路径设备任务数
                    //路径步长（设备总数）最短（权重0.3），路径使用频率最小（权重0.3）的路径，路径设备任务数（权重0.3）

                    route.Add(Convert.ToDouble(dv[i]["F_RouteIDSub"]));//RouteIDSub
                    DataView dv1 = dbo.ExceSQL("select count(F_DeviceIndex) as steps from T_Base_Route_Device where F_RouteIDSub="
                        + dv[i]["F_RouteIDSub"] + "").Tables[0].DefaultView;
                    if (dv1.Count > 0)
                    {
                        //route.Add(Convert.ToDouble(dv1[0]["steps"]));//步长
                        route.Add(0);
                    }
                    else
                    {
                        continue;
                    }
                    //路径使用频率：路径执行调度任务的数量

                    string runsql = "SELECT COUNT(DISTINCT F_ManageTaskIndex) AS ManCount FROM T_Monitor_Task GROUP BY F_RouteID HAVING (F_RouteID = " + dv[i]["F_RouteIDSub"] + ")";
                    DataView dv2 = dbo.ExceSQL(runsql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["ManCount"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["ManCount"]));//路径使用频率
                        }
                        else
                        {
                            route.Add(0);//路径使用频率
                        }
                    }
                    else
                    {
                        route.Add(0);//路径使用频率
                    }
                    //路径设备任务数
                    string monisql = "SELECT COUNT(T_Monitor_Task.F_MonitorIndex) AS mtask FROM T_Monitor_Task ,T_Base_Route_Device where  (T_Monitor_Task.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex) and  (T_Base_Route_Device.F_RouteIDSub = " + dv[i]["F_RouteIDSub"] + ")";
                    dv2 = dbo.ExceSQL(monisql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["mtask"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["mtask"]));//路径设备任务数
                        }
                        else
                        {
                            route.Add(0);//路径设备任务数
                        }
                    }
                    else
                    {
                        route.Add(0);//路径设备任务数
                    }

                    //求最短路径（（路径步长*0.3+路径使用频率*0.3+设备占有数*0.3）的最小值）
                    if (minroute.Count == 0)
                    {
                        minroute.Add(route[0]);
                        minroute.Add(route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                    }
                    else
                    {
                        if (minroute[1] > (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3))
                        {
                            minroute[0] = route[0];
                            minroute[1] = (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                        }
                    }
                }
                if (minroute.Count > 0)
                {
                    return Convert.ToInt32(minroute[0]);
                }
                else
                {

                    return -1;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.MinRouteID时发生错误:" + ex.Message;
                return -1;
            }

        }
        /// <summary>
        /// 根据调度任务的起点和终点设备索引查找路径最短的RouteIDSub
        /// </summary>
        /// <param name="startdevice">起点设备索引</param>
        /// <param name="enddevice">终点设备索引</param>
        /// <param name="AllStatus">不考虑路径状态：true和false都可以</param>
        /// <returns></returns>
        public static int MinRouteID(int startdevice, int enddevice, bool AllStatus, object useAwayfork)
        {
            string dff =string.Empty;
            if (useAwayfork.ToString() == "-")
            {
                dff = "F_UseAwayFork<>'n'";
            }
            else
            {
                dff = "(F_UseAwayFork='" + useAwayfork + "' or F_UseAwayFork='-' )";//20101028
            }
            try
            {
                //选择最短调度路径并且判断此路径上是否有设备发生故障
                string sql = "SELECT distinct(T_Base_Route_Device.F_RouteIDSub) FROM T_Base_Device,T_Base_Route_Device," +
                    "T_Base_Route where T_Base_Route_Device.F_RouteID = T_Base_Route.F_RouteID and " +
                    " T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex and " +
                    " F_StartDevice=" + startdevice + " and F_EndDevice=" + enddevice + " and "+dff+" ";
                DataView dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                List<double> minroute = new List<double>();//0,routIDSub；1，路径最小值
                if (dv.Count == 0)
                {

                    return -1;
                }
                for (int i = 0; i < dv.Count; i++)
                {
                    

                    List<double> route = new List<double>();//0,routIDSub；1,步长；2，路径使用频率；3，路径设备任务数
                    //路径步长（设备总数）最短（权重0.3），路径使用频率最小（权重0.3）的路径，路径设备任务数（权重0.3）

                    route.Add(Convert.ToDouble(dv[i]["F_RouteIDSub"]));//RouteIDSub
                    DataView dv1 = dbo.ExceSQL("select count(F_DeviceIndex) as steps from T_Base_Route_Device where F_RouteIDSub="
                        + dv[i]["F_RouteIDSub"] + "").Tables[0].DefaultView;
                    if (dv1.Count > 0)
                    {
                        //route.Add(Convert.ToDouble(dv1[0]["steps"]));//步长
                        route.Add(0);
                    }
                    else
                    {
                        continue;
                    }
                    //路径使用频率：路径执行调度任务的数量

                    string runsql = "SELECT COUNT(DISTINCT F_ManageTaskIndex) AS ManCount FROM T_Monitor_Task GROUP BY F_RouteID HAVING (F_RouteID = " + dv[i]["F_RouteIDSub"] + ")";
                    DataView dv2 = dbo.ExceSQL(runsql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["ManCount"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["ManCount"]));//路径使用频率
                        }
                        else
                        {
                            route.Add(0);//路径使用频率
                        }
                    }
                    else
                    {
                        route.Add(0);//路径使用频率
                    }
                    //路径设备任务数
                    string monisql = "SELECT COUNT(T_Monitor_Task.F_MonitorIndex) AS mtask FROM T_Monitor_Task ,T_Base_Route_Device where  (T_Monitor_Task.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex) and  (T_Base_Route_Device.F_RouteIDSub = " + dv[i]["F_RouteIDSub"] + ")";
                    dv2 = dbo.ExceSQL(monisql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["mtask"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["mtask"]));//路径设备任务数
                        }
                        else
                        {
                            route.Add(0);//路径设备任务数
                        }
                    }
                    else
                    {
                        route.Add(0);//路径设备任务数
                    }

                    //求最短路径（（路径步长*0.3+路径使用频率*0.3+设备占有数*0.3）的最小值）
                    if (minroute.Count == 0)
                    {
                        minroute.Add(route[0]);
                        minroute.Add(route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                    }
                    else
                    {
                        if (minroute[1] > (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3))
                        {
                            minroute[0] = route[0];
                            minroute[1] = (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                        }
                    }
                }
                if (minroute.Count > 0)
                {
                    return Convert.ToInt32(minroute[0]);
                }
                else
                {

                    return -1;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.MinRouteID时发生错误:" + ex.Message;
                return -1;
            }

        }
        /// <summary>
        /// 20100702
        /// 根据调度任务的起点和终点设备索引查找路径最短的RouteIDSub
        /// </summary>
        /// <param name="startdevice">起点设备索引</param>
        /// <param name="enddevice">终点设备索引</param>
        /// <param name="useAwayfork">是否使用远货叉</param>
        /// <returns></returns>
        public static int MinRouteID(int startdevice, int enddevice, object useAwayfork)
        {
            string dff = string.Empty;
            if (useAwayfork.ToString() == "-")
            {
                dff = "F_UseAwayFork<>'n'";
            }
            else
            {
                dff = "(F_UseAwayFork='" + useAwayfork + "' or F_UseAwayFork='-' )";//20101028
            }
            try
            {
                //选择最短调度路径并且判断此路径上是否有设备发生故障
                string sql = "SELECT distinct(T_Base_Route_Device.F_RouteIDSub) FROM T_Base_Device,T_Base_Route_Device," +
                    "T_Base_Route where T_Base_Route_Device.F_RouteID = T_Base_Route.F_RouteID and " +
                    " T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex and " +
                    " F_StartDevice=" + startdevice + " and F_EndDevice=" + enddevice + "  and "+dff+" and F_Status=1 ";
                DataView dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                List<double> minroute = new List<double>();//0,routIDSub；1，路径最小值
                if (dv.Count == 0)
                {

                    return -1;
                }
                for (int i = 0; i < dv.Count; i++)
                {
                    DataView dvd = dbo.ExceSQL("SELECT F_RouteIDSub, F_LockedState FROM T_Base_Device,T_Base_Route_Device WHERE " +
                        " T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex  and (T_Base_Route_Device.F_RouteIDSub = " +
                        dv[i]["F_RouteIDSub"] + ") AND  (T_Base_Device.F_LockedState = - 1)").Tables[0].DefaultView;
                    if (dvd.Count > 0)
                    {
                        continue;
                    }

                    List<double> route = new List<double>();//0,routIDSub；1,步长；2，路径使用频率；3，路径设备任务数
                    //路径步长（设备总数）最短（权重0.3），路径使用频率最小（权重0.3）的路径，路径设备任务数（权重0.3）

                    route.Add(Convert.ToDouble(dv[i]["F_RouteIDSub"]));//RouteIDSub
                    DataView dv1 = dbo.ExceSQL("select count(F_DeviceIndex) as steps from T_Base_Route_Device where F_RouteIDSub="
                        + dv[i]["F_RouteIDSub"] + "").Tables[0].DefaultView;
                    if (dv1.Count > 0)
                    {
                        //route.Add(Convert.ToDouble(dv1[0]["steps"]));//步长
                        route.Add(0);
                    }
                    else
                    {
                        continue;
                    }
                    //路径使用频率：路径执行调度任务的数量

                    string runsql = "SELECT COUNT(DISTINCT F_ManageTaskIndex) AS ManCount FROM T_Monitor_Task GROUP BY F_RouteID HAVING (F_RouteID = " + dv[i]["F_RouteIDSub"] + ")";
                    DataView dv2 = dbo.ExceSQL(runsql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["ManCount"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["ManCount"]));//路径使用频率
                        }
                        else
                        {
                            route.Add(0);//路径使用频率
                        }
                    }
                    else
                    {
                        route.Add(0);//路径使用频率
                    }
                    //路径设备任务数
                    string monisql = "SELECT COUNT(T_Monitor_Task.F_MonitorIndex) AS mtask FROM T_Monitor_Task ,T_Base_Route_Device where  (T_Monitor_Task.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex) and  (T_Base_Route_Device.F_RouteIDSub = " + dv[i]["F_RouteIDSub"] + ")";
                    dv2 = dbo.ExceSQL(monisql).Tables[0].DefaultView;
                    if (dv2.Count > 0)
                    {
                        if (Information.IsNumeric(dv2[0]["mtask"]) == true)
                        {
                            route.Add(Convert.ToDouble(dv2[0]["mtask"]));//路径设备任务数
                        }
                        else
                        {
                            route.Add(0);//路径设备任务数
                        }
                    }
                    else
                    {
                        route.Add(0);//路径设备任务数
                    }

                    //求最短路径（（路径步长*0.3+路径使用频率*0.3+设备占有数*0.3）的最小值）
                    if (minroute.Count == 0)
                    {
                        minroute.Add(route[0]);
                        minroute.Add(route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                    }
                    else
                    {
                        if (minroute[1] > (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3))
                        {
                            minroute[0] = route[0];
                            minroute[1] = (route[1] * 0.3 + route[2] * 0.3 + route[3] * 0.3);
                        }
                    }
                }
                if (minroute.Count > 0)
                {
                    //// 12112送出12115,12113只允许同时存在一条
                    ////add by zx20121018
                    //if (Convert.ToInt32(minroute[0]) == 88001)
                    //{
                    //    DataView dvfid = dbo.ExceSQL(" select * from T_Monitor_Task where F_NumParam1 =12112 and (F_NumParam4 =12115 or F_NumParam4=12113)").Tables[0].DefaultView;
                    //    if (dvfid.Count > 0)
                    //    {
                    //        return -1;
                    //    }
                    //}
                    ////托盘库入库只拆分一条任务
                    ////add by zx 20121217
                    //if ((startdevice == 12604) && (enddevice == 18005))
                    //{
                    //    DataView dvtuopan = dbo.ExceSQL("select * from T_Manage_Task where FIntoStepOK =1 and FSTARTDEVICE =12604 and FENDDEVICE =18005").Tables[0].DefaultView;
                    //    if (dvtuopan.Count > 0)
                    //    {
                    //        return -1;
                    //    }
                    //}
                    //// 配送出库12307-12310只拆分一条任务
                    //if ((startdevice == 12604) && (enddevice == 18005))
                    //{
                    //    DataView dvtuopan = dbo.ExceSQL("select * from T_Manage_Task where FIntoStepOK =1 and FSTARTDEVICE =12307 and FENDDEVICE =12310").Tables[0].DefaultView;
                    //    if (dvtuopan.Count > 0)
                    //    {
                    //        return -1;
                    //    }
                    //}

                    


                    return Convert.ToInt32(minroute[0]);
                }
                else
                {

                    return -1;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.MinRouteID时发生错误:" + ex.Message;
                return -1;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Mankind">调度任务类型索引</param>
        /// <param name="ManFID">io_control索引</param>
        /// <param name="routeIDSub">调度路径的子路径编号</param>
        /// <param name="drv">调度任务行视图</param>
        /// <returns></returns>
        public static int CreateMonitor(int Mankind,int ManFID, int routeIDSub,DataRowView drv,int status)
        {
            //关联设备属于需要同步执行的设备组
            //穿梭车、堆垛机、AGV都属于关键设备需要单独调度，
            //所以此类设备是路径分段命令的分割点，
            //举例：【成品入库路径】
            //1）输送机输送分段控制
            //2）输送机出库（取关联）；
            //3）RGV将取+RGV取货（取关联）+RGV将送+RGV送货（送关联）；
            //4）输送机入库（送关联）
            //5）输送机输送分段控制
            //6）堆垛机取送货(将取+取货或者将送+送货)；
            //7）巷道虚拟命令
            DataView dvRoute; DataView dvs;
            try
            {
                //090714
                if (ccf.GetMonitorIndex(ManFID, Mankind) >= 30000)
                {

                    ccf.UpdateMonitorIndex(1);
                }
                //20091107
                string sql = "SELECT T_Base_Route_Device.F_DeviceIndex,F_DeviceOrder, T_Base_Route_Device.F_SerialNumber, " +
                    "T_Base_Device.F_DeviceKindIndex,F_UnControl FROM " +
                    "T_Base_Device,T_Base_Route_Device where " +
                    "T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and F_RouteIDSub=" +
                    routeIDSub + " order by F_SerialNumber asc ";
                dvRoute = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvRoute.Count == 0) return 0;
                dbo.TransBegin();
                int CurSerialNumber = 0;
                List<int> PriorDevice0 = new List<int>(), PriorKeyDevice0 = new List<int>();
                string AheadDetect = string.Empty;
                string RunningLock = string.Empty;
                string AheadTrigger = string.Empty;
                string uncontrol = string.Empty;
                for (int i = 0; i < dvRoute.Count; i++)
                {
                    AheadDetect = string.Empty;
                    RunningLock = string.Empty;
                    AheadTrigger = string.Empty;
                    uncontrol = (dvRoute[i]["F_UnControl"] + "").ToString();

                    List<int> PriorDevice = new List<int>(), NextDevice = new List<int>(),
                        CurDevice = new List<int>(), NextKeyDevice = new List<int>();//0设备所引；1设备类型;2:路径序号；3：设备命令
                    //防止输送机设备组重复查找关键设备
                    if (Convert.ToInt32(dvRoute[i]["F_SerialNumber"]) <= CurSerialNumber) continue; // 长输送机不重复考虑

                    CurDevice.Add(Convert.ToInt32(dvRoute[i]["F_DeviceIndex"]));
                    CurDevice.Add(Convert.ToInt32(dvRoute[i]["F_DeviceKindIndex"]));
                    CurDevice.Add(Convert.ToInt32(dvRoute[i]["F_SerialNumber"]));
                    CurDevice.Add(Convert.ToInt32(dvRoute[i]["F_DeviceOrder"]));
                    NextKeyDevice = GetNextKeyDevice(routeIDSub, Convert.ToInt32(dvRoute[i]["F_SerialNumber"]));
                    if (NextKeyDevice.Count > 0)//找到关键设备：0设备所引；1设备类型;2:路径序号；3：设备命令
                    {
                        CurSerialNumber = NextKeyDevice[2];
                        NextDevice = GetNextDevice(routeIDSub, NextKeyDevice[2]);
                        PriorDevice = GetPriorDevice(routeIDSub, NextKeyDevice[2]);
                        
                        int TriggerTaskNo = 0;
                        int[] Coor = new int[6] { 0, 0, 0, 0, 0, 0 };
                        //20101118
                        string tw = string.Empty; 
                        int mainTask = 0; int Rgvorder = 0;
                        switch (NextKeyDevice[1])
                        {
                            case 1:
                                #region 堆垛机

                                #region 生成一个设备命令并且获得取送货坐标
                                //堆垛机取货：
                                if (PriorDevice.Count > 0)
                                {
                                    //如果PriorDevice是输送机则生成输送机命令【CurDevice-->PriorDevice目标设备,出库：2】，
                                    //收到输送机PriorDevice的PLC上报的运行状态则提前触发堆垛机将取命令，然后是取送货命令，获取堆垛机取坐标
                                    #region 前一设备是输送机
                                    if (uncontrol != "1")
                                    {//20091107
                                        if (PriorDevice[1] == 2 )
                                        {
                                            int arrowdev;
                                            List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                            if (newcur != null)
                                            {
                                                CurDevice = newcur;
                                            }

                                            if (CurDevice[0] == PriorDevice[0]) 
                                            {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                                arrowdev = 0;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetBindingDeviceIndex(CurDevice[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";D" + tw.ToString() ;
                                                }
                                                
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                                #endregion
                                            }
                                            else
                                            {
                                                
                                          
                                                arrowdev = PriorDevice[0];
                                                CurDevice[3] = 6;

                                                #region 运行提前检测光电组
                                                //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetSendOutDetect(CurDevice[0]); // 送出检测 (该设备上有物)
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]); //(该设备空闲)
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                //20110318 
                                                //if (12103==CurDevice[0])
                                                //{
                                                    
                                                //    tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                //    if (tw != "")
                                                //    {//20101118
                                                //        AheadDetect += ";D" + tw.ToString();
                                                //    }
                                                //}

                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);

                                                tw = GetBindingDeviceIndex(nextConveyor[0]); //由于该输送机是长输送机的一段，属于输送机的入口，出口都需要检测 //20111116
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";D" + tw.ToString();
                                                }
                                                //20110318
                                                tw = GetBeDetectedDevices(nextConveyor[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";" + tw.ToString();
                                                }

                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";D" + tw.ToString();
                                                }
                                                if (nextConveyor[0] == 12013) //2011/11/16 如果是检定表回库 （入库） 检测条件
                                                {
                                                    if (arrowdev == 12015)
                                                    {
                                                        AheadDetect += "I12008;I12014;I12015";
                                                    }
                                                    if (arrowdev == 12017)
                                                    {
                                                        AheadDetect += "I12008;I12009;I12016;I12017";
                                                    }

                                                }
                                                if (nextConveyor[0] == 12026 || nextConveyor[0] == 12207)
                                                {

                                                }
                                               // if(nextConveyor[0]==12008 || nextConveyor[0] == )


                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + nextConveyor[0].ToString();
                                                #endregion
                                            }
                                            AheadTrigger = PriorDevice[0].ToString(); //+ "-" + (被触发的调度任务号);//此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam,F_UseAwayFork)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";

                                                #region 测试路径 20120916
                                                if (CurDevice[0] == 12116 && ((arrowdev == 12001) || (arrowdev == 12003)))
                                                {
                                                    AheadDetect = "I12116;D-12116.0;I12117;D12117.0";
                                                    int tempdevice = 12026;
                                                    string tempaheaddetect = "I12026;D-12026.0";
                                                    if (arrowdev == 12001)
                                                    {
                                                        tempaheaddetect += ";I12009;D12009.0";
                                                    }
                                                    else
                                                    {
                                                        tempaheaddetect += ";I12027;D12027.0";
                                                    }

                                                    sql = "INSERT INTO T_Monitor_Task " +
                                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                        " F_AheadDetect,F_TxtParam,F_UseAwayFork)" +
                                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                        + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + tempdevice
                                                        + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                                    dbo.ExceSQL(sql);
                                                mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                    sql = "INSERT INTO T_Monitor_Task " +
                                                   "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                   " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                   " F_AheadDetect,F_TxtParam,F_UseAwayFork)" +
                                               "VALUES (" + (ManFID ) + "," + Mankind + "," + (mindex )+ "," + drv["FTASKLEVEL"]
                                                   + "," + tempdevice + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + tempdevice + "," + arrowdev
                                                   + ",'" + tempaheaddetect + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                                    dbo.ExceSQL(sql);

                                                }
                                                #endregion 测试路径

                                                else
                                                {
                                                    dbo.ExceSQL(sql);
                                                }

                                               
                                                #endregion
                                            }
                                            //20101220生成升降站台上升指令
                                           
                                            AheadDetect =  GetBeDetectedDevices(arrowdev);
                                            tw = GetBindingDeviceIndexOut(arrowdev);
                                            if (tw != "")
                                            {//判断在2列位置有货
                                                AheadDetect += ";D-" + tw.ToString();
                                            }
                                            CurDevice[3] = 8;
                                            if ((DeviceAndOrderExitInMonitor(Mankind, ManFID, arrowdev, CurDevice[3], 0) == false)&& (arrowdev != 12032)) // 12032不是顶升机构不产生上升指令 2011/11/17
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                //20120913 JXDL没有高低货位不存在顶升的要求
                                                //sql = "INSERT INTO T_Monitor_Task " +
                                                //    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                //    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                //    " F_AheadDetect,F_TxtParam,F_UseAwayFork)" +
                                                //"VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                //    + "," + arrowdev + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + arrowdev + "," 
                                                //    + "0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                                //dbo.ExceSQL(sql);


                                                #endregion
                                            }


                                        }
                                    }
                                    #endregion

                                    #region 前一设备是条码扫描器等，不载物的关键设备

                                    if ((PriorDevice[1] == 7) || (PriorDevice[1] == 12))
                                    {
                                        int arrowdev;
                                        List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                        if (newcur != null)
                                        {
                                            CurDevice = newcur;
                                            PriorDevice = PriorDevice0;
                                            //输送机的起点设备和终点设备相同时，目标设备索引置为零
                                            arrowdev = 0;
                                            #region 运行提前检测光电组
                                            //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                            tw = GetBindingDeviceIndex(CurDevice[0]);
                                            if (tw != "")
                                            {//20101118
                                                AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);
                                            }
                                            else
                                            {
                                                AheadDetect = null;
                                            }
                                            ////20090803检测设备是否空闲idle
                                            //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                            #endregion

                                            AheadTrigger = PriorDevice[0].ToString(); //+ "-" + (被触发的调度任务号);//此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                                dbo.ExceSQL(sql);
                                                #endregion
                                            }
                                        }

                                    }
                                    #endregion

                                    //如果PriorDevice是固定站台不生成命令，堆垛机生成取送货命令，获取堆垛机取坐标
                                    //如果PriorDevice是巷道，PriorDevice不拆分命令，获取堆垛机取坐标，拆分堆垛机命令取送货
                                    #region 获得取送货坐标


                                    int[] Coor0_2 = new int[6] { 0, 0, 0, 0, 0, 0 };
                                    //如果NextDevice是巷道，NextDevice不拆分命令，获取堆垛机送坐标，拆分堆垛机命令取送货
                                    if (PriorDevice[1] == 10)
                                    {
                                        Coor0_2 = GetStackCoordinateFromManage(Mankind, ManFID, drv);
                                    }
                                    else
                                    {
                                        //如果NextDevice是输送机则取送货命令，获取堆垛机送坐标

                                        //如果NextDevice是固定站台则取送货命令，获取堆垛机送坐标
                                        Coor0_2 = GetStackCoordinateFromLaneGate(NextKeyDevice[0], PriorDevice[0], true);
                                    }
                                    Coor[0] = Coor0_2[0];
                                    Coor[1] = Coor0_2[1];
                                    Coor[2] = Coor0_2[2];
                                    #endregion
                                }

                                //堆垛机送货：
                                if (NextDevice.Count > 0)
                                {
                                    int[] Coor3_5 = new int[6] { 0, 0, 0, 0, 0, 0 };
                                    //如果NextDevice是巷道，NextDevice不拆分命令，获取堆垛机送坐标，拆分堆垛机命令取送货
                                    if (NextDevice[1] == 10)
                                    {
                                        Coor3_5 = GetStackCoordinateFromManage(Mankind, ManFID, drv);
                                    }
                                    else
                                    {
                                        //如果NextDevice是输送机则取送货命令，获取堆垛机送坐标

                                        //如果NextDevice是固定站台则取送货命令，获取堆垛机送坐标
                                        Coor3_5 = GetStackCoordinateFromLaneGate(NextKeyDevice[0],NextDevice[0], false);
                                    }
                                    Coor[3] = Coor3_5[3];
                                    Coor[4] = Coor3_5[4];
                                    Coor[5] = Coor3_5[5];
                                }
                                #endregion

                                #region 生成堆垛机指令:将取+取货+送货

                                #region 将取
                                //AheadDetect = "";
                                //if (NextDevice[1] == 2)
                                //{//将取时做送货做提前检测
                                //    //20091107
                                //    if (CStaticClass.OutDetectArrowIdleGoods == "1")
                                //    {
                                //        #region 运行提前检测光电组


                                //        tw = GetBindingDeviceIndex(NextDevice[0]);
                                //        if (tw != "")
                                //        {
                                //            AheadDetect = tw.ToString() + ";" + GetBeDetectedDevices(NextDevice[0]);
                                //        }
                                //        else
                                //        {
                                //            AheadDetect = null;
                                //        }
                                //        tw = GetBindingDeviceIndexOut(NextDevice[0]);
                                //        if (tw != "")
                                //        {
                                //            AheadDetect = AheadDetect + ";" + tw.ToString();
                                //        }
                                //        ////20090803检测设备是否空闲idle
                                //        AheadDetect += ";" + "I" + NextDevice[0].ToString();
                                //        //20090918给堆垛机送货的输送机增加是否逻辑有物的判断
                                //        AheadDetect += ";" + "N" + NextDevice[0].ToString();
                                //        #endregion
                                //    }
                                //}
                                //AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);

                                //#region 双叉堆垛机修改：列坐标和F_UseAwayFork、F_CorrelDoubleFork 

                                //int UseAwayFork = 1;//远货叉是主货叉

                                //devinfo = Model.CGetInfo.GetDeviceInfo(NextKeyDevice[0]);
                                //if (devinfo.IfCorrelDoubleFork == "1")
                                //{
                                //    UseAwayFork = ccf.GetUseAwayFork(Coor[0], Coor[1], Coor[2], ccf.GetWAREHOUSEFromSTCELL(NextKeyDevice[0]), Mankind, ManFID, NextKeyDevice[0],2);

                                // }
                                //#endregion


                                //if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 2, 0) == false)
                                //{
                                //    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                //    sql = "INSERT INTO T_Monitor_Task " +
                                //        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                //        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                //        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_TxtParam,F_AheadDetect,F_UseAwayFork)" +
                                //    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                //        + "," + NextKeyDevice[0] + ",2," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                //        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + drv["FPALLETBARCODE"] + "','" + AheadDetect + "','"+UseAwayFork+"')";
                                //    dbo.ExceSQL(sql);

                                //    //更新最后一个输送机运行时的堆垛机将取的提前触发
                                //    //格式：运行的设备索引+被触发的调度任务号
                                //    if (AheadTrigger != null)
                                //    {
                                //        AheadTrigger = PriorDevice[0] + "-" + mindex;
                                //        //此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                //        dbo.ExceSQL("update T_Monitor_Task set F_AheadTrigger='" + AheadTrigger + "' where F_MonitorIndex=" + TriggerTaskNo);
                                //    }
                                //}
                                #endregion

                                #region 取货

                                if (PriorDevice[1] == 10)
                                {
                                    AheadDetect = null;
                                }
                                #region 检测前设备有货（顶升高位有货）、设备空闲。后设备无货（顶升高位无货）、设备空闲。 堆垛机无货、空闲。
                                         
                                RunningLock = "";
                                AheadDetect = "";
                                if (PriorDevice[1] == 2)
                                {
                                   

                                    #region 运行时锁定设备组
                                    RunningLock = PriorDevice[0].ToString();
                                    List<int> PriorDevice2 = GetPriorDevice(routeIDSub, PriorDevice[2]);
                                    if (PriorDevice2.Count > 0)
                                    {
                                        if (PriorDevice2[1] == 2)//保证两个输送机对接的第一个输送机也被锁定
                                        {
                                            RunningLock = RunningLock + ";" + PriorDevice2[0].ToString();
                                        }

                                    }

                                    #endregion


                                    
                                  //  AheadDetect = "";
                                    tw = GetBindingDeviceIndex(PriorDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect = "D-" + tw.ToString();
                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    string[] cdi = ccf.GetCorrel_DeviceInfo(PriorDevice[0], true);
                                    if (cdi != null)
                                    {
                                        AheadDetect += ";D-" + cdi[1];//20101118
                                    }
                                       AheadDetect += ";" + GetBeDetectedDevices(PriorDevice[0]);
                                }

                                if (NextDevice[1] == 2)
                                {
                                    tw = GetBindingDeviceIndex(NextDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect += ";D" + tw.ToString();//20101118
                                    }
                                    string[] cdi = ccf.GetCorrel_DeviceInfo(NextDevice[0], true);
                                    if (cdi != null)
                                    {
                                        AheadDetect += ";D-" + cdi[1];//20101118
                                    }
                                  
                                    AheadDetect += ";" + GetBeDetectedDevices(NextDevice[0])+";N"+NextDevice[0];
                                       
                                }
                             
                                tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                if (tw != "")
                                {
                                    AheadDetect += ";D" + tw.ToString();
                                }
                                AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);

                                #endregion


                                //取货
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 4, 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_UseAwayFork)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + ",4," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + AheadDetect + "','" + RunningLock + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                    dbo.ExceSQL(sql);

                                }

                                #endregion

                                #region 将送

                                //if (NextDevice[1] == 10)
                                //{
                                //    AheadDetect = null;
                                //}
                                //RunningLock = "";
                                //AheadDetect = GetBeDetectedDevices(NextKeyDevice[0]);
                                ////将送
                                //if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 3, 0) == false)
                                //{
                                //    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                //    sql = "INSERT INTO T_Monitor_Task " +
                                //        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                //        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                //        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_TxtParam,F_AheadDetect)" +
                                //    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                //        + "," + NextKeyDevice[0] + ",3," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                //        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + drv["FPALLETBARCODE"] + "','" + AheadDetect + "')";
                                //    dbo.ExceSQL(sql);
                                //}

                                #endregion

                                #region 送货


                                RunningLock = "";
                                AheadDetect = "";
                                #region 后设备无货(顶升高位无货)空闲。堆垛机空闲有货
                                if (NextDevice[1] == 2 || NextDevice[1] == 9)
                                {
                                    #region 运行时锁定设备组
                                    RunningLock = "";

                                    DataView dvlane = dbo.ExceSQL("SELECT F_LaneGateDeviceIndex FROM T_Base_Lane_Gate WHERE (F_LaneGateDeviceIndex =" + NextDevice[0] + ") AND (F_RunLock = '1')").Tables[0].DefaultView;
                                    if (dvlane.Count > 0)
                                    {
                                        RunningLock = NextDevice[0].ToString();
                                    }
                                    else
                                    {
                                        RunningLock = "";
                                    }

                                    #endregion
                                    #region 运行提前检测光电组

                                    AheadDetect = "";
                                    tw = GetBindingDeviceIndex(NextDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect = "D" + tw.ToString();//20101118
                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    string[] cdi = ccf.GetCorrel_DeviceInfo(NextDevice[0], true);
                                    if (cdi != null)
                                    {

                                        AheadDetect += "D-" + cdi[1];//20101118
                                    }
                                  
                                    //20090918给堆垛机送货的输送机增加是否逻辑有物的判断
                                    AheadDetect += ";" + GetBeDetectedDevices(NextDevice[0]) + ";N" + NextDevice[0];
                                    #endregion
                                }
                                AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);
                                // 堆垛机放货时保证有货
                                tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                if (tw != "")
                                {
                                    AheadDetect += ";D-" + tw.ToString();
                                }
                                #endregion
                                //送货
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 5, 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_UseAwayFork)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + ",5," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + AheadDetect + "','" + RunningLock + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                    dbo.ExceSQL(sql);

                                }

                                #endregion



                                #region 取送 （为了提高出入库效率指令由取货，放货两个指令改为取放一个指令）

                                //if (PriorDevice[1] == 10)
                                //{
                                //    AheadDetect = null;
                                //}
                                //RunningLock = "";
                                //if (PriorDevice[1] == 2)
                                //{//取货做提前检测
                                //    #region 运行时锁定设备组
                                //    RunningLock = PriorDevice[0].ToString();
                                //    List<int> PriorDevice2 = GetPriorDevice(routeIDSub, PriorDevice[2]);
                                //    if(PriorDevice2.Count>0)
                                //    {
                                //        if (PriorDevice2[1] == 2)//保证两个输送机对接的第一个输送机也被锁定
                                //        {
                                //            RunningLock = RunningLock + ";" + PriorDevice2[0].ToString();
                                //        }

                                //    }

                                //    #endregion
                                //    #region 运行提前检测光电组
                                //    AheadDetect = "";
                                //    //20101011
                                //    string[] cdi = ccf.GetCorrel_DeviceInfo(PriorDevice[0],true);
                                //    if (cdi!=null)
                                //    {//20100406顶升机构被堆垛机取货时检测在顶升高位（-11211），空闲
                                //        AheadDetect = "D-" + cdi[1];//20101118
                                //       // AheadDetect += ";D-" + cdi[5];//20110108 检测2列为有货状态  // 单站台不检测远近
                                        
                                //    }
                                //    //20101011
                                //    else
                                //    {
                                //        tw = GetBindingDeviceIndexOut(PriorDevice[0]);
                                //        if (tw != "")
                                //        {//20101118
                                //           // AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(PriorDevice[0]);
                                //            AheadDetect = "D-" + tw.ToString();
                                //        }
                                //        else
                                //        {
                                //            AheadDetect = null;
                                //        }
                                //    }
                                    
                                //    //20090803检测设备是否空闲idle
                                //    AheadDetect += ";" + "I" + PriorDevice[0].ToString();
                                    
                                //    #endregion

                                //}
                                //if (NextDevice[1] == 2)
                                //{
                                //    //20101011
                                //    string[] cdi = ccf.GetCorrel_DeviceInfo(NextDevice[0], true);
                                //    if (cdi!=null)
                                //    {//20100406检测被堆垛机送货的顶升机构在顶升高位（-11211或者-11221），空闲
                                //        //20101218
                                //        if(cdi[1]!="") //高位
                                //        {
                                //        AheadDetect += ";D-" + cdi[1];//20101118
                                //        }

                                //        if (cdi[3] != "")
                                //        {
                                //            AheadDetect += ";D" + cdi[3];//20101118
                                //        }
                                //        if (cdi[5] != "")
                                //        {

                                //            AheadDetect += ";D" + cdi[5];//20101118
                                //        }
                                //        if (cdi[6] != "")
                                //        {
                                //            AheadDetect += ";D" + cdi[6];//20101118
                                //        }

                                //    //20101011   
                                //    }
                                //    else
                                //    {
                                //        tw = GetBindingDeviceIndex(NextDevice[0]);
                                //        if (tw != "")
                                //        {
                                //            AheadDetect += ";D" + tw.ToString();//20101118
                                //        }
                                //        //tw = GetBindingDeviceIndexOut(NextDevice[0]);
                                //        //if (tw != "")
                                //        //{
                                //        //    AheadDetect += ";D" + tw.ToString();//20101118
                                //        //}
                                //    }
                                //    //20100406检测被堆垛机送货的输送机空闲
                                //   // 20120918
                                //   // AheadDetect += ";" + "I" + NextDevice[0].ToString() + ";" + "N" + NextDevice[0].ToString();
                                //    AheadDetect += ";" + "I" + NextDevice[0].ToString();

                                //}
                                //      //保证堆垛机取货时堆垛机无货 2011/11/16
                                //    tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                //    if (tw != "")
                                //    {
                                //        AheadDetect += ";D" + tw.ToString();
                                //    }
                                //AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);

                                ////取送货
                                //if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 6, 0) == false)
                                //{
                                //    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                //    sql = "INSERT INTO T_Monitor_Task " +
                                //        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                //        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                //        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_UseAwayFork)" +
                                //    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                //        + "," + NextKeyDevice[0] + ",6," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                //        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + AheadDetect + "','" + RunningLock + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                //    dbo.ExceSQL(sql);
                                   
                                //}
                                #endregion

                                #endregion

                                //修改T_Manage_Task的FLANEWAY，FSTACK
                                dvs = dbo.ExceSQL("SELECT F_LaneDeviceIndex,F_StackIndex  FROM T_Base_LaneInfo where F_StackIndex=" + NextKeyDevice[0] + "").Tables[0].DefaultView;
                                int laneway = 0;
                                if (dvs.Count > 0)
                                {
                                    laneway = Convert.ToInt32(dvs[0]["F_LaneDeviceIndex"]);

                                }//20101028
                                dbo.ExceSQL("update T_Manage_Task set FLANEWAY=" + laneway + ",FSTACK=" + NextKeyDevice[0] + " where (FLANEWAY=-1) and (FSTACK=-1) and (F_ManageTaskKindIndex=" + Mankind + ") and FID=" + ManFID);
                                break;

                                #endregion
                           
                            case 2://输送机（关键点：例如十字路口（有前一个和后一个设备）或者路径终点（没有后一个设备）） 
                            case 3://自动出库机
                                #region 输送机
                                if (NextDevice.Count == 0)//终点输送机
                                {
                                    if (uncontrol != "1")
                                    {//20091107
                                        List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                        if (newcur != null)
                                        {
                                            CurDevice = newcur;
                                        }
                                        int arrowdev;
                                        if (CurDevice[0] == NextKeyDevice[0])
                                        {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                            arrowdev = 0;

                                            #region 运行提前检测光电组
                                            if ((CurDevice[3] == 1) || ((CurDevice[3] == 2)))
                                            {
                                                //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetBindingDeviceIndex(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }

                                            }
                                            //else if (CurDevice[3] == 2)
                                            //{
                                            //    tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                            //    if (tw != "")
                                            //    {
                                            //        AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                            //    }
                                            //    else
                                            //    {
                                            //        AheadDetect = null;
                                            //    }
                                            //}
                                            ////20090803检测设备是否空闲idle
                                            //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                            #endregion
                                        }
                                        else
                                        {
                                            arrowdev = NextKeyDevice[0];
                                            CurDevice[3] = 6;
                                            #region 运行提前检测光电组
                                            //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                            tw = GetSendOutDetect(CurDevice[0]);
                                            if (tw != "")
                                            {
                                                AheadDetect = "D-" + tw.ToString();//20101118
                                            }
                                            else
                                            {
                                                AheadDetect = null;
                                            }
                                            //20101118
                                             AheadDetect += ";" + GetBeDetectedDevices(CurDevice[0]);

                                            List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                            tw = GetBindingDeviceIndex(nextConveyor[0]);
                                            if (tw != "")
                                            {
                                                AheadDetect += ";D" + tw.ToString();// + ";" + GetBeDetectedDevices(nextConveyor[0]);//20101118
                                            }
                                            //20110318
                                            tw = GetBeDetectedDevices(nextConveyor[0]);
                                            if (tw != "")
                                            {//20101118
                                                AheadDetect += ";" + tw.ToString();
                                            }
                                            tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                            if (tw != "")
                                            {
                                                AheadDetect += ";D" + tw.ToString();//20101118
                                            }
                                            ////20090803检测设备是否空闲idle
                                            //AheadDetect += ";" + "I" + nextConveyor[0].ToString();
                                            #endregion
                                        }
                                        if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                        {
                                            #region 运行时锁定设备组

                                            #endregion

                                            #region 生成输送机命令
                                            int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                            //20110318
                                            int floor = 0;
                                            //if (18007==arrowdev)
                                            //{
                                                floor =Convert.ToInt32( drv["BOX_QUANTITY"]);
                                            //}
                                            sql = "INSERT INTO T_Monitor_Task " +
                                                "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                " F_AheadDetect,F_TxtParam,F_NumParam5)" +
                                            "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',"+floor+")";
                                            dbo.ExceSQL(sql);
                                            #endregion
                                        }

                                    }
                                }
                                else//十字路口
                                {

                                }
                                #endregion
                                break;
                            case 4:
                                #region RGV
                                //RGV取货：
                                if (PriorDevice.Count > 0)
                                {
                                    //如果PriorDevice是输送机则生成输送机命令【CurDevice-->PriorDevice目标设备,出库：2】，
                                    //收到输送机PriorDevice的PLC上报的运行状态则提前触发RGV运行命令（7），然后是取送货命令，获取堆垛机取坐标
                                    #region 前一设备是输送机

                                    if (PriorDevice[1] == 2)
                                    {
                                        if (uncontrol != "1")
                                        {//20091107
                                            List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                            if (newcur != null)
                                            {
                                                CurDevice = newcur;
                                            }
                                            int arrowdev;

                                            if (CurDevice[0] == PriorDevice[0])
                                            {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                                arrowdev = 0;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetBindingDeviceIndex(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                                #endregion
                                            }
                                            else
                                            {
                                                arrowdev = PriorDevice[0];
                                                CurDevice[3] = 6;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetSendOutDetect(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();

                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                                tw = GetBindingDeviceIndex(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString() + ";" + GetBeDetectedDevices(nextConveyor[0]);//20101118
                                                }
                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + nextConveyor[0].ToString();
                                                #endregion
                                            }
                                            AheadTrigger = PriorDevice[0].ToString(); //+ "-" + (被触发的调度任务号);//此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                                dbo.ExceSQL(sql);
                                                #endregion
                                            }

                                        }


                                    }

                                    #endregion

                                    #region 获得RGV运行的接货位的设备索引

                                    Coor[0] = PriorDevice[0];
                                    Coor[1] = 0;
                                    Coor[2] = 0;
                                    Coor[3] = 0;
                                    Coor[4] = 0;
                                    Coor[5] = 0;
                                    #endregion

                                    #region 生成RGV指令:7-运动（到目标设备索引）+（2-左接货3-左送货）或者（4-右接货5-右送货）
                                    //20090625
                                    #region 运行提前检测光电组
                                    AheadDetect = "";
                                    tw = GetBindingDeviceIndex(NextDevice[0]);//目标输送机入口无探物，能运行
                                    if (tw != "")
                                    {
                                        AheadDetect = "D" + tw.ToString() + ";" + GetBeDetectedDevices(NextDevice[0]);//20101118
                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    tw = GetBindingDeviceIndexOut(NextDevice[0]);//目标输送机出口无探物，能运行
                                    if (tw != "")
                                    {
                                        AheadDetect = AheadDetect + ";D" + tw.ToString();//20101118
                                    }
                                    //20090803检测设备是否空闲idle
                                    AheadDetect += ";" + "I" + NextDevice[0].ToString();
                                    //20090803检测设备是否空闲idle
                                    AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);
                                    tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect += ";D" + tw.ToString();//20101118
                                    }
                                    #endregion

                                    //运动
                                    if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 2, Coor[0]) == false)
                                    {
                                        int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                        sql = "INSERT INTO T_Monitor_Task " +
                                            "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                            " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                            " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_TxtParam,F_AheadDetect)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + NextKeyDevice[0] + ",7," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                            + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + drv["FPALLETBARCODE"] + "','" + AheadDetect + "')";
                                        dbo.ExceSQL(sql);
                                        //更新最后一个输送机运行时的RGV运行的提前触发
                                        //格式：运行的设备索引+被触发的调度任务号
                                        if (AheadTrigger != null)
                                        {
                                            AheadTrigger = PriorDevice[0] + "-" + mindex;
                                            //此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            dbo.ExceSQL("update T_Monitor_Task set F_AheadTrigger='" + AheadTrigger + "' where F_MonitorIndex=" + TriggerTaskNo);
                                        }
                                    }

                                    #endregion

                                    #region 输送机的送货

                                    #region 运行提前检测光电组
                                    AheadDetect = "";
                                    tw = GetBindingDeviceIndexOut(PriorDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(PriorDevice[0]);//20101118

                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    ////20090803检测设备是否空闲idle
                                    //AheadDetect += ";" + "I" + PriorDevice[0].ToString();
                                    tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect = AheadDetect + ";D" + tw.ToString();// +";" + GetBeDetectedDevices(NextKeyDevice[0]);//20101118
                                    }

                                    #endregion
                                    if (DeviceAndOrderExitInMonitor(Mankind, ManFID, PriorDevice[0], 3, 0) == false)
                                    {
                                        int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                        sql = "INSERT INTO T_Monitor_Task " +
                                            "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                            " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                            " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_TxtParam)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + PriorDevice[0] + "," + 3 + "," + routeIDSub + "," + status + "," + PriorDevice[0] + ",0,"
                                            + "0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                        dbo.ExceSQL(sql);
                                        mainTask = mindex;
                                    }
                                    #endregion

                                    #region RGV的接货（被关联的任务）
                                    #region 运行提前检测光电组
                                    AheadDetect = "";
                                    tw = GetBindingDeviceIndexOut(PriorDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(PriorDevice[0]);//20101118
                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    ////20090803检测设备是否空闲idle
                                    //AheadDetect += ";" + "I" + PriorDevice[0].ToString();
                                    tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                    if (tw != "")
                                    {
                                        AheadDetect = AheadDetect + ";D" + tw.ToString() + ";" + GetBeDetectedDevices(NextKeyDevice[0]);//20101118
                                    }
                                    ////20090803检测设备是否空闲idle
                                    //AheadDetect += ";" + "I" + NextKeyDevice[0].ToString();
                                    #endregion

                                    Rgvorder = GetRGVOrder(PriorDevice[0], true);
                                    if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], Rgvorder, 0) == false)
                                    {
                                        int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                        sql = "INSERT INTO T_Monitor_Task " +
                                            "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                            " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                            " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_TxtParam)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + NextKeyDevice[0] + "," + Rgvorder + "," + routeIDSub + "," + status + "," + PriorDevice[0] + ",0" +
                                            ",0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                        dbo.ExceSQL(sql);
                                        dbo.ExceSQL("update T_Monitor_Task set F_Associate=" + mindex + " where F_MonitorIndex=" + mainTask);

                                    }

                                    #endregion

                                }

                                //获得RGV运行的送货位的设备索引：
                                if (NextDevice.Count > 0)
                                {
                                    Coor[0] = NextDevice[0];
                                    Coor[1] = 0;
                                    Coor[2] = 0;
                                    Coor[3] = 0;
                                    Coor[4] = 0;
                                    Coor[5] = 0;
                                }


                                #region 生成RGV指令:7-运动（到目标设备索引）+（2-左接货3-左送货）或者（4-右接货5-右送货）
                                //20090803检测设备是否空闲idle
                                AheadDetect = GetBeDetectedDevices(NextKeyDevice[0]);
                                //运动
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], 7, Coor[0]) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_TxtParam,F_AheadDetect)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + ",7," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + drv["FPALLETBARCODE"] + "','" + AheadDetect + "')";
                                    dbo.ExceSQL(sql);
                                }

                                #endregion

                                #region RGV的送货

                                #region 运行提前检测光电组
                                AheadDetect = "";
                                if (NextDevice[0] == 2246)//2246不检测出口有物，直接输送机报警
                                {
                                }
                                else
                                {
                                    tw = GetBindingDeviceIndex(NextDevice[0]);//目标输送机入口无探物，能运行
                                    if (tw != "")
                                    {
                                        AheadDetect = "D" + tw.ToString();// +";" + GetBeDetectedDevices(NextDevice[0]);//20101118
                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    tw = GetBindingDeviceIndexOut(NextDevice[0]);//目标输送机出口无探物，能运行
                                    if (tw != "")
                                    {
                                        AheadDetect = AheadDetect + ";D" + tw.ToString();//20101118
                                    }

                                }
                                tw = GetBindingDeviceIndex(NextKeyDevice[0]);//RGV有探物，能运行
                                if (tw != "")
                                {
                                    AheadDetect = AheadDetect + ";" + "D-" + tw.ToString() + ";" + GetBeDetectedDevices(NextKeyDevice[0]);//20101118
                                }
                                ////20090803检测设备是否空闲idle
                                //AheadDetect += ";" + "I" + NextKeyDevice[0].ToString();
                                #endregion

                                Rgvorder = GetRGVOrder(NextDevice[0], false);
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], Rgvorder, 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_TxtParam)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + Rgvorder + "," + routeIDSub + "," + status + "," + NextDevice[0] + ",0" +
                                        ",0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                    dbo.ExceSQL(sql);
                                    mainTask = mindex;
                                }

                                #endregion

                                #region 输送机的接货（被关联的任务）


                                #region 运行提前检测光电组
                                AheadDetect = "";
                                tw = GetBindingDeviceIndexOut(NextDevice[0]);//目标输送机出口无探物，能运行
                                if (tw != "")
                                {
                                    AheadDetect = AheadDetect + ";D" + tw.ToString();//20101118
                                }
                                if (NextDevice[0] != 2246)//2246不检测入口(操作员一侧)有物
                                {

                                    tw = GetBindingDeviceIndex(NextDevice[0]);//输送机入口无探物，能运行
                                    if (tw != "")
                                    {
                                        AheadDetect = "D" + tw.ToString() + ";" + GetBeDetectedDevices(NextDevice[0]);//20101118
                                    }
                                    else
                                    {
                                        AheadDetect = null;
                                    }
                                    ////20090803检测设备是否空闲idle
                                    //AheadDetect += ";" + "I" + NextDevice[0].ToString();
                                }
                                tw = GetBindingDeviceIndex(NextKeyDevice[0]);//RGV有探物，能运行
                                if (tw != "")
                                {
                                    AheadDetect = AheadDetect + ";D" + "-" + tw.ToString() + ";" + GetBeDetectedDevices(NextKeyDevice[0]);//20101118
                                }
                                ////20090803检测设备是否空闲idle
                                //AheadDetect += ";" + "I" + NextKeyDevice[0].ToString();
                                #endregion
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextDevice[0], 4, 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_TxtParam)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextDevice[0] + "," + 4 + "," + routeIDSub + "," + status + "," + NextDevice[0] + ",0,"
                                        + "0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                    dbo.ExceSQL(sql);
                                    dbo.ExceSQL("update T_Monitor_Task set F_Associate=" + mindex + " where F_MonitorIndex=" + mainTask);

                                }
                                #endregion
                                break;



                                #endregion
                            case 5:
   

                                #region 生成和管理交互虚拟设备的【出库确认】命令
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], NextKeyDevice[3], 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);

                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                        " F_AheadDetect,F_TxtParam)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + NextKeyDevice[3] + "," + routeIDSub + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                    dbo.ExceSQL(sql);
                                }
                                #endregion

                                break;
                            case 6:
                                #region AGV

                                #region 生成一个设备命令并且获得取送货坐标
                                //AGV取货：
                                if (PriorDevice.Count > 0)
                                {
                                    #region 前一设备是输送机

                                    if (PriorDevice[1] == 2)
                                    {
                                        if (uncontrol != "1")
                                        {//20091107
                                            List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                            if (newcur != null)
                                            {
                                                CurDevice = newcur;
                                            }
                                            int arrowdev;
                                            if (CurDevice[0] == PriorDevice[0])
                                            {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                                arrowdev = 0;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetBindingDeviceIndex(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118


                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                                if (CStaticClass.AGVAllowSingleFork == "0")//20100710
                                                {
                                                    #region 隔壁输送机空闲无物
                                                    //奇数加一；偶数减一
                                                    if ((CurDevice[0] % 2) == 0)
                                                    {
                                                        AheadDetect += ";D" + GetBindingDeviceIndexOut(CurDevice[0] - 1).ToString();//20101118
                                                    }
                                                    else
                                                    {
                                                        AheadDetect += ";D" + GetBindingDeviceIndexOut(CurDevice[0] + 1).ToString();//20101118
                                                    }
                                                    #endregion
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                arrowdev = PriorDevice[0];
                                                CurDevice[3] = 6;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetSendOutDetect(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118


                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();

                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                                tw = GetBindingDeviceIndex(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString() + ";" + GetBeDetectedDevices(nextConveyor[0]);//20101118
                                                }
                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                AheadDetect += ";" + "N" + nextConveyor[0].ToString();
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + nextConveyor[0].ToString();

                                                #endregion
                                            }
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                                dbo.ExceSQL(sql);
                                                #endregion
                                            }
                                        }
                                    }

                                    #endregion

                                    int[] Coor0_2 = new int[6] { 0, 0, 0, 0, 0, 0 };
                                    //如果PriorDevice是AGV通道，PriorDevice不拆分命令，获取送坐标，拆分AGV命令取、送货
                                    if (PriorDevice[1] == 11)
                                    {
                                        Coor0_2 =GetAGVAddressFromManage (Mankind, ManFID, drv);
                                    }
                                    else
                                    {
                                        //如果NextDevice是输送机则取送货命令，获取送坐标

                                        //如果NextDevice是固定站台则取送货命令，获取送坐标
                                        Coor0_2[1] =PriorDevice[0];
                                    }
                                    Coor[0] = Coor0_2[0];
                                    Coor[1] = Coor0_2[1];//站台设备索引
                                    Coor[2] = Coor0_2[2];
                                }
                                if (NextDevice.Count > 0)
                                {
                                    int[] Coor3_5 = new int[6] { 0, 0, 0, 0, 0, 0 };
                                    //如果NextDevice是AGV通道，NextDevice不拆分命令，获取送坐标，拆分AGV命令取、送货
                                    if (NextDevice[1] == 11)
                                    {
                                        Coor3_5 = GetAGVAddressFromManage(Mankind, ManFID, drv);
                                    }
                                    else
                                    {
                                        //如果NextDevice是输送机则取送货命令，获取送坐标

                                        //如果NextDevice是固定站台则取送货命令，获取送坐标
                                        Coor3_5[4] =NextDevice[0];
                                    }
                                    Coor[3] = Coor3_5[3];
                                    Coor[4] = Coor3_5[4];//站台设备索引
                                    Coor[5] = Coor3_5[5];
                                }
                                #endregion

                                #region 生成AGV指令:取货、送货
                                //转换调度任务类型和AGV任务类型
                                int agvorder = 0;

                                #region AGV取货
                                if (PriorDevice.Count > 0)
                                {
                                    agvorder = 1;
                                    RunningLock = "";
                                    if (PriorDevice[1] == 2)
                                    {
                                        #region 运行时锁定设备组
                                        RunningLock = PriorDevice[0].ToString();
                                        //取货时锁定隔壁输送机
                                        if (CStaticClass.AGVAllowSingleFork == "0")
                                        {
                                            if ((PriorDevice[0] % 2) == 0)
                                            {
                                                RunningLock += ";" + (PriorDevice[0] - 1).ToString();
                                            }
                                            else
                                            {
                                                RunningLock += ";" + (PriorDevice[0] + 1).ToString();
                                            }
                                        }
                                        #endregion
                                        AheadDetect = "-" + GetBindingDeviceIndexOut(PriorDevice[0]).ToString() + ";I" + PriorDevice[0].ToString();
                                        #region 增加检测顶升是否在低位20100710
                                        AheadDetect += ";-" + PriorDevice[0].ToString() + "3";
                                        #endregion
                                    }
                                    //else if (PriorDevice[1] == 9)//固定站台（机台）
                                    //{
                                        
                                    //    AheadDetect = "H" + PriorDevice[0].ToString();

                                    //}
                                    //else if (PriorDevice[1] == 11)//AGV通道
                                    //{

                                    //    AheadDetect = "H" + Coor[1].ToString();

                                    //}
                                    if (NextDevice.Count > 0)
                                    {
                                        if (NextDevice[1] == 2)
                                        {//20100714
                                            AheadDetect += ";" + GetBindingDeviceIndex(NextDevice[0]).ToString() + ";I" + NextDevice[0].ToString() + ";N" + NextDevice[0].ToString();
                                            if (CStaticClass.AGVAllowSingleFork == "0")//20100710
                                            {
                                                #region 隔壁输送机空闲无物
                                                //奇数加一；偶数减一
                                                if ((NextDevice[0] % 2) == 0)
                                                {
                                                    AheadDetect += ";D" + GetBindingDeviceIndex(NextDevice[0] - 1).ToString() + ";I" + (NextDevice[0] - 1).ToString();//20101118
                                                }
                                                else
                                                {
                                                    AheadDetect += ";D" + GetBindingDeviceIndex(NextDevice[0] + 1).ToString() + ";I" + (NextDevice[0] + 1).ToString();//20101118
                                                }
                                                #endregion
                                            }
                                        }
                                        //else if (NextDevice[1] == 9)//固定站台（机台）
                                        //{

                                        //    AheadDetect += ";N" + NextDevice[0].ToString();
                                        //    #region 隔壁机台无物
                                        //    //奇数加一；偶数减一
                                        //    if ((NextDevice[0] % 2) == 0)
                                        //    {
                                        //        AheadDetect += ";N" + (NextDevice[0] - 1).ToString();
                                        //    }
                                        //    else
                                        //    {
                                        //        AheadDetect += ";N" + (NextDevice[0] + 1).ToString();
                                        //    }
                                        //    #endregion

                                        //}
                                        //else if (NextDevice[1] == 11)//AGV通道
                                        //{

                                        //    AheadDetect += ";N" + Coor[4].ToString();
                                        //    #region 隔壁机台无物
                                        //    //奇数加一；偶数减一
                                        //    if ((Coor[4] % 2) == 0)
                                        //    {
                                        //        AheadDetect += ";N" + (Coor[4] - 1).ToString();
                                        //    }
                                        //    else
                                        //    {
                                        //        AheadDetect += ";N" + (Coor[4] + 1).ToString();
                                        //    }
                                        //    #endregion

                                        //}
                                    }
                                    if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], agvorder, 0) == false)
                                    {//20091107
                                        int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                        sql = "INSERT INTO T_Monitor_Task " +
                                            "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                            " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                            " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_UseAwayFork)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + NextKeyDevice[0] + ","+agvorder+"," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                            + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + AheadDetect + "','" + RunningLock + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                        dbo.ExceSQL(sql);
                                        ////完成应答3
                                        //int mindex1 = ccf.GetMonitorIndex(ManFID, Mankind);
                                        //sql = "INSERT INTO T_Monitor_Task " +
                                        //    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        //    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        //    " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_AgvTask,F_UseAwayFork)" +
                                        //"VALUES (" + ManFID + "," + Mankind + "," + (mindex1) + "," + drv["FTASKLEVEL"]
                                        //    + "," + NextKeyDevice[0] + ",3," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                        //    + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'','','" + drv["FPALLETBARCODE"] + "'," + mindex + ",'" + drv["FUseAwayFork"] + "')";
                                        //dbo.ExceSQL(sql);
                                    }


                                }
                                #endregion

                                #region ＡＧＶ运行到送货点
                                agvorder = 4;
                                AheadDetect = "";
                                RunningLock = "";
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], agvorder, 0) == false)
                                    {//20091107
                                        int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                        sql = "INSERT INTO T_Monitor_Task " +
                                            "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                            " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                            " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_UseAwayFork)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + NextKeyDevice[0] + "," + agvorder + "," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                            + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + AheadDetect + "','" + RunningLock + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                        dbo.ExceSQL(sql);
                                        ////完成应答3
                                        //int mindex1 = ccf.GetMonitorIndex(ManFID, Mankind);
                                        //sql = "INSERT INTO T_Monitor_Task " +
                                        //    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        //    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                        //    " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_AgvTask,F_UseAwayFork)" +
                                        //"VALUES (" + ManFID + "," + Mankind + "," + (mindex1) + "," + drv["FTASKLEVEL"]
                                        //    + "," + NextKeyDevice[0] + ",3," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                        //    + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'','','" + drv["FPALLETBARCODE"] + "'," + mindex + ",'" + drv["FUseAwayFork"] + "')";
                                        //dbo.ExceSQL(sql);
                                    }
                                #endregion

                                #region AGV送货
                                if (NextDevice.Count > 0)
                                {
                                    agvorder = 2;
                                    RunningLock = "";
                                    if (NextDevice[1] == 2)
                                    {//20100714
                                        #region 运行时锁定设备组
                                        RunningLock = NextDevice[0].ToString();
                                        //送货时锁定隔壁输送机
                                        if (CStaticClass.AGVAllowSingleFork == "0")
                                        {
                                            if ((NextDevice[0] % 2) == 0)
                                            {
                                                RunningLock += ";" + (NextDevice[0] - 1).ToString();
                                            }
                                            else
                                            {
                                                RunningLock += ";" + (NextDevice[0] + 1).ToString();
                                            }
                                        }
                                        #endregion
                                        AheadDetect = GetBindingDeviceIndex(NextDevice[0]).ToString() + ";I" + NextDevice[0].ToString() + ";N" + NextDevice[0].ToString();
                                        if (CStaticClass.AGVAllowSingleFork == "0")
                                        {
                                            #region 隔壁输送机空闲无物
                                            //奇数加一；偶数减一
                                            if ((NextDevice[0] % 2) == 0)
                                            {
                                                AheadDetect = "D" + GetBindingDeviceIndex(NextDevice[0] - 1).ToString() + ";I" + (NextDevice[0] - 1).ToString();//20101118
                                            }
                                            else
                                            {
                                                AheadDetect = "D" + GetBindingDeviceIndex(NextDevice[0] + 1).ToString() + ";I" + (NextDevice[0] + 1).ToString();//20101118
                                            }
                                            #endregion
                                        }

                                    }
                                    //else if (NextDevice[1] == 9)//固定站台（机台）
                                    //{

                                    //    AheadDetect = "N" + NextDevice[0].ToString();
                                    //    #region 隔壁机台无物
                                    //    //奇数加一；偶数减一
                                    //    if ((NextDevice[0] % 2) == 0)
                                    //    {
                                    //        AheadDetect += ";N" + (NextDevice[0] - 1).ToString();
                                    //    }
                                    //    else
                                    //    {
                                    //        AheadDetect += ";N" + (NextDevice[0] + 1).ToString() ;
                                    //    }
                                    //    #endregion

                                    //}
                                    //else if (NextDevice[1] == 11)//AGV通道
                                    //{

                                    //    AheadDetect = "N" + Coor[4].ToString();
                                    //    #region 隔壁机台无物
                                    //    //奇数加一；偶数减一
                                    //    if ((Coor[4] % 2) == 0)
                                    //    {
                                    //        AheadDetect += ";N" + (Coor[4] - 1).ToString();
                                    //    }
                                    //    else
                                    //    {
                                    //        AheadDetect += ";N" + (Coor[4] + 1).ToString();
                                    //    }
                                    //    #endregion

                                    //}
                                    if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], agvorder, 0) == false)
                                    {//20091107
                                        int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                        sql = "INSERT INTO T_Monitor_Task " +
                                            "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                            " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                            " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_UseAwayFork)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + NextKeyDevice[0] + "," + agvorder + "," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                            + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'" + AheadDetect + "','" + RunningLock + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "')";
                                        dbo.ExceSQL(sql);
                                    //    //完成应答3
                                    //    int mindex1 = ccf.GetMonitorIndex(ManFID, Mankind);
                                    //    sql = "INSERT INTO T_Monitor_Task " +
                                    //        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                    //        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2," +
                                    //        " F_NumParam3, F_NumParam4,F_NumParam5, F_NumParam6,F_AheadDetect,F_RunningLock,F_TxtParam,F_AgvTask,F_UseAwayFork)" +
                                    //    "VALUES (" + ManFID + "," + Mankind + "," + (mindex1) + "," + drv["FTASKLEVEL"]
                                    //        + "," + NextKeyDevice[0] + ",3," + routeIDSub + "," + status + "," + Coor[0] + "," + Coor[1]
                                    //        + "," + Coor[2] + "," + Coor[3] + "," + Coor[4] + "," + Coor[5] + ",'','','" + drv["FPALLETBARCODE"] + "'," + mindex + ",'" + drv["FUseAwayFork"] + "')";
                                    //    dbo.ExceSQL(sql);
                                    }


                                }
                                #endregion

                                #endregion

                                #endregion
                                break;
                            case 7:
                                #region 条码扫描仪（托盘条码比对1）
                                if (PriorDevice.Count > 0)
                                {
                                    //如果PriorDevice是输送机则生成输送机命令【CurDevice-->PriorDevice目标设备,出库：2】，
                                    //收到输送机PriorDevice的PLC上报的运行状态则提前触发RGV运行命令（7），然后是取送货命令，获取堆垛机取坐标
                                    #region 前一设备是输送机

                                    if (PriorDevice[1] == 2)
                                    {
                                        if (uncontrol != "1")
                                        {//20091107
                                            List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                            if (newcur != null)
                                            {
                                                CurDevice = newcur;
                                            }
                                            int arrowdev;
                                            if (CurDevice[0] == PriorDevice[0])
                                            {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                                arrowdev = 0;
                                                #region 运行提前检测光电组
                                                if ((CurDevice[3] == 1)||(CurDevice[3] == 2))
                                                {
                                                    //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                    tw = GetBindingDeviceIndex(CurDevice[0]);
                                                    if (tw != "")
                                                    {
                                                        AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                    }
                                                    else
                                                    {
                                                        AheadDetect = null;
                                                    }
                                                    tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                    if (tw != "")
                                                    {
                                                        AheadDetect += ";D" + tw.ToString();//20101118
                                                    }

                                                }
                          
                                                #endregion
                                            }
                                            else
                                            {
                                                arrowdev = PriorDevice[0];
                                                CurDevice[3] = 6;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetSendOutDetect(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    //AheadDetect = "D-" + tw.ToString();//20101118
                                                    AheadDetect = "D-" + tw.ToString();// +";" + GetBeDetectedDevices(CurDevice[0]);//20101220
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                //20100221
                                                AheadDetect += ";" + GetBeDetectedDevices(CurDevice[0]);
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();

                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                                tw = GetBindingDeviceIndex(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();// +";" + GetBeDetectedDevices(nextConveyor[0]);//20101118
                                                }
                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                //20110318
                                                tw = GetBeDetectedDevices(nextConveyor[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";" + tw.ToString();
                                                }
                                                //if (CurDevice[0] == 1223)//辅料库AGV取货站台的前一个站台
                                                //{
                                                //    AheadDetect += ";" + "N" + nextConveyor[0].ToString();
                                                //}
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + nextConveyor[0].ToString();
                                                #endregion
                                            }
                                            AheadTrigger = PriorDevice[0].ToString(); //+ "-" + (被触发的调度任务号);//此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                                dbo.ExceSQL(sql);
                                                #endregion


                                            }
                                        }
                                    }

                                    #endregion

                                }
                                #region 运行提前检测光电组
                                //20110318
                                tw = GetBindingDeviceIndex(PriorDevice[0]);
                                if (tw != "")
                                {
                                    AheadDetect = "D-" + tw.ToString() +";"+ GetBeDetectedDevices(PriorDevice[0]);
                                }
                                else
                                {
                                    AheadDetect = null;
                                }
                                #endregion

                                #region 生成条码比对命令
                                //20110318
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], NextKeyDevice[3], 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);

                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                        " F_AheadDetect,F_TxtParam)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + NextKeyDevice[3] + "," + routeIDSub + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                    dbo.ExceSQL(sql);
                                }
                                #endregion


                                #endregion
                                break;
                            case 12:
                                #region 虚拟关键设备（只作为路径分割点）
                                if (PriorDevice.Count > 0)
                                {
                                    //如果PriorDevice是输送机则生成输送机命令【CurDevice-->PriorDevice目标设备,出库：2】，
                                    //收到输送机PriorDevice的PLC上报的运行状态则提前触发RGV运行命令（7），然后是取送货命令，获取堆垛机取坐标
                                    #region 前一设备是输送机

                                    if (PriorDevice[1] == 2||PriorDevice[1] == 3)
                                    {
                                        if (uncontrol != "1")
                                        {//20091107
                                            List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                            if (newcur != null)
                                            {
                                                CurDevice = newcur;
                                            }
                                            int arrowdev;
                                            if (CurDevice[0] == PriorDevice[0])
                                            {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                                arrowdev = 0;
                                                CurDevice[3] = 2;
                                                arrowdev = CurDevice[0];
                                                #region 运行提前检测光电组
                                           
                                                    if ((CurDevice[3] == 1) || (CurDevice[3] == 2))
                                                    {
                                                        //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                        tw = GetBindingDeviceIndex(CurDevice[0]);
                                                        if (tw != "")
                                                        {
                                                            AheadDetect = "D-" + tw.ToString();//20101118
                                                        }
                                                        else
                                                        {
                                                            AheadDetect = null;
                                                        }
                                                        tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                        if (tw != "")
                                                        {
                                                            AheadDetect += ";D" + tw.ToString();//20101118
                                                        }
                                                    }

                                                    AheadDetect += ";"+GetBeDetectedDevices(CurDevice[0]);//20110401
                                               
                                                #endregion
                                            }
                                            else
                                            {
                                                arrowdev = PriorDevice[0];
                                                CurDevice[3] = 6;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetSendOutDetect(CurDevice[0]);
                                                if (tw != "")
                                                {//20091107
                                                    AheadDetect = "D-" + tw.ToString(); //20101118
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                ////20090803检测设备是否空闲idle
                                                ////20110108
                                                AheadDetect += ";" + GetBeDetectedDevices(CurDevice[0]); 
                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                                tw = GetBindingDeviceIndex(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                tw = GetBeDetectedDevices(nextConveyor[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";" + tw.ToString();
                                                }
                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                // 12041异常口会作回库口使用，必须保证两者不会堵死
                                                //zx20131122
                                                if (arrowdev == 12041) 
                                                {
                                                   
                                                    tw = GetBindingDeviceIndex(12041);
                                                    if (tw != "")
                                                    {
                                                        AheadDetect += ";D" + tw.ToString();
                                                    }
                                                    tw = GetBeDetectedDevices(12041);
                                                    if (tw != "")
                                                    {//20101118
                                                        AheadDetect += ";" + tw.ToString();
                                                    }
                                                    tw = GetBindingDeviceIndexOut(12041);
                                                    if (tw != "")
                                                    {
                                                        AheadDetect += ";D" + tw.ToString();
                                                    }
                                                }

                                                #endregion
                                            }

                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam,F_NumParam5,F_NumParam6)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "'," + drv["UNPACK_QUANTITY"] + "," + drv["BOX_QUANTITY"] + ")";
                                               
                                                dbo.ExceSQL(sql);
                                                #endregion


                                            }
                                             //2011/11/16 如果结束位置的输送机在拆盘机下 ，则该输送机生成一个拆盘指令，指定输送机要拆的数量
                                            if (arrowdev == 12028)
                                            {
                                                // AheadDetect = string.Empty;
                                               
                                                //CurDevice[3] = unpacktype(ManFID);
                                             
                                                //AheadDetect = "I" + arrowdev.ToString();
                                              
                                                //if (DeviceAndOrderExitInMonitor(Mankind, ManFID, arrowdev, CurDevice[3], 0) == false)
                                                //{
                                                //    #region 运行时锁定设备组

                                                //    #endregion

                                                //    #region 生成输送机命令
                                                //    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                //    TriggerTaskNo = mindex;
                                               
                                                //   // int handfid = GetManageHandIdx();
                                                //    //tw = string.Empty;
                                                //    //tw = GetBindingDeviceIndex(arrowdev);
                                               

                                                //    sql = "INSERT INTO T_Monitor_Task " +
                                                //        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                //        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                //        " F_AheadDetect,F_TxtParam,F_NumParam5)" +
                                                //    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                //        + "," + arrowdev + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + arrowdev + ","
                                                //        + "0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "'," + drv["BOX_QUANTITY"] + ")";
                                                //    if (CurDevice[3] != -1)
                                                //    {
                                                //        dbo.ExceSQL(sql);
                                                //    }


                                                //    #endregion
                                                //}
                                            }


                                        }
                                    }
                                    #endregion

                                }
                                #endregion
                                break;
                            case 30:
                                #region  20100617和管理交互虚拟设备，1：出库托盘确认
                                if (PriorDevice.Count > 0)
                                {
                                    //如果PriorDevice是输送机则生成输送机命令【CurDevice-->PriorDevice目标设备,出库：2】，
                                    //收到输送机PriorDevice的PLC上报的运行状态则提前触发RGV运行命令（7），然后是取送货命令，获取堆垛机取坐标
                                    #region 前一设备是输送机

                                    if (PriorDevice[1] == 2)
                                    {
                                        if (uncontrol != "1")
                                        {//20091107
                                            List<int> newcur = NewCurDevice(PriorDevice0, PriorKeyDevice0);
                                            if (newcur != null)
                                            {
                                                CurDevice = newcur;
                                            }
                                            int arrowdev;
                                            if (CurDevice[0] == PriorDevice[0])
                                            {//输送机的起点设备和终点设备相同时，目标设备索引置为零
                                                arrowdev = 0;
                                                #region 运行提前检测光电组
                                                if ((CurDevice[3] == 1) || (CurDevice[3] == 2))
                                                {
                                                    //CurDevice的F_BindingDevice里存的光电开关的设备所引。CurDevice有探物
                                                    tw = GetBindingDeviceIndex(CurDevice[0]);
                                                    if (tw != "")
                                                    {
                                                        AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                    }
                                                    else
                                                    {
                                                        AheadDetect = null;
                                                    }
                                                    tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                    if (tw != "")
                                                    {
                                                        AheadDetect += ";D" + tw.ToString();//20101118
                                                    }

                                                }
                                                //else if (CurDevice[3] == 2)
                                                //{
                                                //    tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                                //    if (tw != "")
                                                //    {
                                                //        AheadDetect = "D-" + tw.ToString() + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                //    }
                                                //    else
                                                //    {
                                                //        AheadDetect = null;
                                                //    }
                                                //}
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();
                                                #endregion
                                            }
                                            else
                                            {
                                                arrowdev = PriorDevice[0];
                                                CurDevice[3] = 6;
                                                #region 运行提前检测光电组
                                                //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                                tw = GetSendOutDetect(CurDevice[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect = "D-" + tw.ToString();//20101118
                                                }
                                                else
                                                {
                                                    AheadDetect = null;
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + CurDevice[0].ToString();

                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                                tw = GetBindingDeviceIndex(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString() + ";" + GetBeDetectedDevices(nextConveyor[0]);//20101118
                                                }
                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                if (CurDevice[0] == 1223)//辅料库AGV取货站台的前一个站台
                                                {
                                                    AheadDetect += ";" + "N" + nextConveyor[0].ToString();
                                                }
                                                ////20090803检测设备是否空闲idle
                                                //AheadDetect += ";" + "I" + nextConveyor[0].ToString();
                                                #endregion
                                            }
                                            AheadTrigger = PriorDevice[0].ToString(); //+ "-" + (被触发的调度任务号);//此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #region 运行时锁定设备组

                                                #endregion

                                                #region 生成输送机命令
                                                int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                                TriggerTaskNo = mindex;

                                                sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                                dbo.ExceSQL(sql);
                                                #endregion


                                            }
                                        }
                                    }

                                    #endregion

                                }
                                #region 运行提前检测光电组

                                //tw = GetBindingDeviceIndexOut(PriorDevice[0]);
                                //if (tw != "")
                                //{
                                //    AheadDetect = "D-" + tw.ToString();//20101118
                                //}
                                //else
                                //{
                                //    AheadDetect = null;
                                //}
                                #endregion

                                #region 生成和管理交互虚拟设备的【出库确认】命令
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], NextKeyDevice[3], 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);

                                    sql = "INSERT INTO T_Monitor_Task " +
                                        "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                        " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                        " F_AheadDetect,F_TxtParam)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + NextKeyDevice[3] + "," + routeIDSub + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "')";
                                    dbo.ExceSQL(sql);
                                }
                                #endregion


                                #endregion

                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {

                    }
                    PriorDevice0 = PriorDevice;
                    PriorKeyDevice0 = NextKeyDevice;
                    //20091107
                    PriorDevice = null;
                    NextKeyDevice = null;
                    CurDevice = null;
                    NextKeyDevice = null;
                }

                dbo.TransCommit();
                //20091107
                PriorDevice0 = null;
                PriorKeyDevice0 = null;
                
                
                return 1;
            }
            catch (Exception ex)
            {
                dbo.TransRollback();
                DisassembleTaskError = "ControlSystem.CDisassembleTask.CreateMonitor时发生错误:" + ex.Message;
                return 0;
            }
            finally
            {
                dvRoute = null;
                dvs = null;

            }
        }
        /// <summary>
        /// 查找路径运行方向的反方向的最近的设备，返回值：索引0：设备所引；索引1：设备类型;2:路径序号；3：设备命令
        /// </summary>
        /// <param name="CurRouteID">路径ID</param>
        /// <param name="CurSerialNumber">路径上的序号</param>
        /// <returns></returns>
        public static List<int> GetPriorDevice(int CurRouteIDSub, int CurSerialNumber)
        {
            
            List<int> keyDevice = new List<int>();
            string sql;DataView dvRoute;
            try
            {
                //后续设备最近的设备
                sql = "SELECT T_Base_Route_Device.F_DeviceIndex,F_DeviceOrder, T_Base_Route_Device.F_SerialNumber, " +
                        "T_Base_Device_Command.F_DeviceCommandIndex,T_Base_Device.F_DeviceKindIndex FROM T_Base_Device_Command " +
                        ",T_Base_Device,T_Base_Route_Device where T_Base_Device_Command.F_DeviceKindIndex = T_Base_Device.F_DeviceKindIndex" +
                        " and T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and F_RouteIDSub=" +
                        CurRouteIDSub + " and F_SerialNumber < " + CurSerialNumber + "  order by F_SerialNumber desc ";
                dvRoute = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvRoute.Count > 0)
                {
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceIndex"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceKindIndex"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_SerialNumber"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceOrder"]));
                }
                return keyDevice;
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "ControlSystem.CDisassembleTask.GetPriorDevice:" + ex.Message;
                return null;
            }
            finally
            {
                keyDevice=null;
                dvRoute = null ;
                sql = null;
            }
        }
        /// <summary>
        /// 对于长串输送机组，需要判断当前设备的下一个设备是否具备发送状态
        /// </summary>
        /// <param name="CurRouteIDSub">当前调度的子路径</param>
        /// <param name="CurSerialNumber">输送机组的当前输送机对应的路径序号</param>
        /// <returns></returns>
        static List<int> GetCurConveyorNextDevice(int CurRouteIDSub, int CurSerialNumber)
        {
            List<int> CurDeviceNextDev = new List<int>();
            DataView dvRoute; string sql;
            try
            {
                //找到前一个设备CurDevice的下一个设备
                sql = "SELECT T_Base_Route_Device.F_DeviceIndex,F_DeviceOrder, T_Base_Route_Device.F_SerialNumber, " +
                        "T_Base_Device_Command.F_DeviceCommandIndex,T_Base_Device.F_DeviceKindIndex FROM T_Base_Device_Command " +
                        ",T_Base_Device,T_Base_Route_Device where T_Base_Device_Command.F_DeviceKindIndex = T_Base_Device.F_DeviceKindIndex" +
                        " and T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and F_RouteIDSub=" +
                        CurRouteIDSub + " and F_SerialNumber > " + CurSerialNumber + " and T_Base_Device.F_DeviceKindIndex=2 order by F_SerialNumber asc ";
                dvRoute = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvRoute.Count > 0)
                {
                    CurDeviceNextDev.Add(Convert.ToInt32(dvRoute[0]["F_DeviceIndex"]));
                    CurDeviceNextDev.Add(Convert.ToInt32(dvRoute[0]["F_DeviceKindIndex"]));
                    CurDeviceNextDev.Add(Convert.ToInt32(dvRoute[0]["F_SerialNumber"]));
                    CurDeviceNextDev.Add(Convert.ToInt32(dvRoute[0]["F_DeviceOrder"]));
                }
                return CurDeviceNextDev;
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "ControlSystem.CDisassembleTask.GetCurConveyorNextDevice:" + ex.Message;
                return null;
            }
            finally
            {
                CurDeviceNextDev=null;
                dvRoute = null;
                sql =null;
            }
        }
        /// <summary>
        /// 查找路径方向上最近的关键设备，返回值：索引0：设备所引；索引1：设备类型；2:路径序号；3：设备命令
        /// </summary>
        /// <param name="CurRouteID">路径ID</param>
        /// <param name="CurSerialNumber">路径上的序号</param>
        /// <returns></returns>
        static List<int> GetNextKeyDevice(int CurRouteIDSub, int CurSerialNumber)
        {
            List<int> keyDevice = new List<int>(); DataView dvRoute; DataView dv; string sql;
            try
            {
                //首先判断本设备是否为关键设备
                dv = dbo.ExceSQL("SELECT F_SerialNumber, T_Base_Device.F_DeviceIndex,F_DeviceOrder,F_DeviceKindIndex FROM T_Base_Device," +
                    "T_Base_Route_Device  where T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex " +
                    " and F_RouteIDSub=" + CurRouteIDSub + " and F_SerialNumber=" + CurSerialNumber
                    + " and F_KeyDevice = '1'").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    keyDevice.Add(Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                    keyDevice.Add(Convert.ToInt32(dv[0]["F_DeviceKindIndex"]));
                    keyDevice.Add(Convert.ToInt32(dv[0]["F_SerialNumber"]));
                    keyDevice.Add(Convert.ToInt32(dv[0]["F_DeviceOrder"]));
                    return keyDevice;
                }
                //然后依次判断后续设备最近的关键设备
                sql = "SELECT T_Base_Route_Device.F_DeviceIndex,F_DeviceOrder, T_Base_Route_Device.F_SerialNumber, " +
                        "T_Base_Device_Command.F_DeviceCommandIndex,T_Base_Device.F_DeviceKindIndex FROM T_Base_Device_Command " +
                        ",T_Base_Device,T_Base_Route_Device where T_Base_Device_Command.F_DeviceKindIndex = T_Base_Device.F_DeviceKindIndex" +
                        " and T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and F_RouteIDSub=" +
                        CurRouteIDSub + " and F_SerialNumber > " + CurSerialNumber + " and T_Base_Device.F_KeyDevice = '1' order by F_SerialNumber asc ";
                dvRoute = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvRoute.Count > 0)
                {
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceIndex"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceKindIndex"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_SerialNumber"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceOrder"]));

                }
                return keyDevice;
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "ControlSystem.CDisassembleTask.GetNextKeyDevice:" + ex.Message;
                return null;
            }
            finally
            {
                keyDevice=null;
                dvRoute = null;
                dv = null;
                sql = null;
            }
        }
        /// <summary>
        /// 查找路径方向上下一个设备，返回值：索引0：设备所引；索引1：设备类型；2:路径序号；3：设备命令
        /// </summary>
        /// <param name="CurRouteID">路径ID</param>
        /// <param name="CurSerialNumber">路径上的序号</param>
        /// <returns></returns>
        public static List<int> GetNextDevice(int CurRouteIDSub, int CurSerialNumber)
        {
            List<int> keyDevice = new List<int>(); DataView dvRoute; string sql;
            try
            {
                //然后依次判断后续设备最近的设备
                sql = "SELECT T_Base_Route_Device.F_DeviceIndex,F_DeviceOrder, T_Base_Route_Device.F_SerialNumber, " +
                        "T_Base_Device_Command.F_DeviceCommandIndex,T_Base_Device.F_DeviceKindIndex FROM T_Base_Device_Command " +
                        ",T_Base_Device,T_Base_Route_Device where T_Base_Device_Command.F_DeviceKindIndex = T_Base_Device.F_DeviceKindIndex" +
                        " and T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and F_RouteIDSub=" +
                        CurRouteIDSub + " and F_SerialNumber > " + CurSerialNumber + "  order by F_SerialNumber asc ";
                dvRoute = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvRoute.Count > 0)
                {
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceIndex"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceKindIndex"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_SerialNumber"]));
                    keyDevice.Add(Convert.ToInt32(dvRoute[0]["F_DeviceOrder"]));

                }
                return keyDevice;
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "ControlSystem.CDisassembleTask.GetNextDevice:" + ex.Message;
                return null;
            }
            finally
            {
                keyDevice=null;
                dvRoute = null;
                sql = null;
            }
        }
        /// <summary>
        ///  获得AGV坐标
        /// </summary>
        /// <param name="Mankind">调度任务类型</param>
        /// <param name="ManFID">调度任务索引</param>
        /// <param name="IOType">搬运任务类型：1，入库（送坐标）；2：出库（取坐标）；3：移库（取和送坐标）</param>
        /// <returns></returns>
        static int[] GetAGVAddressFromManage(int Mankind, int ManFID, DataRowView drv)
        {
            int[] stackCoo = new int[6] { 0, 0, 0, 0, 0, 0 };//取排-列-层（Z-X-Y）；送排-列-层（Z-X-Y）
            string sql = string.Empty ;
            char[] cc = new char[1] { '-' };
            string[] split = new string[3];
            DataView dv;
            try
            {
                switch (Convert.ToInt32(drv["FCONTROLTASKTYPE"]))
                {
                    case 1://入库，取坐标：机台站台；送坐标：路径下一个设备
                        sql = "SELECT FSTARTCELL,FSTARTDEVICE,FENDDEVICE  FROM T_Manage_Task WHERE (FID = " + ManFID + ") AND (F_ManageTaskKindIndex = " + Mankind + ")";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            stackCoo[0] = 0;
                            stackCoo[1] =Convert.ToInt32(dv[0]["FSTARTCELL"]);
                            stackCoo[2] = 0;

                            stackCoo[3] = 0;
                            stackCoo[4] = 0;
                            stackCoo[5] = 0;
                        }
                        else
                        {
                            DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage时没能从调度任务获得AGV坐标！";
                            return null;
                        }
                        break;

                    case 2://出库：取坐标在路径上一个设备取；送坐标：机台站台
                        sql = "SELECT FENDCELL,FENDDEVICE  FROM T_Manage_Task WHERE (FID = " + ManFID + ") AND (F_ManageTaskKindIndex = " + Mankind + ")";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            stackCoo[0] = 0;
                            stackCoo[1] = 0;
                            stackCoo[2] = 0;

                            stackCoo[3] = 0;
                            stackCoo[4] = Convert.ToInt32(dv[0]["FENDCELL"]);
                            stackCoo[5] = 0;
                        }
                        else
                        {
                            DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage时没能从调度任务获得AGV坐标！";
                            return null;
                        }
                        break;
                    
                    default:
                        break;
                    case 3://移库，取坐标：机台站台；送坐标：路径下一个设备
                        sql = "SELECT FSTARTCELL,FSTARTDEVICE,FENDCELL,FENDDEVICE  FROM T_Manage_Task WHERE (FID = " + ManFID + ") AND (F_ManageTaskKindIndex = " + Mankind + ")";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            stackCoo[0] = 0;
                            if (Information.IsNumeric(dv[0]["FSTARTCELL"])==true)
                            {
                                stackCoo[1] = Convert.ToInt32(dv[0]["FSTARTCELL"]);
                            }
                            else
                            {
                                stackCoo[1] = 0;
                            }
                            stackCoo[2] = 0;

                            stackCoo[3] = 0;
                            if(Information.IsNumeric(dv[0]["FENDCELL"])==true)
                            {
                            stackCoo[4] = Convert.ToInt32(dv[0]["FENDCELL"]);
                            }
                            else
                            {
                                stackCoo[4] = 0;
                            }
                            stackCoo[5] = 0;
                        }
                        else
                        {
                            DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage时没能从调度任务获得AGV坐标！";
                            return null;
                        }
                        break;
                }


                return stackCoo;
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "ControlSystem.CDisassembleTask.GetAGVAddressFromManage:" + ex.Message;
                return null;
            }
            finally
            {
                stackCoo = null;
                sql = null ;
               cc = null ;
               split =null ;
               dv=null ;
            }
            
        }
        /// <summary>
        /// 在表T_Base_AGV_Gate获得AGV地址
        /// </summary>
        /// <param name="devindex">AGV地址对应的设备索引</param>
        /// <returns></returns>
        static int GetAGVAddressFromAgvGate(int devindex)
        {
            DataView dv;
            try
            {
                dv = dbo.ExceSQL("select * from T_Base_AGV_Gate where F_AGVGateDeviceIndex=" + devindex).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_Address"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                _DisassembleTaskError = "ControlSystem.CDisassembleTask.GetAGVAddressFromAgvGate:" + ex.Message;
                return -1;
            }
            finally
            {
                dv = null;
            }
        }
        /// <summary>
        ///  获得堆垛机坐标取排-列-层（Z-X-Y）；送排-列-层（Z-X-Y）
        /// </summary>
        /// <param name="Mankind">调度任务类型</param>
        /// <param name="ManFID">调度任务索引</param>
        /// <param name="IOType">搬运任务类型：1，入库（送坐标）；2：出库（取坐标）；3：移库（取和送坐标）</param>
        /// <returns></returns>
        static int[] GetStackCoordinateFromManage(int Mankind, int ManFID,DataRowView drv)
        {
            int[] stackCoo = new int[6] { 0, 0, 0, 0, 0, 0 };//取排-列-层（Z-X-Y）；送排-列-层（Z-X-Y）
            string sql =string.Empty ;
            char[] cc = new char[1] {'-' };
            string[] split = new string[3];
            DataView dv;
            try
            {
                switch (Convert.ToInt32(drv["FCONTROLTASKTYPE"]))
                {
                    case 1://入库，送坐标
                        sql = "SELECT FENDCELL  FROM T_Manage_Task WHERE (FID = " + ManFID + ") AND (F_ManageTaskKindIndex = " + Mankind + ")";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            split = dv[0]["FENDCELL"].ToString().Split(cc);
                            stackCoo[3] = Convert.ToInt32(split[0]);
                            stackCoo[4] = Convert.ToInt32(split[1]);
                            stackCoo[5] = Convert.ToInt32(split[2]);
                        }
                        else
                        {
                            DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage时没能从调度任务获得堆垛机坐标！";
                            return null;
                        }
                        break;

                    case 2://出库，取坐标
                        sql = "SELECT FSTARTCELL  FROM T_Manage_Task WHERE (FID = " + ManFID + ") AND (F_ManageTaskKindIndex = " + Mankind + ")";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            split = dv[0]["FSTARTCELL"].ToString().Split(cc);
                            stackCoo[0] = Convert.ToInt32(split[0]);
                            stackCoo[1] = Convert.ToInt32(split[1]);
                            stackCoo[2] = Convert.ToInt32(split[2]);
                        }
                        else
                        {
                            DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage时没能从调度任务获得堆垛机坐标！";
                            return null;
                        }
                        break;
                    case 3:
                        sql = "SELECT FSTARTCELL,FENDCELL  FROM T_Manage_Task WHERE (FID = " + ManFID + ") AND (F_ManageTaskKindIndex = " + Mankind + ")";
                        dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            if (dv[0]["FSTARTCELL"].ToString() != "-")
                            {
                                split = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                stackCoo[0] = Convert.ToInt32(split[0]);
                                stackCoo[1] = Convert.ToInt32(split[1]);
                                stackCoo[2] = Convert.ToInt32(split[2]);
                            }
                            if (dv[0]["FENDCELL"].ToString() != "-")
                            {
                                split = dv[0]["FENDCELL"].ToString().Split(cc);
                                stackCoo[3] = Convert.ToInt32(split[0]);
                                stackCoo[4] = Convert.ToInt32(split[1]);
                                stackCoo[5] = Convert.ToInt32(split[2]);
                            }
                        }
                        else
                        {
                            DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage时没能从调度任务获得堆垛机坐标！";
                            return null;
                        }
                        break;
                    default:
                        break;
                }
                return stackCoo;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromManage调度任务的坐标有误！"+ex.Message ;
                return null;
            }
            
            finally{
                stackCoo = null;
                sql = null;
                cc = null ;
                split=null ;
                dv=null ;

            }
        }
       /// <summary>
        /// 获得巷道的出入口处设备对应的堆垛机坐标取排-列-层（Z-X-Y）；送排-列-层（Z-X-Y）
       /// </summary>
       /// <param name="devIndex">设备索引</param>
       /// <param name="ifGet">是否取货</param>
       /// <returns></returns>
        static int[] GetStackCoordinateFromLaneGate(int stackIndex,int devIndex,bool ifGet)
        {
            char[] cc = new char[1] { '-' };//20100305
            string[] split;
            int[] rt = new int[6] { 0,0,0,0,0,0};
            DataView dv;
            int LaneWay = ccf.GetLaneWayFromLaneInfo(stackIndex);

            try
            {
                dv = dbo.ExceSQL("select * from T_Base_Lane_Gate where F_LaneGateDeviceIndex=" + devIndex + " and F_LaneIndex="+LaneWay+"").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (ifGet == true)//取坐标
                    {
                        //20100305
                        split = dv[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//送坐标
                    {
                        //20100305
                        split = dv[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
                    }

                }
                return rt;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetStackCoordinateFromLaneGate:" + ex.Message;
                return null;
            }
            finally
            {
                cc =null ;
                split=null ;
                rt =null ;
                dv=null ;
            }
        }
         /// <summary>
        /// 获得设备的入库口探物光电的设备索引值
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        /// 20101118
        static string GetBindingDeviceIndex(int devinx)
        {
            
            try
            {
               devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
               
               if (devinfo.BindingDevice == null) return "";
               return devinfo.BindingDevice;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetBindingDeviceIndex:" + ex.Message;
                return "";
            }
            finally
            {
                devinfo = null;
            }
            
        }
        /// <summary>
        /// 获得输送机设备的出库口探物光电的设备索引值
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        /// 20101118
        static string GetBindingDeviceIndexOut(int devinx)
        {
            
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
                if (devinfo.BindingDeviceOut == null)return  "";
                return devinfo.BindingDeviceOut;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetBindingDeviceIndexOut:" + ex.Message;
                return "";
            }
            finally
            {
                devinfo = null;
            }
            
        }
        /// <summary>
        ///被临近设备运行前检测的光电信号对应的设备索引组（故障，正转，反转，上升，下降等），
        /// 索引之间使用分号“;”隔开，索引前面加负号“-”表示需要检测值为“1”的信号
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        static string GetBeDetectedDevices(int devinx)
        {
            
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
                return devinfo.BeDetected;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetBeDetectedDevices:" + ex.Message;
                return null ;
            }
            finally
            {
                devinfo = null;
            }
            
        }
        /// <summary>
        /// 获取输送机执行送出命令时，需要提前检测的光电开关设备索引
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        /// 20101118
        static string  GetSendOutDetect(int devinx)
        {
            
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
                if (devinfo.SendOutDetect == null || devinfo.SendOutDetect =="0") return "";//20101018
                return devinfo.SendOutDetect;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetSendOutDetect:" + ex.Message;
                return "";
            }
            finally
            {
                devinfo = null;
            }
            
        }
        /// <summary>
        /// 双叉堆垛机在一个输送机取送盘时需要额外检测的探物开关（隔壁输送机是否有探物）
        /// </summary>
        /// <param name="devinx"></param>
        /// <returns></returns>
        static int GetDoubleForkDetect(int devinx)
        {
            
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(devinx);
                return Convert.ToInt32(devinfo.DoubleForkDetect);
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetSendOutDetect:" + ex.Message;
                return 0;
            }
            finally
            {
                devinfo = null;
            }

        }

        /// <summary>
        /// 获取设备是否逻辑有货
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        static string GetIfHaveGoods(int devinx)
        {
            string sql =string.Empty;
        
            DataView db;
            try
            {
                sql = "SELECT F_HaveGoods FROM T_Base_Device WHERE (F_DeviceIndex = " + devinx + ") and F_HaveGoods is not null";
               db = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (db.Count > 0)
                {
                    return db[0]["F_HaveGoods"].ToString();
                }
                else
                    return "";
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetIfHaveGoods:" + ex.Message;
                return "";
            }
                
            finally
            {
                db = null;
                sql = null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="devidx">RGV地址的设备索引号</param>
        /// <param name="IfGet">是否是接货</param>
        /// <returns></returns>
        static int GetRGVOrder(int devidx,bool IfGet)
        {//（2-左接货3-左送货）或者（4-右接货5-右送货）
            int order = 0;
            DataView dv;
            try
            {
                dv = dbo.ExceSQL("SELECT F_IFChannelLeft, F_RGVGateDeviceIndex" +
                " FROM T_Base_RGV_Gate WHERE (F_RGVGateDeviceIndex = " + devidx + ")").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["F_IFChannelLeft"].ToString() == "1")
                    {
                        if (IfGet == true)
                        {
                            order = 2;
                        }
                        else
                        {
                            order = 3;
                        }
                    }
                    else
                    {
                        if (IfGet == true)
                        {
                            order = 4;
                        }
                        else
                        {
                            order = 5;
                        }
                    }
                }
                return order;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetRGVOrder:" + ex.Message;
                return 0;
            }
            finally
            {
                dv = null;
            }
        }
        /// <summary>
        /// 获得AGV的前一个设备信息
        /// 20090625
        /// </summary>
        /// <param name="CurRouteIDSub">路径子编号</param>
        /// <param name="CurSerialNumber">AGV设备的路径序号</param>
        /// <returns></returns>
        static List<int> GetAGVPriorDevice(int CurRouteIDSub, int CurSerialNumber)
        {
             
            List<int> Device = new List<int>();
            try
            {
                string sql = "SELECT T_Base_Route_Device.F_DeviceIndex,F_DeviceOrder, T_Base_Route_Device.F_SerialNumber, " +
                        "T_Base_Device_Command.F_DeviceCommandIndex,T_Base_Device.F_DeviceKindIndex FROM T_Base_Device_Kind,T_Base_Device_Command " +
                        ",T_Base_Device,T_Base_Route_Device where T_Base_Device_Command.F_DeviceKindIndex = T_Base_Device.F_DeviceKindIndex" +
                        " and T_Base_Device_Kind.F_DeviceKindIndex = T_Base_Device_Command.F_DeviceKindIndex and T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and F_RouteIDSub=" +
                        CurRouteIDSub + " and F_SerialNumber < " + CurSerialNumber + " and F_GoodsMoveKindIndex=1 order by F_SerialNumber desc ";
                DataView dvRoute = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dvRoute.Count > 0)
                {
                    Device.Add(Convert.ToInt32(dvRoute[0]["F_DeviceIndex"]));
                    Device.Add(Convert.ToInt32(dvRoute[0]["F_DeviceKindIndex"]));
                    Device.Add(Convert.ToInt32(dvRoute[0]["F_SerialNumber"]));
                    Device.Add(Convert.ToInt32(dvRoute[0]["F_DeviceOrder"]));
                }
                return Device;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetAGVPriorDevice:" + ex.Message;
                return null;
            }
            finally
            {
                Device=null ;
            }
        
        }
        /// <summary>
        /// 判断调度表T_Monitor_Task是否存在调度任务的设备和命令
        /// </summary>
        /// <param name="Mankind">调度任务类型</param>
        /// <param name="ManFID">调度任务索引</param>
        /// <param name="DeviceIndex">设备所引</param>
        /// <param name="Order">设备命令</param>
        /// <returns></returns>
        static bool DeviceAndOrderExitInMonitor(int Mankind, int ManFID, int DeviceIndex,int Order,int ArrowAddress)
        {
            DataView dv;string sql=string.Empty ;
            try
            {
                if (Order == -1) return true;

                switch (ccf.GetDeviceKindIdx(DeviceIndex))
                {
                    case 1://堆垛机
                        sql = "SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + ManFID + ")" +
                        " AND (F_ManageTASKKINDINDEX = " + Mankind + ") AND (F_DeviceIndex = " + DeviceIndex + ")" +
                        " AND (F_DeviceCommandIndex = " + Order + ")";
                        break;
                    case 2://输送机
                        sql = "SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + ManFID + ")" +
                        " AND (F_ManageTASKKINDINDEX = " + Mankind + ") AND (F_DeviceIndex = " + DeviceIndex + ")" +
                        " AND (F_DeviceCommandIndex = " + Order + ")";
                        break;
                    case 4://RGV
                        sql = "SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + ManFID + ")" +
                        " AND (F_ManageTASKKINDINDEX = " + Mankind + ") AND (F_DeviceIndex = " + DeviceIndex + ")" +
                        " AND (F_DeviceCommandIndex = " + Order + ") and F_NumParam1=" + ArrowAddress + "";
                        break;
                    case 6://AGV
                        sql = "SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + ManFID + ")" +
                        " AND (F_ManageTASKKINDINDEX = " + Mankind + ") AND (F_DeviceIndex = " + DeviceIndex + ")" +
                        " AND (F_DeviceCommandIndex = " + Order + ")";
                        break;
                    default:
                        sql = "SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + ManFID + ")" +
                        " AND (F_ManageTASKKINDINDEX = " + Mankind + ") AND (F_DeviceIndex = " + DeviceIndex + ")" +
                        " AND (F_DeviceCommandIndex = " + Order + ")";
                        break;
                }
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.DeviceAndOrderExitInMonitor:" + ex.Message;
                return false;
            }
            finally
            {
                dv = null;
                sql = null;
            }
        }
        /// <summary>
        /// 找到不能移动托盘的关键设备的前一个设备：例如，条码扫描器前一个位置（运动反方向）的输送机 ( 条码扫描)
        /// </summary>
        /// <param name="prirorDevice">关键设备的前一个设备</param>
        /// <param name="prirorKeydevice">关键设备</param>
        /// <returns></returns>
        static List<int> NewCurDevice(List<int> prirorDevice, List<int> prirorKeydevice)
        {//0设备所引；1设备类型;2:路径序号；3：设备命令
            try
            {
                if ((prirorKeydevice.Count > 0) && (prirorDevice.Count > 0))
                {
                    DataView dv = dbo.ExceSQL("SELECT F_GoodsMoveKindIndex, F_DeviceKindIndex FROM T_Base_Device_Kind WHERE " +
                        "(F_DeviceKindIndex = " + prirorKeydevice[1] + ") and (F_GoodsMoveKindIndex=2)").Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        return prirorDevice;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.NewCurDevice:" + ex.Message;
                return null;
            }
            finally
            {
                prirorDevice=null;
                prirorKeydevice=null;
            }
        }
        /// <summary>
        /// 获取可用的目标位置：入库的巷道或者出库站台；同时修改调度任务为不可拆分状态
        /// </summary>
        /// <param name="dr">T_Manage_Task表的行记录</param>
        /// <returns></returns>
        public static void GetUsableDestination(DataRowView dr)
        {
            //只修申请改调度任务的路径，不修改调度自动任务路径
            if (dr["F_ManageTaskKindIndex"].ToString() != "1") return ;
            //20100108入库倒退指令不允许改道
            //if ((dr["FENDDEVICE"].ToString() == "1219") || (dr["FENDDEVICE"].ToString() == "1203")
            //    || (dr["FENDDEVICE"].ToString() == "1205") || (dr["FENDDEVICE"].ToString() == "2203")
            //    || (dr["FENDDEVICE"].ToString() == "2212")) return;

            string sql = string.Empty ;
            string adviceDev = string.Empty;
            //20100610查找一个路径可用，任务数最少的终点设备
            Dictionary<int, int> advDev = new Dictionary<int, int>();
            object ob;

            //20091107
            DataView dvIO = dboM.ExceSQL("select CONTROL_ID, CONTROL_STATUS from IO_Control where (CONTROL_ID = " + Convert.ToInt32(dr["FID"]) + ") AND ((CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEAPPLY + ") or (CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEREPLY + "))").Tables[0].DefaultView;
            if (dvIO.Count <= 0)
            {
                DataTable dtd = dbo.ExceSQL("SELECT F_TASKKIND, F_DESTINATION FROM T_Base_Destination WHERE (F_TASKKIND = " + dr["FCONTROLTASKTYPE"] + ") and (F_AbendStation=1) and (F_DESTINATION=" + dr["FENDDEVICE"] + ")").Tables[0];
                if (dtd.Rows.Count > 0)//原来终点是应急站台那么还分配这个站台，不需要改变
                {
                    adviceDev = dtd.Rows[0]["F_DESTINATION"].ToString();
                    //20091005
                    return;
                }
                else
                {
                    //查找可用目标位置
                    DataTable dt = dbo.ExceSQL("SELECT F_TASKKIND, F_DESTINATION FROM T_Base_Destination WHERE (F_TASKKIND = " + dr["FCONTROLTASKTYPE"] + ") and (F_DESTINATION <>" + dr["FENDDEVICE"] + ") and (F_AbendStation=0)").Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (CDisassembleTask.MinRouteID(Convert.ToInt32(dr["FSTARTDEVICE"]), Convert.ToInt32(dt.Rows[i]["F_DESTINATION"]), dr["FUseAwayFork"]) != -1)
                            {
                                //20100610统计到终点设备正在执行的任务数
                                ob = dbo.GetSingle("SELECT count(FENDDEVICE) as counts FROM T_Manage_Task where FENDDEVICE='" + dt.Rows[i]["F_DESTINATION"] + "' and fstatus>0");
                                advDev.Add(Convert.ToInt32(dt.Rows[i]["F_DESTINATION"]), Convert.ToInt32(ob));

                                //20100610  adviceDev = dt.Rows[i]["F_DESTINATION"].ToString();
                                //break;
                            }
                        }
                        if (advDev.Count == 0)//20100610
                        {

                            return;


                        }
                        else
                        {//20100610
                            int mincount = 9999;
                            foreach (int aaa in advDev.Keys)
                            {
                                if (advDev[aaa] < mincount)
                                {
                                    mincount = advDev[aaa];
                                    adviceDev = aaa.ToString();
                                }
                            }
                            if (adviceDev == "")
                            {

                                return;

                            }
                        }
                    }
                    else
                    {
                        return;
                    }
                }


                //DataView DV = dboM.ExceSQL("select IO_CONTROL_APPLY_SEQ.NEXTVAL FROM DUAL").Tables[0].DefaultView;
                //20101108int fid = dboM.GetManageTableIndex("IO_CONTROL_APPLY");
                string dtime = DateTime.Now.ToString("u");
                dtime = dtime.Substring(0, dtime.Length - 1);
                //20091128
                dboM.TransBegin();
                try
                {
                    dboM.ExceSQL(" update IO_CONTROL set CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEAPPLY + " where CONTROL_ID=" + dr["FID"] + "");
                    //向管理申请修改任务//20101108CONTROL_APPLY_ID," + fid + ",
                    sql = "INSERT INTO IO_CONTROL_APPLY ( CONTROL_ID,CONTROL_APPLY_TYPE,WAREHOUSE_CODE, STOCK_BARCODE, DEVICE_CODE, APPLY_TASK_STATUS, CREATE_TIME, " +
                            " CONTROL_APPLY_REMARK)" +
                    "VALUES (" + dr["FID"] + ",2,'" + dr["FSTARTWAREHOUSE"] + "','" + dr["FPALLETBARCODE"] + "','" + adviceDev + "',0,'" + dtime + "',null)";
                    dboM.ExceSQL(sql);
                    dboM.TransCommit();
                    //修改调度任务为不可拆分状态
                    dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dr["FID"]) + ") AND (F_ManageTASKKINDINDEX =1)");

                }
                catch (Exception ex)
                {
                    _DisassembleTaskError = "拆分任务，向管理申请改道时：" + ex.Message;
                    dboM.TransRollback();
                }
            }
            
        }

        public static void  CreateRelativeMonitor(int manKind, int FID)
        {
            int relativeFID = -1;
            DataView dv; DataView dvs;
            try
            {
                dv = dbo.ExceSQL("SELECT F_RELATIVECONTORLID FROM T_Manage_Task WHERE (FID = " + FID + ") AND (F_ManageTaskKindIndex = " + manKind + ") and (F_RELATIVECONTORLID<>-1)").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    relativeFID = Convert.ToInt32(dv[0]["F_RELATIVECONTORLID"]);
                }
                else
                {
                    dv = dbo.ExceSQL("SELECT FID FROM T_Manage_Task WHERE (F_RELATIVECONTORLID  = " + FID + ") AND (F_ManageTaskKindIndex = " + manKind + ") ").Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        relativeFID = Convert.ToInt32(dv[0]["FID"]);
                    }
                    else
                    {
                        return ;
                    }
                }
                //双叉关联调度任务在此拆分20100323
                //获取双叉关联任务的路径和任务信息，递归调用CreateMonitor
                
                if (relativeFID != -1)
                {
                    dvs = dbo.ExceSQL("SELECT T_Manage_Task.* FROM T_Manage_Task WHERE (FID = " + relativeFID + ") AND (F_ManageTaskKindIndex = " + manKind  + ") and (FIntoStepOK=0)").Tables[0].DefaultView;
                    if (dvs.Count > 0)
                    {
                        int minrid = MinRouteID(Convert.ToInt32(dvs[0]["FSTARTDEVICE"]), Convert.ToInt32(dvs[0]["FENDDEVICE"]), dvs[0]["FUseAwayFork"]);
                        if (minrid != -1)
                        {
                            if (CreateMonitor(manKind, relativeFID, minrid, dvs[0], 0) > 0)
                            {
                                //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                dbo.ExceSQL("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvs[0]["FID"]
                                + " and F_ManageTaskKindIndex=" + dvs[0]["F_ManageTaskKindIndex"]);
                               
                            }
                        }
                    }
                }
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }
        /// <summary>
        /// 找到一个双叉最合适货位，修改关联关系
        /// </summary>
        /// <param name="dr"></param>
        public static void GetOutDoubleForkTask(DataRowView dr)
        {//sqlser的 SUBSTRING(express1,1开始,2);C#的.Substring(0开始, 2)
            if (dr["F_RELATIVECONTORLID"].ToString() != "-1") return;
            int forwlimitX = 0, backlimitX = 0;
            DataView dv = dbo.ExceSQL("SELECT F_ForwardLimitX, F_BackLimitX FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = " + dr["FLANEWAY"] + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                forwlimitX=Convert.ToInt32(dv[0]["F_ForwardLimitX"]);
                backlimitX = Convert.ToInt32(dv[0]["F_BackLimitX"]);
            }
            else
                return;

            string sqladd = string.Empty ;
            if (forwlimitX.ToString() == dr["FStartCol"].ToString())
            {
                sqladd = " and FStartCol <>" + forwlimitX + " ";
            }
            else if (backlimitX.ToString() == dr["FStartCol"].ToString())
            {
                sqladd = " and FStartCol <>" + backlimitX + " ";
            }
            else
            {
                sqladd = " ";
            }
            //列的速度是层的速度的3倍，所以层的差值要乘以三（提升一层的时间相当于移动三列的时间）
            string sql = "SELECT TOP 1 F_ManageTaskKindIndex, FID, MIN(POWER(FStartCol  - " + dr["FStartCol"] + ", 2) + POWER((FStartLayer - " +
             dr["FStartLayer"] + ") * 3, 2)) AS Expr1 FROM T_Manage_Task WHERE (FIntoStepOK = '0') AND " +
             "(FSTATUS = 0) AND (FCONTROLTASKTYPE = " + dr["FCONTROLTASKTYPE"] + ") AND (FLOGIC_AREA = '" + dr["FLOGIC_AREA"] + 
             "') AND (FCONTORL_BATCH = '" + dr["FCONTORL_BATCH"] + "') AND (FLANEWAY = " + dr["FLANEWAY"] +
             ") AND (F_RELATIVECONTORLID = - 1) and F_ManageTaskKindIndex=" + dr["F_ManageTaskKindIndex"] + " and FID<>"+dr["fid"]+
             sqladd + "  GROUP BY F_ManageTaskKindIndex, FID order by Expr1 asc";
            dv=dbo.ExceSQL(sql).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID="+dv[0]["FID"]+" where FID="+dr["fid"]+" and F_ManageTaskKindIndex=" + dr["F_ManageTaskKindIndex"] );
                dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + dr["fid"] + " where FID=" + dv[0]["FID"] + " and F_ManageTaskKindIndex=" + dv[0]["F_ManageTaskKindIndex"]);
            }
            else
            {
                return;
            }

        }

        /// <summary>
        /// 根据条码类型指定拆盘指令类型
        /// </summary>
        /// <param name="ManFID"></param>
        /// <returns></returns>
        static int unpacktype(int ManFID )
        {
          DataView dv=  dbo.ExceSQL("select * from t_manage_task where fid =" + ManFID).Tables[0].DefaultView;
          if (dv.Count <= 0)
          {
              return -1;
          }
          else
          {
              string unpacknum = string.Empty;
              if (dv[0]["FPALLETBARCODE"] == DBNull.Value )
              {
                  return 7;
              }
              else
              {
                  unpacknum = dv[0]["FPALLETBARCODE"].ToString();
                  if (unpacknum == "-" || unpacknum ==string.Empty)
                  {
                      return 7;
                  }
                  if ((unpacknum.Substring(7, 2) == "03") )
                  {
                      return 8;
                  }
                  else
                  {
                      return 7;
                  }
              }
        
         
          }
        }

        static int GetManageHandIdx()
        {
            DataSet ds = dbo.ExceSQL("SELECT F_ManageTaskKindIndex, max(FID) as mFID FROM T_Manage_Task Where F_ManageTaskKindIndex=4 group by F_ManageTaskKindIndex");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                return (Convert.ToInt32(ds.Tables[0].DefaultView[0]["mFID"]) + 1);
            }
            else
            {
                DataSet dss = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Base_Manage_Task_Index_Hand_Task");
                if (dss.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1) >= 29998)
                    {
                        return 20001;
                    }
                    else
                    {
                        return (Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1);
                    }
                }
                else
                {
                    return 20001;
                }
            }
        }
    }

}
