using Microsoft.VisualBasic;
using RGD.DataService;
using RGD.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;

namespace RGD.WCS
{
    /// <summary>
    /// Creator:Richard.liu
    /// 任务拆分类
    /// 选取调度任务时以保障设备利用率最大化为原则：1、每个路径端头的入库站台要有一个任务；
    /// 2、每个堆垛机要有一个任务（以优先方式决定先执行哪种任务）；
    /// 3、组合优先方式时，在调度任务完成时调整已拆分任务优先级为最高级9，进行优先执行。
    ///
    /// 把调度任务分解成多个监控搬运任务
    /// 分解原则：把一个调度任务按照出入库路径的设备索引排出多个步骤的设备指令
    /// 20091107增加对五个调度策略SelectTask_ManPRI();SelectTask_OnlyIn();SelectTask_InSubjoinOut();
    /// SelectTask_OnlyOut();SelectTask_OutSubjoinIn();的优先级相同时根据下达时间的升序执行order by FTASKLEVEL desc,FBEGTIME asc
    /// </summary>

    public static class CDisassembleTask
    {
        private static string _DisassembleTaskError = "";

        public static string DisassembleTaskError
        {
            get { return _DisassembleTaskError; }
            set { _DisassembleTaskError = value; }
        }

        private static CCommonFunction ccf = new CCommonFunction();

        private static Model.MDevice devinfo;

        /// <summary>
        /// 拆分调度任务，不包括手工任务（直接生成存入调度T_Monitor_Task表）
        /// </summary>
        public static int MyTaskIntoSteps()
        {
            int nSubCount = 0;
            try
            {   //出库优先携带附带运行条件的入库任务
                nSubCount = SelectTask_OutSubjoinIn();
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.MyTaskIntoSteps时发生错误:" + ex.Message;
            }
            return nSubCount;
        }

        /// <summary>
        /// 出库优先附带符合运行条件的入库任务
        /// 具体实现：在收到出库任务的完成时，挑选一个可以执行的入库任务把优先级设成最高9
        /// </summary>
        private static int SelectTask_OutSubjoinIn()
        {
            int nSubCount = 0;
            try
            {
                #region 遍历堆垛机 根据堆垛机分解任务

                Model.MDevice deviceInfo;
                string sql = "SELECT F_StackIndex FROM T_Base_StackInfo";
                DataView dvStack = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                int routeid = -1;
                sql = "select * from t_warehouse";
                DataView task = DbHelperSQL.Query(sql).Tables[0].DefaultView;

                if (task[0]["F_TASK_TYPE"].ToString() != "Inventory")
                {
                    #region 若果是出库任务,一次性拆分,在发送任务处一次性发送所有AGV取货任务

                    DataView OutTask = DbHelperSQL.Query("select * from T_Manage_Task where FCONTROLTASKTYPE='2' and FIntoStepOK='0'").Tables[0].DefaultView;
                    for (int a = 0; a < OutTask.Count; a++)
                    {
                        routeid = MinRouteID(Convert.ToInt32(OutTask[0]["FSTARTDEVICE"]), Convert.ToInt32(OutTask[0]["FENDDEVICE"]), OutTask[0]["FUseAwayFork"]);
                        if (CreateMonitor(Convert.ToInt32(OutTask[a]["F_ManageTaskKindIndex"]), Convert.ToInt32(OutTask[a]["FID"]), routeid, OutTask[a], 0) > 0)
                        {
                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                            DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + OutTask[a]["FID"]
                            + " and F_ManageTaskKindIndex=" + OutTask[a]["F_ManageTaskKindIndex"]);
                            //若为需要回库的任务,IS_PICKUP为true,正常拆分后,根据调度任务索引FID查询命令为6的设备指令,并将6修改为9
                            if (OutTask[a]["IS_PICKUP"].ToString() == "True")
                            {
                                DbHelperSQL.ExecuteSql("update T_Monitor_task set F_DeviceCommandIndex='9' where F_ManageTaskIndex='" + OutTask[a]["FID"].ToString() + "' and F_DeviceCommandIndex='6'");
                            }
                        }
                    }

                    #endregion 若果是出库任务,一次性拆分,在发送任务处一次性发送所有AGV取货任务
                }
                else//盘库任务
                {
                    //发送至agv的盘库任务是一个完整的任务组,其调度任务构成为①出①入②出②入③出③入...,以此类推,
                    //但实际执行顺序为①取②取③取....①放①从输送线取②放②从输送线取③放③从输送线取.......①送②送③送...,然后执行下个循环

                    //1.优先拆分入库任务
                    //2.当有正在执行的调度任务时,不能拆分出库任务,或者已拆分的出库任务等于agv层数时,不能拆分
                    //3.拆分入库任务时,必须要射频的允许拆分标志
                    //4.盘库射频成功后,才写入允许拆分标志
                    //5.当agv上报流水线取货完成的时候,重置允许拆分标志
                    //6.拆分入库任务时,不得存在agv取货任务,防止一次性将入库任务拆分完
                    //7.拆分入库任务的时候,实际上任务已经被发送过了
                    DataView invSplitTask = DbHelperSQL.Query($"select * from T_Manage_Task where FCONTROLTASKTYPE='2' and FIntoStepOK='1' and FMANAGEID='{task[0]["F_TASK_NO"].ToString()}'").Tables[0].DefaultView;
                    //4为agv层数
                    if (invSplitTask.Count == 5)
                    {
                        return 0;
                    }

                    //查询是否有未拆分的盘库返库任务，若存在且允许拆分标志为1，且不存在agv取货任务,应优先拆分并分配任务组
                    DataView invInTask = DbHelperSQL.Query($"select top 1 * from T_Manage_Task where FCONTROLTASKTYPE='1' and FIntoStepOK='0' and FMANAGEID='{task[0]["F_TASK_NO"].ToString()}'").Tables[0].DefaultView;
                    Object splitFlag = DbHelperSQL.GetSingle("select split_flag from io_rfid");
                    if (invInTask.Count != 0 && Convert.ToInt32(splitFlag) == 1)
                    {

                        DataView MANAGE = DbHelperSQL.Query($"select * from T_Manage_Task where FID={Convert.ToInt32(invInTask[0]["FID"])-1}").Tables[0].DefaultView;
                        if (MANAGE.Count==0)
                        {
                            routeid = MinRouteID(Convert.ToInt32(invInTask[0]["FSTARTDEVICE"]), Convert.ToInt32(invInTask[0]["FENDDEVICE"]), invInTask[0]["FUseAwayFork"]);
                            if (CreateMonitor(Convert.ToInt32(invInTask[0]["F_ManageTaskKindIndex"]), Convert.ToInt32(invInTask[0]["FID"]), routeid, invInTask[0], 0) > 0)
                            {
                                //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + invInTask[0]["FID"]
                                + " and F_ManageTaskKindIndex=" + invInTask[0]["F_ManageTaskKindIndex"]);
                            }
                        }
                    }
                    //拆分出库任务时，不得存在正在执行中的任务
                    //注意：发送出库任务后，必须更新调度任务状态，否则影响后续拆分任务
                    DataView invRunOutTask = DbHelperSQL.Query("select * from T_Manage_Task where  FSTATUS='1'").Tables[0].DefaultView;
                    if (invRunOutTask.Count != 0)
                    {
                        return 0;
                    }
                    DataView invOutTask = DbHelperSQL.Query("select top 5 * from T_Manage_Task where FCONTROLTASKTYPE='2' and FIntoStepOK='0'").Tables[0].DefaultView;
                    for (int i = 0; i < invOutTask.Count; i++)
                    {
                        routeid = MinRouteID(Convert.ToInt32(invOutTask[0]["FSTARTDEVICE"]), Convert.ToInt32(invOutTask[0]["FENDDEVICE"]), invOutTask[0]["FUseAwayFork"]);
                        if (CreateMonitor(Convert.ToInt32(invOutTask[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(invOutTask[i]["FID"]), routeid, invOutTask[i], 0) > 0)
                        {
                            //分解完成，修改T_Manage_Task表FIntoStepOK=1 出库任务状态改为出库中
                            DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1',FStatus = '1' where FID=" + invOutTask[i]["FID"]
                            + " and F_ManageTaskKindIndex=" + invOutTask[i]["F_ManageTaskKindIndex"]);

                            DbHelperSQL.ExecuteSql("update t_monitor_task set F_Status=2 where F_DeviceCommandIndex=4 and F_ManageTaskIndex=" + invOutTask[i]["FID"]);
                        }
                    }
                    //当前盘库任务均执行完后删除任务信息
                    Object manageCount = DbHelperSQL.GetSingle($"select count(*) as count from T_Manage_Task where FMANAGEID='{task[0]["F_TASK_NO"].ToString()}'");
                    if (task[0]["F_TASK_STATUS"].ToString()== "STOPPING" && Convert.ToInt32(splitFlag) == 0)
                    {
                        DbHelperSQL.ExecuteSql("update T_Warehouse set F_TASK_NO='',f_TASK_TYPE='',f_task_status='FREE',F_IO_WH_SORT_CODE='',F_LASTBOX_REACH_FLAG=0");
                    }
                }
                for (int i = 0; i < dvStack.Count; i++)
                {
                    #region 首先选择此堆垛机所有入库任务，判断那个能执行

                    string sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTATUS = 0) AND (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                    DataView dvManage = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                    for (int j = 0; j < dvManage.Count; j++)//有这个堆垛机的入库任务等待拆分
                    {
                        //选择最短调度路径并且判断此路径上是否有设备发生故障
                        routeid = MinRouteID(Convert.ToInt32(dvManage[j]["FSTARTDEVICE"]), Convert.ToInt32(dvManage[j]["FENDDEVICE"]), dvManage[j]["FUseAwayFork"]);
                        if (routeid == -1 || task[0]["F_TASK_TYPE"].ToString() == "Inventory")
                        {
                            continue;
                        }
                        if (CreateMonitor(Convert.ToInt32(dvManage[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvManage[j]["FID"]), routeid, dvManage[j], 0) > 0)
                        {
                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                            DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvManage[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_Status = 1 OR T_Monitor_Task.F_Status = 2) AND F_DeviceCommandIndex=5 and " +
                        "(T_Monitor_Task.F_DeviceIndex = " + dvStack[i]["F_StackIndex"] + ") AND (T_Manage_Task.FCONTROLTASKTYPE = 1)";
                    DataView dvt = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                    if (dvt.Count > 0)
                    {
                        #region 有这个堆垛机的入库任务在执行

                        sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                        dvt = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;

                        if (dvt.Count <= 0)//没有此堆垛机的出库任务在排队或者执行 | 分解一个出库任务
                        {
                            #region 挑选此堆垛机的出库任务

                            sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                            dvManage = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                            if (dvManage.Count > 0)//挑选此堆垛机的出库任务
                            {
                                routeid = MinRouteID(Convert.ToInt32(dvManage[0]["FSTARTDEVICE"]), Convert.ToInt32(dvManage[0]["FENDDEVICE"]), dvManage[0]["FUseAwayFork"]);
                                if (routeid == -1)
                                {
                                    continue;
                                }
                                //20101028增加出库关联
                                deviceInfo = BaseDeviceService.GetDeviceInfo(Convert.ToInt32(dvManage[0]["FSTACK"]));
                                if (deviceInfo != null)
                                {
                                    if (deviceInfo.IfCorrelDoubleFork == "1")
                                    {
                                        GetOutDoubleForkTask(dvManage[0]);
                                    }
                                }
                                if (CreateMonitor(Convert.ToInt32(dvManage[0]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvManage[0]["FID"]), routeid, dvManage[0], 0) > 0)
                                {
                                    //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                    DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvManage[0]["FID"]
                                    + " and F_ManageTaskKindIndex=" + dvManage[0]["F_ManageTaskKindIndex"]);
                                    DbHelperSQL.ExecuteSql("update dbo.T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                        dvManage[0]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dvManage[0]["FID"] + "");
                                    nSubCount++;
                                }
                            }

                            #endregion 挑选此堆垛机的出库任务
                        }
                        else //解析 |
                        {
                            #region 如果有此堆垛机的出库任务在排队或者执行

                            sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTACK = " + dvStack[i]["F_StackIndex"] +
                                ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                            dvManage = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                            if (dvManage.Count > 0)//挑选此堆垛机的出库任务
                            {
                                for (int j = 0; j < dvManage.Count; j++)
                                {
                                    //判断将要被拆分的出库任务是否在已拆分的队列中有终点相同的出库任务，没有就找一个拆分
                                    sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dvManage[j]["FENDDEVICE"] + ") and (FSTACK = " +
                                        dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc,FBEGTIME asc";
                                    DataView dv12 = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                                    if (dv12.Count <= 0)
                                    {
                                        routeid = MinRouteID(Convert.ToInt32(dvManage[j]["FSTARTDEVICE"]), Convert.ToInt32(dvManage[j]["FENDDEVICE"]), dvManage[j]["FUseAwayFork"]);
                                        if (routeid == -1)
                                        {
                                            continue;
                                        }
                                        if (CreateMonitor(Convert.ToInt32(dvManage[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvManage[j]["FID"]), routeid, dvManage[j], 0) > 0)
                                        {
                                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                            int level = Convert.ToInt32(dvManage[j]["FTASKLEVEL"]) == 100 ? 100 : 9;

                                            DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1',FTASKLEVEL=" + level + " where  FID=" + dvManage[j]["FID"]
                                            + " and F_ManageTaskKindIndex=" + dvManage[j]["F_ManageTaskKindIndex"]);

                                            DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_MonitorTaskLevel=9 where F_MonitorTaskLevel<>100 and F_ManageTASKKINDINDEX=" +
                                                dvManage[j]["F_ManageTaskKindIndex"] + " and F_ManageTaskIndex=" + dvManage[j]["FID"] + "");

                                            nSubCount++;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                DataView dvv = DbHelperSQL.Query("select * from T_Manage_Task  WHERE (FSTACK = " +
                                    dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0)").Tables[0].DefaultView;
                                for (int aa = 0; aa < dvv.Count; aa++)
                                {
                                    DbHelperSQL.ExecuteSql("update T_Manage_Task set FTASKLEVEL=9 WHERE (FTASKLEVEL<>100) and  F_ManageTASKKINDINDEX=" +
                                                dvv[aa]["F_ManageTaskKindIndex"] + " and FID=" + dvv[aa]["FID"] + "");
                                    DbHelperSQL.ExecuteSql("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 有这个堆垛机的入库任务在执行
                    }
                    else
                    {
                        //此堆垛机没有正在入库的任务 | 分解出库任务

                        #region 选择此堆垛机一个出库任务

                        sqlstr = "SELECT * FROM T_Manage_Task WHERE (FSTATUS = 0) AND (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                        dvManage = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                        for (int j = 0; j < dvManage.Count; j++)
                        {
                            sqlstr = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FENDDEVICE=" + dvManage[j]["FENDDEVICE"] +
                                ") and (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 2) AND (FIntoStepOK = '1') AND (FStatus = 0) order by FTASKLEVEL desc";
                            dvt = DbHelperSQL.Query(sqlstr).Tables[0].DefaultView;
                            if (dvt.Count > 0)//有此堆垛机的出库任务而且终点相同在排队就不拆分了
                            {
                                continue;
                            }
                            //判断堆垛机是否有调度命令在执行或者被锁定
                            sql = "SELECT F_ManageTASKKINDINDEX, F_DeviceIndex, F_Status FROM T_Monitor_Task" +
                                " where F_DeviceIndex=" + dvStack[i]["F_StackIndex"] + " and F_Status>0 ";
                            dvt = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                            if (dvt.Count > 0)
                            {
                                continue;
                            }
                            //被锁定20091009
                            sql = "SELECT F_DeviceIndex, F_LockedState FROM T_Base_Device where F_DeviceIndex=" + dvStack[i]["F_StackIndex"] + " and (F_LockedState>0 or F_ManTaskReserve>0)";
                            DataView dv1 = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                            if (dv1.Count > 0)
                            {
                                continue;
                            }
                            //选择最短调度路径并且判断此路径上是否有设备发生故障
                            routeid = MinRouteID(Convert.ToInt32(dvManage[j]["FSTARTDEVICE"]), Convert.ToInt32(dvManage[j]["FENDDEVICE"]), dvManage[j]["FUseAwayFork"]);
                            if (routeid == -1)
                            {
                                continue;
                            }
                            if (CreateMonitor(Convert.ToInt32(dvManage[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvManage[j]["FID"]), routeid, dvManage[j], 0) > 0)
                            {
                                //分解完成，修改T_Manage_Task表FIntoStepOK=1
                                DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvManage[j]["FID"]
                                + " and F_ManageTaskKindIndex=" + dvManage[j]["F_ManageTaskKindIndex"]);

                                nSubCount++;
                            }
                        }

                        #endregion 选择此堆垛机一个出库任务
                    }

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

                    #region 有这个堆垛机的扫描任务等待拆分[盘库任务]

                    sql = "SELECT * FROM T_Manage_Task WHERE (FSTATUS = 0) AND (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 5) AND (FIntoStepOK = '0') order by FTASKLEVEL desc,FBEGTIME asc";
                    dvManage = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                    for (int j = 0; j < dvManage.Count; j++)//有这个堆垛机的扫描任务等待拆分
                    {
                        sql = "SELECT * FROM T_Manage_Task WHERE  (FSTACK = " + dvStack[i]["F_StackIndex"] + ") AND (FCONTROLTASKTYPE = 5) AND (FIntoStepOK = '1')";
                        dvt = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                        if (dvt.Count > 0)
                        {   //有执行中的扫描任务
                            break;
                        }
                        if (CreateStockTakeMonitor(Convert.ToInt32(dvManage[j]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvManage[j]["FID"]), dvManage[j], 0) > 0)
                        {
                            //分解完成，修改T_Manage_Task表FIntoStepOK=1
                            DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvManage[j]["FID"] + " and F_ManageTaskKindIndex=" + dvManage[j]["F_ManageTaskKindIndex"]);
                            nSubCount++;
                        }
                    }

                    #endregion 有这个堆垛机的扫描任务等待拆分[盘库任务]
                }

                #endregion 遍历堆垛机 根据堆垛机分解任务

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //获取任务FIntoStepOK[未处理的]FSTACK<=0 or FCONTROLTASKTYPE=3 FTASKLEVEL[优先级] FCONTROLTASKTYPE[类型] [时间]

                #region 其他任务 FCONTROLTASKTYPE=3[移库任务]

                sql = "SELECT * FROM T_Manage_Task WHERE ((FSTACK <= 0)or(FCONTROLTASKTYPE = 3)) AND (FIntoStepOK = '0')  order by FTASKLEVEL desc, FCONTROLTASKTYPE asc,FBEGTIME asc";
                dvStack = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                for (int i = 0; i < dvStack.Count; i++)//挑选没有堆垛机参与的任务
                {
                    //选择最短调度路径并且判断此路径上是否有设备发生故障
                    routeid = MinRouteID(Convert.ToInt32(dvStack[i]["FSTARTDEVICE"]), Convert.ToInt32(dvStack[i]["FENDDEVICE"]), dvStack[i]["FUseAwayFork"]);
                    if (routeid == -1)
                    {
                        continue;
                    }
                    if (CreateMonitor(Convert.ToInt32(dvStack[i]["F_ManageTaskKindIndex"]), Convert.ToInt32(dvStack[i]["FID"]), routeid, dvStack[i], 0) > 0)
                    {
                        //分解完成，修改T_Manage_Task表FIntoStepOK=1
                        DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='1' where FID=" + dvStack[i]["FID"] + " and F_ManageTaskKindIndex=" + dvStack[i]["F_ManageTaskKindIndex"]);
                        nSubCount++;
                    }
                }

                #endregion 其他任务 FCONTROLTASKTYPE=3[移库任务]
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.SelectTask_OutSubjoinIn时发生错误:" + ex.Message;
            }
            return nSubCount;
        }

        /// <summary>
        /// 根据调度任务的起点和终点设备索引查找路径最短的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 = DbHelperSQL.Query(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 = DbHelperSQL.Query("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 = DbHelperSQL.Query("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 = DbHelperSQL.Query(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 = DbHelperSQL.Query(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>
        ///
        /// </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 = DbHelperSQL.Query(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;
                                                }

                                                ////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();
                                                }

                                                #endregion 运行提前检测光电组
                                            }
                                            AheadTrigger = PriorDevice[0].ToString(); //+ "-" + (被触发的调度任务号);//此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #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,F_createtime)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + drv["FUseAwayFork"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                                DbHelperSQL.ExecuteSql(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 生成输送机命令

                                                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_createtime)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                                DbHelperSQL.ExecuteSql(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;
                                }
                                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)
                                    {
                                        if (cdi[1] != "") //高位 dzf
                                        {
                                            AheadDetect += ";D-" + cdi[1];//20101118
                                        }

                                        if (cdi[0] != "")//有货
                                        {
                                            AheadDetect += ";D-" + cdi[0];//20101118
                                        }
                                    }
                                    //20101011
                                    else
                                    {
                                        tw = GetBindingDeviceIndexOut(PriorDevice[0]);
                                        if (tw != "")
                                        {//20101118
                                            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[0] != "")//无货
                                        {
                                            AheadDetect += ";D" + cdi[0];//20101118
                                        }
                                        //if (cdi[5] != "")//DZF
                                        //{
                                        //    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检测被堆垛机送货的输送机空闲
                                    AheadDetect += ";" + "I" + NextDevice[0].ToString() + ";" + "N" + NextDevice[0].ToString();//dzf
                                }
                                //保证堆垛机取货时堆垛机无货 2011/11/16
                                tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                if (tw != "")
                                {
                                    AheadDetect += ";D" + tw.ToString();
                                }
                                AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);
                                //取货
                                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,F_CreateTime)" +
                                    "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"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(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 = "";
                                if (NextDevice[1] == 2 || NextDevice[1] == 9)
                                {//送货做提前检测+运行时锁定
                                    #region 运行时锁定设备组

                                    RunningLock = "";

                                    DataView dvlane = DbHelperSQL.Query("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 = "";
                                    //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[0] != "")
                                        {
                                            AheadDetect += ";D" + cdi[0];//20101118
                                        }
                                        //if (cdi[5] != "")//DZF
                                        //{
                                        //    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() + ";" + GetBeDetectedDevices(NextDevice[0]);//20101118
                                        }
                                        else
                                        {
                                            AheadDetect = null;
                                        }
                                    }
                                    //tw = GetBindingDeviceIndexOut(NextDevice[0]); //DZF
                                    //if (tw != "")
                                    //{
                                    //    AheadDetect = AheadDetect + ";D" + tw.ToString();//20101118
                                    //}
                                    ////20090803检测设备是否空闲idle
                                    AheadDetect += ";" + "I" + NextDevice[0].ToString();
                                    //20090918给堆垛机送货的输送机增加是否逻辑有物的判断
                                    AheadDetect += ";" + "N" + NextDevice[0].ToString(); //DZF 注释回来

                                    #endregion 运行提前检测光电组
                                }
                                AheadDetect += ";" + GetBeDetectedDevices(NextKeyDevice[0]);
                                // 堆垛机放货时保证有货
                                tw = GetBindingDeviceIndex(NextKeyDevice[0]);
                                if (tw != "")
                                {
                                    AheadDetect += ";D-" + tw.ToString();
                                }
                                //送货
                                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,F_createtime)" +
                                    "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"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(sql);
                                }

                                #endregion 送货

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

                                //修改T_Manage_Task的FLANEWAY，FSTACK
                                dvs = DbHelperSQL.Query("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
                                DbHelperSQL.ExecuteSql("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://输送机（关键点：例如十字路口（有前一个和后一个设备）或者路径终点（没有后一个设备））

                                #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 生成输送机命令

                                            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,F_createtime)" +
                                            "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',0,'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                            DbHelperSQL.ExecuteSql(sql);

                                            #endregion 生成输送机命令
                                        }
                                    }
                                }

                                #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 生成输送机命令

                                                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_createtime)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                                DbHelperSQL.ExecuteSql(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 获得RGV运行的接货位的设备索引

                                    #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,F_createtime)" +
                                        "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 + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                        DbHelperSQL.ExecuteSql(sql);
                                        //更新最后一个输送机运行时的RGV运行的提前触发
                                        //格式：运行的设备索引+被触发的调度任务号
                                        if (AheadTrigger != null)
                                        {
                                            AheadTrigger = PriorDevice[0] + "-" + mindex;
                                            //此设备的运行状态（货物当前位置=PriorDevice[0]）触发堆垛机的将取
                                            DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_AheadTrigger='" + AheadTrigger + "' where F_MonitorIndex=" + TriggerTaskNo);
                                        }
                                    }

                                    #endregion 生成RGV指令:7-运动（到目标设备索引）+（2-左接货3-左送货）或者（4-右接货5-右送货）

                                    #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,F_createtime)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + PriorDevice[0] + "," + 3 + "," + routeIDSub + "," + status + "," + PriorDevice[0] + ",0,"
                                            + "0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                        DbHelperSQL.ExecuteSql(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,F_createtime)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + NextKeyDevice[0] + "," + Rgvorder + "," + routeIDSub + "," + status + "," + PriorDevice[0] + ",0" +
                                            ",0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                        DbHelperSQL.ExecuteSql(sql);
                                        DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_Associate=" + mindex + " where F_MonitorIndex=" + mainTask);
                                    }

                                    #endregion RGV的接货（被关联的任务）
                                }

                                //获得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,f_createtime)" +
                                    "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 + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(sql);
                                }

                                #endregion 生成RGV指令:7-运动（到目标设备索引）+（2-左接货3-左送货）或者（4-右接货5-右送货）

                                #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,F_createtime)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + Rgvorder + "," + routeIDSub + "," + status + "," + NextDevice[0] + ",0" +
                                        ",0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(sql);
                                    mainTask = mindex;
                                }

                                #endregion RGV的送货

                                #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,F_createtime)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextDevice[0] + "," + 4 + "," + routeIDSub + "," + status + "," + NextDevice[0] + ",0,"
                                        + "0,0,0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(sql);
                                    DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_Associate=" + mindex + " where F_MonitorIndex=" + mainTask);
                                }

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

                                break;

                            #endregion RGV

                            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,F_createtime)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + NextKeyDevice[3] + "," + routeIDSub + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ")";
                                    DbHelperSQL.ExecuteSql(sql);
                                }

                                #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
                                                    }
                                                }
                                                //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
                                                    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 生成输送机命令

                                                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_createtime)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                                DbHelperSQL.ExecuteSql(sql);

                                                #endregion 生成输送机命令
                                            }
                                        }
                                    }

                                    #endregion 前一设备是输送机
                                }

                                #region 运行提前检测光电组

                                //20110318
                                tw = GetBindingDeviceIndexOut(PriorDevice[0]);
                                if (tw != "")
                                {
                                    AheadDetect = "D-" + tw.ToString();
                                }
                                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,F_createtime)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + NextKeyDevice[3] + "," + routeIDSub + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(sql);
                                }

                                #endregion 生成条码比对命令

                                #endregion 条码扫描仪（托盘条码比对1）

                                break;

                            case 12:

                                #region 虚拟关键设备（只作为路径分割点）

                                if (PriorDevice.Count > 0)
                                {
                                    if (CurDevice[1] == 34)
                                    {
                                        int arrowdev = PriorDevice[0];

                                        #region 运行提前检测光电组

                                        //CurDevice的F_SendOutDetect里存的光电开关的设备所引。CurDevice有探物
                                        tw = GetSendOutDetect(CurDevice[0]);
                                        if (tw != "")
                                        {//AGV无物
                                            AheadDetect = "D" + tw.ToString(); //20101118
                                        }
                                        else
                                        {
                                            AheadDetect = null;
                                        }
                                        AheadDetect += ";" + GetBeDetectedDevices(CurDevice[0]);//设备空闲

                                        #endregion 运行提前检测光电组

                                        if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                        {
                                            #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_createtime)" +
                                            "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',0,'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                            DbHelperSQL.ExecuteSql(sql);

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

                                    #region 前一设备是输送机

                                    else 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;

                                                #region 运行提前检测光电组

                                                //20101011
                                                //string[] cdi = ccf.GetCorrel_DeviceInfo(CurDevice[0], true);
                                                //if ((null!= cdi)&&(CurDevice[3] == 2))
                                                //{//20100406检测被堆垛机送货的顶升机构在顶升高位（-11211或者-11221），空闲
                                                //    AheadDetect += ";D-" + cdi[1] + ";" + GetBeDetectedDevices(CurDevice[0]);//20101118
                                                //}
                                                ////20101011
                                                //else
                                                //{
                                                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
                                                //}
                                                //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];
                                                if (arrowdev == CConfig.Device_DStacker)
                                                {
                                                    //箱子类型
                                                    int type = new ManageTaskService().GetTypeIndex(ManFID);
                                                    if (type == 1)
                                                    {
                                                        CurDevice[3] = 7;
                                                    }
                                                    else if (type == 2)
                                                    {
                                                        CurDevice[3] = 8;
                                                    }
                                                }
                                                //else if (arrowdev == 12020)
                                                //{
                                                //    CurDevice[3] = 7;
                                                //}
                                                else
                                                {
                                                    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]); ;
                                                //20101220

                                                List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                                tw = GetBindingDeviceIndex(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }
                                                //20110318
                                                tw = GetBeDetectedDevices(nextConveyor[0]);
                                                if (tw != "")
                                                {//20101118
                                                    AheadDetect += ";" + tw.ToString();
                                                }
                                                tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                                if (tw != "")
                                                {
                                                    AheadDetect += ";D" + tw.ToString();//20101118
                                                }

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

                                            if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                            {
                                                #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_createtime)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',0,'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                                DbHelperSQL.ExecuteSql(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 生成输送机命令

                                                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_createtime)" +
                                                "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                    + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                    + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                                DbHelperSQL.ExecuteSql(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,F_createtime)" +
                                    "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                        + "," + NextKeyDevice[0] + "," + NextKeyDevice[3] + "," + routeIDSub + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.Query(sql);
                                }

                                #endregion 生成和管理交互虚拟设备的【出库确认】命令

                                #endregion 20100617和管理交互虚拟设备，1：出库托盘确认

                                break;

                            case 32:

                                #region 拣选模组

                                //如果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;

                                            #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]); ;
                                            //20101220

                                            //List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                            //tw = GetBindingDeviceIndex(nextConveyor[0]);
                                            //if (tw != "")
                                            //{
                                            //    AheadDetect += ";D" + tw.ToString();//20101118
                                            //}
                                            ////20110318
                                            //tw = GetBeDetectedDevices(nextConveyor[0]);
                                            //if (tw != "")
                                            //{//20101118
                                            //    AheadDetect += ";" + tw.ToString();
                                            //}
                                            //tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                            //if (tw != "")
                                            //{
                                            //    AheadDetect += ";D" + tw.ToString();//20101118
                                            //}

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

                                        if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                        {
                                            #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_createtime)" +
                                            "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',0,'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                            DbHelperSQL.ExecuteSql(sql);

                                            #endregion 生成输送机命令
                                        }
                                    }
                                }

                                #endregion 前一设备是输送机

                                #region 运行提前检测光电组

                                //20110318
                                tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                if (tw != "")
                                {//输送线有物
                                    AheadDetect = "D-" + tw.ToString();
                                }
                                else
                                {
                                    AheadDetect = null;
                                }
                                AheadDetect += ";I" + CurDevice[0] + ";I" + NextKeyDevice[0];

                                #endregion 运行提前检测光电组

                                #region 生成条码比对命令

                                //20110318
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], NextKeyDevice[3], 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);
                                    string Sql = "insert into T_Monitor_Task" +
                                        "(F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex,F_MonitorTaskLevel," +
                                            "F_DeviceIndex,F_DeviceCommandIndex,F_Status,F_NumParam1,F_NumParam4,F_AheadDetect,F_TxtParam,F_PickUpLocation,f_createtime) " +
                                            "values(" + routeIDSub + "," + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"] + ","
                                            + NextKeyDevice[0] + "," + drv["PICKUP_TYPE"] + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "'," + drv["PICKUP_LOCATION"] + ",'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(Sql);
                                }

                                #endregion 生成条码比对命令

                                #endregion 拣选模组

                                break;

                            case 33:

                                #region 贴标机

                                #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;

                                            #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]); ;
                                            //20101220

                                            //List<int> nextConveyor = GetCurConveyorNextDevice(routeIDSub, CurDevice[2]);
                                            //tw = GetBindingDeviceIndex(nextConveyor[0]);
                                            //if (tw != "")
                                            //{
                                            //    AheadDetect += ";D" + tw.ToString();//20101118
                                            //}
                                            ////20110318
                                            //tw = GetBeDetectedDevices(nextConveyor[0]);
                                            //if (tw != "")
                                            //{//20101118
                                            //    AheadDetect += ";" + tw.ToString();
                                            //}
                                            //tw = GetBindingDeviceIndexOut(nextConveyor[0]);
                                            //if (tw != "")
                                            //{
                                            //    AheadDetect += ";D" + tw.ToString();//20101118
                                            //}

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

                                        if (DeviceAndOrderExitInMonitor(Mankind, ManFID, CurDevice[0], CurDevice[3], 0) == false)
                                        {
                                            #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_createtime)" +
                                            "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                                + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                                + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',0,'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                            DbHelperSQL.ExecuteSql(sql);

                                            #endregion 生成输送机命令
                                        }
                                    }
                                }

                                #endregion 前一设备是输送机

                                #region 运行提前检测光电组

                                //20110318
                                tw = GetBindingDeviceIndexOut(CurDevice[0]);
                                if (tw != "")
                                {//输送线有物
                                    AheadDetect = "D-" + tw.ToString();
                                }
                                else
                                {
                                    AheadDetect = null;
                                }
                                AheadDetect += ";I" + CurDevice[0] + ";I" + NextKeyDevice[0];

                                #endregion 运行提前检测光电组

                                #region 生成条码比对命令

                                //20110318
                                if (DeviceAndOrderExitInMonitor(Mankind, ManFID, NextKeyDevice[0], NextKeyDevice[3], 0) == false)
                                {
                                    int mindex = ccf.GetMonitorIndex(ManFID, Mankind);

                                    string Sql = "insert into T_Monitor_Task" +
                                        "(F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex,F_MonitorTaskLevel," +
                                            "F_DeviceIndex,F_DeviceCommandIndex,F_Status,F_NumParam1,F_NumParam4,F_AheadDetect,F_TxtParam,F_PickUpLocation,f_createtime) " +
                                            "values(" + routeIDSub + "," + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"] + ","
                                            + NextKeyDevice[0] + "," + drv["PICKUP_TYPE"] + "," + status + ",0,0,'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "'," + drv["PICKUP_LOCATION"] + ",'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                    DbHelperSQL.ExecuteSql(Sql);
                                }

                                #endregion 生成条码比对命令

                                #endregion 贴标机

                                break;

                            case 34://AGV

                                #region AGV

                                {
                                    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
                                            }
                                        }

                                        #endregion 运行提前检测光电组
                                    }
                                    else
                                    {
                                        arrowdev = NextKeyDevice[0];
                                        //if (arrowdev == 12020 && CurDevice[0] != 12011 && CurDevice[0] != 12027)
                                        //{
                                        //    CurDevice[3] = 7;   //送到异常口的发7
                                        //}
                                        //else
                                        {
                                            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 生成输送机命令

                                        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,F_createtime)" +
                                        "VALUES (" + ManFID + "," + Mankind + "," + mindex + "," + drv["FTASKLEVEL"]
                                            + "," + CurDevice[0] + "," + CurDevice[3] + "," + routeIDSub + "," + status + "," + CurDevice[0] + "," + arrowdev
                                            + ",'" + AheadDetect + "','" + drv["FPALLETBARCODE"] + "',0,'" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                                        DbHelperSQL.ExecuteSql(sql);

                                        #endregion 生成输送机命令
                                    }
                                }

                                #endregion AGV

                                break;

                            default:
                                break;
                        }
                    }
                    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;
            }
        }

        //------------------------------------------------------------------------------------------------------------------------

        private static int GetRouteIDsub(int device)
        {
            DataView dv = DbHelperSQL.Query("SELECT F_RouteIDSub, F_DeviceIndex, F_RouteID FROM T_Base_Route_Device where F_DeviceIndex=" + device + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_RouteIDSub"]);
            }
            else
            {
                return -1;
            }
        }

        /// <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 CreateStockTakeMonitor(int Mankind, int ManFID, DataRowView drv, int status)
        {
            try
            {
                //dbo.TransBegin();
                int routeIDsub = GetRouteIDsub(Convert.ToInt32(drv["fstack"].ToString()));

                char[] cc = new char[1] { '-' };
                string[] sp = drv["FSTARTCELL"].ToString().Split(cc);
                int z = Convert.ToInt32(sp[0]);
                int x = Convert.ToInt32(sp[1]);
                int y = Convert.ToInt32(sp[2]);

                string useawayfork = "-";
                useawayfork = "0";
                int hidx = Convert.ToInt32(drv["FID"].ToString());
                int hmindx = ccf.GetMonitorIndex(hidx, 4);
                string Sql = "insert into T_Monitor_Task(F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex," +
                        "F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_UseAwayFork,F_createtime) " +
                        "values(" + routeIDsub + "," + hidx + "," + Mankind + "," + hmindx + "," + Convert.ToInt32(drv["fstack"].ToString())
                        + ",2," + z + "," + x + "," + y + ",0,0,0,'" + useawayfork + "','" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "')";
                int s = DbHelperSQL.ExecuteSql(Sql);
                //dbo.TransCommit();
                return 1;
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                DisassembleTaskError = "ControlSystem.CDisassembleTask.CreateMonitor时发生错误:" + ex.Message;
                return 0;
            }
        }

        /// <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 = DbHelperSQL.Query(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>
        private 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 = DbHelperSQL.Query(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>
        private static List<int> GetNextKeyDevice(int CurRouteIDSub, int CurSerialNumber)
        {
            List<int> keyDevice = new List<int>(); DataView dvRoute; DataView dv; string sql;
            try
            {
                //首先判断本设备是否为关键设备
                dv = DbHelperSQL.Query("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 = DbHelperSQL.Query(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 = DbHelperSQL.Query(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>
        ///  获得堆垛机坐标取排-列-层（Z-X-Y）；送排-列-层（Z-X-Y）
        /// </summary>
        /// <param name="Mankind">调度任务类型</param>
        /// <param name="ManFID">调度任务索引</param>
        /// <param name="IOType">搬运任务类型：1，入库（送坐标）；2：出库（取坐标）；3：移库（取和送坐标）</param>
        /// <returns></returns>
        private 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 = DbHelperSQL.Query(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 = DbHelperSQL.Query(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 = DbHelperSQL.Query(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>
        private 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 = new CommonService().GetLaneWay(stackIndex);
            try
            {
                dv = DbHelperSQL.Query("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
        private static string GetBindingDeviceIndex(int devinx)
        {
            try
            {
                devinfo = BaseDeviceService.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
        private static string GetBindingDeviceIndexOut(int devinx)
        {
            try
            {
                devinfo = BaseDeviceService.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>
        private static string GetBeDetectedDevices(int devinx)
        {
            try
            {
                devinfo = BaseDeviceService.GetDeviceInfo(devinx);
                return devinfo.BeDetected;
            }
            catch (Exception ex)
            {
                DisassembleTaskError = "ControlSystem.CDisassembleTask.GetBeDetectedDevices:" + ex.Message;
                return "";
            }
            finally
            {
                devinfo = null;
            }
        }

        /// <summary>
        /// 获取输送机执行送出命令时，需要提前检测的光电开关设备索引
        /// </summary>
        /// <param name="devinx">设备索引</param>
        /// <returns></returns>
        /// 20101118
        private static string GetSendOutDetect(int devinx)
        {
            try
            {
                devinfo = BaseDeviceService.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="devidx">RGV地址的设备索引号</param>
        /// <param name="IfGet">是否是接货</param>
        /// <returns></returns>
        private static int GetRGVOrder(int devidx, bool IfGet)
        {//（2-左接货3-左送货）或者（4-右接货5-右送货）
            int order = 0;
            DataView dv;
            try
            {
                dv = DbHelperSQL.Query("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>
        /// 判断调度表T_Monitor_Task是否存在调度任务的设备和命令
        /// </summary>
        /// <param name="Mankind">调度任务类型</param>
        /// <param name="ManFID">调度任务索引</param>
        /// <param name="DeviceIndex">设备所引</param>
        /// <param name="Order">设备命令</param>
        /// <returns></returns>
        private 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 (BaseDeviceService.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 = DbHelperSQL.Query(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>
        private static List<int> NewCurDevice(List<int> prirorDevice, List<int> prirorKeydevice)
        {//0设备所引；1设备类型;2:路径序号；3：设备命令
            try
            {
                if ((prirorKeydevice.Count > 0) && (prirorDevice.Count > 0))
                {
                    DataView dv = DbHelperSQL.Query("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"></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 = DbHelperSQL.Query("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 = DbHelperSQL.Query(sql).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                DbHelperSQL.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + dv[0]["FID"] + " where FID=" + dr["fid"] + " and F_ManageTaskKindIndex=" + dr["F_ManageTaskKindIndex"]);
                DbHelperSQL.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + dr["fid"] + " where FID=" + dv[0]["FID"] + " and F_ManageTaskKindIndex=" + dv[0]["F_ManageTaskKindIndex"]);
            }
            else
            {
                return;
            }
        }
    }
}