using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Resources;
using CommonLib;
using DBFactory;
using ICommLayer;
using CommLayerFactory;
using System.Globalization;
using System.Net;
namespace WcfControlMonitorLib
{
    /// <summary>
    /// Creator:Richard.liu
    /// 获得设备状态类
    /// 
    /// 需要做的工作:
    /// 1.下位机给上位机发送设备(任务)状态信息(正在执行状态或者报警的设备所处调度路径的F_SerialNumber》=当前值)
    /// 2.(单独处理)下位机给上位机发送条码信息(托盘条码,烟箱一号工程码)
    /// 3.(单独处理)下位机给上位机发送现场控制触摸屏申请信号:1-重发当前设备指令
    ///     2-申请修改当前设备所执行任务的目标位置
    /// 4.跟踪货物运行到的位置(多个调度任务在执行同一个调度任务,取有探物的为当前位置)
    ///     并且判断是否存在提前触发任务
    /// 5.获取调度任务的优先策略判断:最短路径优先,
    /// 入库优先携带出库,出库优先携带入库等
    /// 6.任务号传递到当前设备时,把本路径的前一设备的运行锁解除,
    ///     同时把当前设备加运行锁
    /// 7.(根据故障点单独处理)调度路径是否可用的分析以及给管理进行反馈
    /// 8.(单独处理)创建自动调度任务
    /// 9.动画显示设备状态
    /// </summary>
    public class CGetState
    {
        public static event CDataSourceChangeEventHandler DataChange;
        public static void OnDataChange(object sender, CDataChangeEventArgs e)
        {
            if (DataChange != null)
            {
                DataChange(sender, e);
            }
        }
        public static event RefreshMonitorEventHandler RefreshMonitor;
        public static void OnRefreshMonitor(RefreshMonitorEventArgs e)
        {
            if (RefreshMonitor != null)
            {
                RefreshMonitor(e);
            }
        }
        char[] dd = new char[1] { '.' };//20101124
        //string[] DS;//20101124
        StringBuilder sql = new StringBuilder();
        Model.MError errs;
        Model.MDevice devinfo;
        ISendDeviceOrder sdo;
        StringBuilder[] wv = { new StringBuilder("2") };
        StringBuilder[] witemnames = { new StringBuilder("") };
        IGetDeviceState gds;
        CCommonFunction ccf = new CCommonFunction();
        DBOperator dbo = CStaticClass.dbo;
        DBOperator dboM =CStaticClass.dboM;
        //20100108
        CControl ccl = new CControl();
        string _CGetStateError = "";//监控调度类错误说明
        public string CGetStateError
        {
            get { return _CGetStateError; }
            set { _CGetStateError = value;
            RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", _CGetStateError);
            OnRefreshMonitor(rmea);
            }
        }
        public int[] _States;
        int _fid;
        int _mti;
        //int _relativeFID;
        //int _iotype=0;
        //int _endnode=0;
        /// <summary>
        /// 获得所有正在执行设备的状态
        /// </summary>
        public CGetState()
        {
            dbo.Open();
            if (dboM.Open() == false)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", "连接管理数据库失败!!!");
                OnRefreshMonitor(rmea);
            }
            
        }
        
        /// <summary>
        /// 获得反馈信息
        ///电器反馈该设备的"完成"时 删除设备指令 , 解除设备表占用状态F_LockedState=0;
        ///路径明细表F_LockedDeviceIndex里的所有对应设备索引解锁;
        /// 
        ///判断是最后一个设备指令吗? 是,回写调度任务IO_Control的FSTATUS=2即"搬运完成";
        /// T_Manage_Task的正在执行状态FSTATUS=2 ;
        /// </summary>
        /// <returns></returns>
        public void  GetDeviceState()
        {
            DataView dv=new DataView();
                
            DataView dvm = new DataView();
                
            DataView dvmo = new DataView();
                
            DataView dd = new DataView();
            try
            {

                int devKind;

                int DeviceIdx;
                int TaskIdx = 0;

                //20100617增加和管理交互虚拟设备,类型30
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_DeviceIndex,F_DeviceKindIndex,F_MaxSendCount,F_SendInterval FROM T_Base_Device WHERE (F_DeviceKindIndex = 1) OR (F_DeviceKindIndex = 2) OR (F_DeviceKindIndex = 4) OR (F_DeviceKindIndex = 7) OR (F_DeviceKindIndex = 6) OR (F_DeviceKindIndex = 30)");
                dd = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                for (int j = 0; j < dd.Count; j++)
                {

                    DeviceIdx = Convert.ToInt32(dd[j]["F_DeviceIndex"]);
                    devKind = Convert.ToInt32(dd[j]["F_DeviceKindIndex"]);
                    //20100609
                    devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);

                    //20091107
                    #region 发送后规定时间内没报开始或者读取数据成功需要进行超时重发,重发超限时报错
                    if (devKind == 6) //延吉烟厂只有AGV需要重新发送
                    {
                        sql.Remove(0, sql.Length);
                        sql.Append("select F_MonitorIndex,F_DeviceIndex,F_SendCount,F_StartTime,F_Status,F_AgvNo from T_Monitor_Task where F_DeviceIndex=").Append(DeviceIdx).Append(" and f_status=1 and F_SendFlag='1'");
                        dvmo = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;//20100905只重发主任务
                        if (dvmo.Count > 0)
                        {//20110510
                            TaskIdx = Convert.ToInt32(dvmo[0]["F_MonitorIndex"]);
                            int scount = Convert.ToInt32(dvmo[0]["F_SendCount"]);
                            scount++;
                            if (scount > Convert.ToInt32(dd[j]["F_MaxSendCount"]))
                            {
                                //发送次数超限报警
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Monitor_Task set F_Status=999 where F_Status<>999 and F_MonitorIndex=").Append(TaskIdx);//20110505
                                dbo.ExceSQL(sql.ToString());

                            }
                            else
                            {
                                //DateTime.Now.AddMilliseconds
                                if (dvmo[0]["F_StartTime"].ToString() != "-")
                                {
                                    if (Convert.ToDateTime(dvmo[0]["F_StartTime"].ToString().Substring(0, 19), CultureInfo.CurrentCulture).AddMilliseconds(Convert.ToDouble(dd[j]["F_SendInterval"])) <= DateTime.Now)
                                    {
                                        if (devKind == 2)
                                        {
                                            //20110510输送机零
                                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                                            sdo.SendDeviceOrder(0, 0, 0, DeviceIdx, 0);

                                        }
                                        if (dvmo[0]["F_AgvNo"] == DBNull.Value)
                                        {
                                            sql.Remove(0, sql.Length);
                                            sql.Append("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=").Append(DeviceIdx);
                                            dbo.ExceSQL(sql.ToString());
                                            sql.Remove(0, sql.Length);
                                            sql.Append("update T_Monitor_Task set F_SendCount=").Append(scount).Append(",F_Status=0 where F_MonitorIndex=").Append(TaskIdx);
                                            dbo.ExceSQL(sql.ToString());
                                        }
                                        CommonClassLib.CCarryConvert.WriteDarkCasket("GetDeviceState", "超时重发", DeviceIdx.ToString(), "设备指令索引:" + TaskIdx.ToString() + "发送后,一直没有报告执行或者完成,重新发送命令!");
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region 优化调度
                    //if (devinfo.NeedOptimize.ToString() == "1" )
                    //{//此设备需要优化调度,直接到表:T_Monitor_Task_Child查找设备状态
                    //    sqlNO = "SELECT F_MonitorIndex, F_DeviceIndex, F_Status FROM T_Monitor_Task_Child WHERE (F_Status = 1) AND (F_MonitorIndex = " + TaskIdx + ")";
                    //    dvNO = dbo.ExceSQL(sqlNO).Tables[0].DefaultView ;
                    //    if (dvNO.Count > 0)
                    //    {
                    //        DeviceIdx = Convert.ToInt32(dvNO[0]["F_DeviceIndex"]);
                    //        GetKindDeviceState(TaskIdx, DeviceIdx,Convert.ToInt32( dv[i]["F_RouteID"]));
                    //        continue;
                    //    }
                    //    else
                    //    {
                    //        continue;
                    //    }

                    //}
                    #endregion
                    //AGV //20100609
                    if ((dd[j]["F_DeviceKindIndex"].ToString() == "6") || (devinfo.SerialPort > 0)) continue;
                    //条码扫描仪比对条码值;
                    if (dd[j]["F_DeviceKindIndex"].ToString() == "7")
                    {

                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        sql.Remove(0, sql.Length);
                        sql.Append("select * from T_Monitor_Task where (F_DeviceIndex=").Append(DeviceIdx).Append(") and F_Status>=1");

                        dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            TaskIdx = Convert.ToInt32(dv[0]["F_MonitorIndex"]);
                            int FID = Convert.ToInt32(dv[0]["F_ManageTaskIndex"]);
                            int Taskind = Convert.ToInt32(dv[0]["F_ManageTASKKINDINDEX"]);
                            //string oldDevice = "1201";
                            //string oldCell = "-";
                            //int cno = 0;
                            //string cCell = "-";

                            #region 条码比对处理
                            //    //gds = CommModeCreate.CreateGetDeviceState(DeviceIdx);
                            //    sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            //    witemnames[0] = "DB2,byte" + Convert.ToString((devinfo.Dbw2Address + 0));
                            //    string gdata = CStaticClass.GetStringData(DeviceIdx);
                            //    if (dv[0]["F_DeviceCommandIndex"].ToString() == "1")//条码比对;
                            //    {
                            //        #region 条码比对

                            //        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", DeviceIdx.ToString(), gdata);
                            //        wv[0] = "2";
                            //        sdo.WriteDBData(witemnames, wv);
                            //        //管理建议如果gdata=="0000000000"放行到机台,真正错码的送到原货位
                            //        if ((gdata == dv[0]["F_TxtParam"].ToString().ToUpper()) || (gdata == "\0\0\0\0\0\0\0\0\0\0"))
                            //        {
                            //            ActionComplete(DeviceIdx, TaskIdx,1);
                            //            //刷新监控中心显示
                            //        }
                            //        else
                            //        {
                            //            if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("设备索引:" + DeviceIdx + ",条码比对错误;故障发生时间:" + DateTime.Now.ToString("u")) < 0)
                            //            {
                            //                FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "设备索引:" + DeviceIdx + ",条码比对错误;故障发生时间:" + DateTime.Now.ToString("u"), true);

                            //            }
                            //            ActionError(DeviceIdx, TaskIdx, 30);
                            //            dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_LockedState=" + TaskIdx);
                            //            //改到人工处理处(辅料1201):记住调度任务索引FID生成当前位置到1201,同时上报管理系统错误码,异常完成:本地管理表FERRORCODE=990
                            //            
                            //            if (DeviceIdx == 1603)//残盘回库
                            //            {
                            //                //残盘扫描直接回库
                            //                ActionComplete(DeviceIdx, TaskIdx, 1);
                            //                continue;
                            //            }
                            //            else if (DeviceIdx == 1604)//机台呼叫出库
                            //            {
                            //                cno = 1222;
                            //                dvm = dbo.ExceSQL("SELECT FSTARTDEVICE, FSTARTCELL FROM T_Manage_Task WHERE (FID = " + FID + ") AND (F_ManageTaskKindIndex = " + Taskind + ")").Tables[0].DefaultView;
                            //                if (dvm.Count > 0)
                            //                {
                            //                    oldCell = dvm[0]["FSTARTCELL"].ToString();
                            //                    oldDevice = dvm[0]["FSTARTDEVICE"].ToString();
                            //                }
                            //                else
                            //                {
                            //                    oldDevice = "1201";
                            //                    oldCell = "-";
                            //                }
                            //            }
                            //            else if  (DeviceIdx == 3604) 
                            //            {
                            //                oldDevice = "3229";
                            //                oldCell = "-";
                            //                cno = 3272;
                            //            }
                            //            else if  (DeviceIdx == 4601) 
                            //            {
                            //                oldDevice = "3229";
                            //                oldCell = "-";
                            //                cno = 4218;
                            //            }

                            //            else
                            //            {//不需要改路径的直接报告异常完成
                            //                dbo.ExceSQL("update T_Manage_Task set FExceptionNO=" + Model.CGeneralFunction.TASKABEND + " where (F_ManageTaskKindIndex = " + Taskind + ") AND (FID = " + FID + ")");
                            //                ActionComplete(DeviceIdx, TaskIdx, 1);
                            //                continue;

                            //            }



                            //            dbo.ExceSQL("DELETE FROM T_Manage_Task WHERE (F_ManageTaskKindIndex = "+Taskind+") AND (FID = "+FID+")");
                            //            dbo.ExceSQL("DELETE FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + FID + ") AND (F_ManageTASKKINDINDEX = " + Taskind + ")");
                            //            //20090902修改库房索引ccf.GetWarehouseIndex()
                            //            sql = "INSERT INTO T_Manage_Task" +
                            //            "(FID, F_ManageTaskKindIndex,FPALLETBARCODE,FMANAGETASKTYPE,FCONTROLTASKTYPE, FTASKLEVEL, FISRETURN," +
                            //            "FSTARTWAREHOUSE,FENDWAREHOUSE, FSTARTCELL, FSTARTDEVICE, FENDDEVICE, FENDCELL, " +
                            //            "FSTATUS, FBEGTIME, FIntoStepOK,FExceptionNO)" +
                            //            "VALUES (" + FID + "," + Taskind + ",'0000000000','1','1','1','1','" + ccf.GetWarehouseIndex() + "','" + ccf.GetWarehouseIndex() + "','-'," + cno + ",'" + oldDevice + "','" + oldCell + "','0','" + DateTime.Now.ToString("u") + "','0'," + Model.CGeneralFunction.TASKABEND + ")";
                            //            dbo.ExceSQL(sql);   

                            //            continue;
                            //        }
                            //        #endregion
                            //    }
                            //    else if (dv[0]["F_DeviceCommandIndex"].ToString() == "2")//叠盘后条码扫描申请任务;
                            //    {
                            //        #region 叠盘后条码扫描申请任务

                            //        if ((gdata == "\0\0\0\0\0\0\0\0\0\0") || (gdata == null))
                            //        { 
                            //            gdata = "0000000000";

                            //        }
                            //        int dcode=0;
                            //        if (DeviceIdx == 1603)
                            //        {
                            //            dcode = 1220;
                            //        }
                            //        else
                            //        {
                            //            continue;
                            //        }
                            //        DataView dvbc = dboM.ExceSQL("SELECT DEVICE_CODE,STOCK_BARCODE FROM IO_CONTROL_APPLY WHERE APPLY_TASK_STATUS=0 and DEVICE_CODE=" + dcode + " and (STOCK_BARCODE = '" + gdata + "')").Tables[0].DefaultView;
                            //        if (dvbc.Count > 0)
                            //        {
                            //            continue;
                            //        }
                            //        //20090915
                            //        string Sql = "SELECT STOCK_BARCODE from IO_CONTROL where STOCK_BARCODE='" + gdata + "' and CONTROL_STATUS<100";
                            //        DataView dvs = dboM.ExceSQL(Sql).Tables[0].DefaultView;
                            //        if (dvs.Count > 0)
                            //        {

                            //            continue;
                            //        }

                            //        //向管理申请入库任务
                            //        int fid = dboM.GetManageTableIndex("IO_CONTROL_APPLY");
                            //        string dtime = DateTime.Now.ToString("u");
                            //        dtime = dtime.Substring(0, dtime.Length - 1);
                            //        sql = "INSERT INTO IO_CONTROL_APPLY(CONTROL_APPLY_ID,CONTROL_APPLY_TYPE, DEVICE_CODE, STOCK_BARCODE, APPLY_TASK_STATUS, CREATE_TIME,CONTROL_APPLY_REMARK)VALUES " +
                            //            "(" + fid + ",1," + dcode + ",'" + gdata + "',0,'" + dtime + "',2)";
                            //        dboM.ExceSQL(sql);
                            //        //20090918
                            //        ActionComplete(DeviceIdx, TaskIdx, 1);
                            //        wv[0] = "2";
                            //        sdo.WriteDBData(witemnames, wv);
                            //        #endregion
                            //    }
                            #endregion


                        }




                    }
                    else if (dd[j]["F_DeviceKindIndex"].ToString() == "30")
                    {//20100617增加和管理交互虚拟设备,类型30
                        sql.Remove(0, sql.Length);
                        sql.Append("select * from T_Monitor_Task where (F_DeviceIndex=").Append(DeviceIdx).Append(") and F_Status>=1");

                        dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            TaskIdx = Convert.ToInt32(dv[0]["F_MonitorIndex"]);
                            gds = CommModeCreate.CreateGetDeviceState(DeviceIdx);
                            int[] states = gds.GetDeviceState(DeviceIdx, TaskIdx);
                            if (states != null)
                            {
                                if (states[1] == Model.CGeneralFunction.TASKOUTCONFIRM)
                                {
                                    ActionComplete(DeviceIdx, TaskIdx, 0);
                                }
                            }
                        }
                    }
                    else//其它类型设备
                    {

                        GetKindDeviceState(TaskIdx, DeviceIdx, 0);

                    }


                }



                //20090920
                #region 处理死锁问题
                ActionDeadLock();
                #endregion
                
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", "获取设备状态时:" +ex.StackTrace+ ex.Message);
                OnRefreshMonitor(rmea);

            }
            finally
            {//20091107
                dv.Dispose();
                dvm.Dispose();
                dvmo.Dispose();
                dd.Dispose();

            }

        }
        /// <summary>
        /// 设备报告空闲
        /// </summary>
        /// <param name="DeviceIdx"></param>
        public void ActionIdle(int DeviceIdx)
        {

        }
        ///
        public string ChangetostringTwo(int single)
        {
            if (single < 10)
                return "0"+Convert.ToString(single);
            else
                return Convert.ToString(single); 
        }
        /// <summary>
        /// 报告完成
        ///电器反馈该设备的"完成"时 删除设备指令 , 解除设备表占用状态F_LockedState=0;
        ///路径明细表F_LockedDeviceIndex里的所有对应设备索
        ///引解锁
        /// 修改或解除调度逻辑预约锁;
        ///判断是否为调度任务的最后一个设备指令?是,回写调度任务IO_Control的Control_STATUS=999即"搬运完成";
        ///删除T_Manage_Task的正在执行状态FSTATUS=2的任务,修改ST_CELL表的货位状态 ;
        /// </summary>
        /// <param name="DeviceIdx">设备索引</param>
        /// <param name="TaskIdx">设备指令索引</param>
        ///<param name="ClearZero">是否向设备发送清零命令:1清零;900撤销整个调度任务;999手工报告调度任务完成</param>
        public void ActionComplete(int DeviceIdx,int TaskIdx,int ClearZero)
        {
	        if (TaskIdx == 0) return;
            string dtime = string.Empty;
            devinfo =Model.CGetInfo.GetDeviceInfo(DeviceIdx);
            int devKind = ccf.GetDeviceKindIdx(DeviceIdx);
            //20100305
            int[] zxy = ccf.GetCoordinatesFromMonitorTask(TaskIdx);
            StringBuilder  zxystr = new StringBuilder();
            if (zxy != null)
            {
                zxystr .Append( (zxy[3].ToString().Length ==1 ? "0" + zxy[3].ToString() : zxy[3].ToString()) ).Append( "-" ).Append(
                    ((zxy[4].ToString().Length == 1) ? ("0" + zxy[4].ToString()) : (zxy[4].ToString())) ).Append( "-" ).Append(
                    ((zxy[5].ToString().Length == 1) ? ("0" + zxy[5].ToString()) : (zxy[5].ToString())));
            }
            int order = ccf.GetDeviceOrderFromMonitor(TaskIdx);

            #region 扬州晶澳双叉堆垛机取货报完成时判断是否可以关联任务

            //DataView dvInOther = new DataView(); DataView dvOutOther = new DataView(); DataView dvOut = new DataView();
            //bool relation_flag = Model.CGeneralFunction.GetIfDoubleForkTask(TaskIdx, DeviceIdx);
            //if ((relation_flag == false) && (order == 4) && (devinfo.IfCorrelDoubleFork == "1"))//任务无关联且取货完成且双叉设备
            //{
            //    int temp_mti = ccf.GetManageTaskKindIndexFromMonitor(TaskIdx);
            //    string useawayfork = Model.CGeneralFunction.GetUseAwayFork(TaskIdx);//待配对任务需要的货叉不能是该货叉
            //    bool isDoubleForkTask = Model.CGeneralFunction.GetIfDoubleForkTask(TaskIdx, DeviceIdx);
            //    int ComFid = ccf.GetManageTaskIndexfromMonitor(TaskIdx);
            //   // int ControlType = ccf.GetFCONTROLTASKTYPEFromManageTask(temp_mti, ManagetTaskID);
            //    int sendz = zxy[0];
            //    int sendx = zxy[1];
            //    int sendy = zxy[2];
            //    string sendcell = string.Format("{0:D2}-{1:D2}-{2:D2}", zxy[0], zxy[1], zxy[2]);//要查找到该取货位置
            //    int getgate = ccf.GetLaneGateDeviceIndexFromLaneGate(sendcell);//取货位置的设备编号

            //    if ((isDoubleForkTask == false) && (getgate == 12002) || (getgate == 12004))//扬州晶澳暂时只有无关联的双提升机入库时才判断置关联其余全部单任务执行
            //    {
            //        sql.Remove(0, sql.Length);
            //        if (getgate == 12002)
            //        {
            //            sql.Append("select *  from  T_Monitor_Task  where  F_DeviceIndex = 15011 and  F_NumParam1 = 1 and  F_NumParam2 = 1 and F_NumParam3 = 1 and  F_Status < 2 order  by F_SplitTime");//and F_Status > 0
            //            dvInOther = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;//查询12004
            //            if (dvInOther.Count > 0)
            //            {
            //                sql.Remove(0, sql.Length);
            //                sql.Append("select *  from  T_Manage_Task  where  FID = ").Append(Convert.ToInt32(dvInOther[0]["F_ManageTaskIndex"]));//and F_Status > 0
            //                dvOut = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;//查找到12004对应管理任务查看是否已关联
            //                if (dvOut.Count > 0)
            //                {
            //                    if (Convert.ToInt32(dvOut[0]["F_RELATIVECONTORLID"]) == -1)
            //                    {
            //                        string otherfork = useawayfork == "1" ? "2" : "1";
            //                        sql.Remove(0, sql.Length);
            //                        sql.Append("update T_Manage_Task set F_RELATIVECONTORLID=").Append(ComFid).Append(" where  FID= ").Append(ComFid).Append("or FID= ").Append(Convert.ToInt32(dvOut[0]["FID"]));
            //                        dbo.ExecuteSql(sql.ToString());

            //                        sql.Remove(0, sql.Length);
            //                        sql.Append("update T_Manage_Task set FUseAwayFork=").Append(otherfork).Append(" where  FID= ").Append(Convert.ToInt32(dvOut[0]["FID"]));
            //                        dbo.ExecuteSql(sql.ToString());

            //                        sql.Remove(0, sql.Length);
            //                        sql.Append("UPDATE T_Monitor_Task SET F_UseAwayFork = '").Append(otherfork).Append("' WHERE (F_ManageTaskIndex = ")
            //                            .Append(Convert.ToInt32(dvOut[0]["FID"])).Append(")");// AND (F_ManageTASKKINDINDEX = ")
            //                        dbo.ExecuteSql(sql.ToString());

            //                        object[] ob = new object[3] { 15011, otherfork, Convert.ToInt32(dvOut[0]["FID"]) };
            //                        if (Convert.ToInt32(otherfork) == 1)
            //                        {
            //                            dbo.ExceSQL(string.Format("UPDATE T_Monitor_Task SET F_AheadDetect = REPLACE(F_AheadDetect, '{0}.1', '{0}.0')  WHERE F_DeviceIndex={0} and (F_ManageTaskIndex ={2}) ", ob));
            //                        }
            //                        else
            //                        {
            //                            dbo.ExceSQL(string.Format("UPDATE T_Monitor_Task SET F_AheadDetect = REPLACE(F_AheadDetect, '{0}.0', '{0}.1')  WHERE F_DeviceIndex={0} and (F_ManageTaskIndex ={2}) ", ob));
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //        else
            //        {
            //            sql.Append("select *  from  T_Monitor_Task  where  F_DeviceIndex = 15001 and  F_NumParam1 = 1 and  F_NumParam2 = 2 and F_NumParam3 = 1 and  F_Status < 2 order  by F_SplitTime");//and F_Status > 0
            //            dvInOther = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
            //            if (dvInOther.Count > 0)
            //            {
            //                sql.Remove(0, sql.Length);
            //                sql.Append("select *  from  T_Manage_Task  where  FID = ").Append(Convert.ToInt32(dvInOther[0]["F_ManageTaskIndex"]));//and F_Status > 0
            //                dvOut = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
            //                if (dvOut.Count > 0)
            //                {
            //                    if (Convert.ToInt32(dvOut[0]["F_RELATIVECONTORLID"]) == -1)
            //                    {
            //                        string otherfork = useawayfork == "1" ? "2" : "1";

            //                        sql.Remove(0, sql.Length);
            //                        sql.Append("update T_Manage_Task set F_RELATIVECONTORLID=").Append(ComFid).Append(" where  FID= ").Append(ComFid).Append("or FID= ").Append(Convert.ToInt32(dvOut[0]["FID"]));
            //                        dbo.ExecuteSql(sql.ToString());

            //                        sql.Remove(0, sql.Length);
            //                        sql.Append("update T_Manage_Task set FUseAwayFork=").Append(otherfork).Append(" where  FID= ").Append(Convert.ToInt32(dvOut[0]["FID"]));
            //                        dbo.ExecuteSql(sql.ToString());

            //                        sql.Remove(0, sql.Length);
            //                        sql.Append("UPDATE T_Monitor_Task SET F_UseAwayFork = '").Append(otherfork).Append("' WHERE (F_ManageTaskIndex = ")
            //                            .Append(Convert.ToInt32(dvOut[0]["F_ManageTaskIndex"])).Append(")");// AND (F_ManageTASKKINDINDEX = ")
            //                        dbo.ExecuteSql(sql.ToString());

            //                        object[] ob = new object[3] { 15011, otherfork, Convert.ToInt32(dvOut[0]["FID"]) };
            //                        if (Convert.ToInt32(otherfork) == 1)
            //                        {
            //                            dbo.ExceSQL(string.Format("UPDATE T_Monitor_Task SET F_AheadDetect = REPLACE(F_AheadDetect, '{0}.1', '{0}.0')  WHERE F_DeviceIndex={0} and (F_ManageTaskIndex ={2}) ", ob));
            //                        }
            //                        else
            //                        {
            //                            dbo.ExceSQL(string.Format("UPDATE T_Monitor_Task SET F_AheadDetect = REPLACE(F_AheadDetect, '{0}.0', '{0}.1')  WHERE F_DeviceIndex={0} and (F_ManageTaskIndex ={2}) ", ob));
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            #endregion




            #region 双伸堆垛机连续出库并且多个任务需要倒库时  将移库和对应远货位绑定 当移库完成时提高对应出库任务优先级//add by gaojianan 2020 3 25
            if ((devKind == 1) && (order == 5))
            {

                int freach = 0; DataView dvFr = new DataView();
                dvFr = dbo.ExceSQL(string.Format("SELECT F_ForkAmount,F_Reach from T_Base_StackInfo where F_StackIndex = '{0}'", DeviceIdx)).Tables[0].DefaultView;
                if (dvFr.Count > 0)
                {
                    freach = Convert.ToInt32(dvFr[0]["F_Reach"]);
                }
                if (freach == 2)
                {
                    DataView dvc = new DataView();
                    string sqlstr1 = string.Format("SELECT T_Monitor_Task.F_NumParam1 as F_Z,T_Monitor_Task.F_NumParam2 as F_X, T_Monitor_Task.F_NumParam3 as F_Y , T_Manage_Task.FCONTROLTASKTYPE as MControlType  FROM  T_Monitor_Task full join T_Manage_Task on (T_Monitor_Task.F_ManageTaskIndex = T_Manage_Task.FID)  WHERE  (T_Monitor_Task.F_DeviceCommandIndex =5)  and (T_Monitor_Task.F_DeviceIndex = {0}  and  T_Monitor_Task.F_MonitorIndex = {1}  and  T_Manage_Task.FCONTROLTASKTYPE = 3)", DeviceIdx, TaskIdx);//,T_Manage_Task.FID as MFid 
                    dvc = dbo.ExceSQL(sqlstr1).Tables[0].DefaultView;

                    for (int i = 0; i < dvc.Count; i++)
                    {
                        int tempF = Convert.ToInt32(dvc[i]["F_Z"]);
                        if ((Convert.ToInt32(dvc[i]["MControlType"]) == 3) && ((tempF == 2) || (tempF == 3) || (tempF == 6) || (tempF == 9) || (tempF == 12) || (tempF == 13) || (tempF == 16) || (tempF == 17)))
                        {
                            int tempZ = 0;
                            string strtempz = string.Empty; string strtempx = string.Empty; string strtempy = string.Empty;

                            if ((tempF == 2) || (tempF == 6) || (tempF == 12) || (tempF == 16))//2 12 16
                            {
                                tempZ = Convert.ToInt32(dvc[i]["F_Z"]) - 1;
                            }
                            if ((tempF == 3) || (tempF == 9) || (tempF == 13) || (tempF == 17))
                            {
                                tempZ = Convert.ToInt32(dvc[i]["F_Z"]) + 1;
                            }
                            strtempz = ChangetostringTwo(tempZ);
                            strtempx = ChangetostringTwo(Convert.ToInt32(dvc[i]["F_X"]));
                            strtempy = ChangetostringTwo(Convert.ToInt32(dvc[i]["F_Y"]));

                            DataView dvc2 = new DataView();
                            string sqlstr2 = string.Format("SELECT   FID,FIntoStepOK  FROM  T_Manage_Task  WHERE  FCONTROLTASKTYPE =2  and FSTARTCELL = '{0}'", strtempz + "-" + strtempx + "-" + strtempy);
                            dvc2 = dbo.ExceSQL(sqlstr2).Tables[0].DefaultView;

                            int changeL = 10;
                            if (dvc2.Count > 0)
                            {
                                string sqlstr3 = string.Format("update T_Manage_Task set FTASKLEVEL = FTASKLEVEL + {0}  where FID = {1} ", changeL, dvc2[0]["FID"]);
                                dbo.ExceSQL(sqlstr3);

                                if (Convert.ToInt32(dvc2[0]["FIntoStepOK"]) == 1)
                                {
                                    string sqlstr4 = string.Format("update T_Monitor_Task  set F_MonitorTaskLevel = F_MonitorTaskLevel + {0} where F_ManageTaskIndex = {1} ", changeL, dvc2[0]["FID"]);
                                    dbo.ExceSQL(sqlstr4);
                                }
                            }
                        }
                    }
                }

            }
            #endregion


            if (order == -1)
            {
               // CGetStateError =DeviceIdx+"上报的任务号:"+TaskIdx+ "在调度系统已经没有记录!";
                return;
            }
            if (GetManage_Kind(TaskIdx) == false) return;
            int errrcode= ccf.GetExceptionNOFromManageTask(_fid,_mti );
            //攀枝花当升将当前任务存储到对应称重位置
            if (DeviceIdx == 12056 || DeviceIdx == 12059)
            {
                dbo.ExecuteSql(string.Format("UPDATE T_Base_PLC_Ask  SET F_TaskIndex = {0} WHERE (F_BindingDevice  = {1}) ", _fid, DeviceIdx));
            }
            //int ControlType = ccf.GetFCONTROLTASKTYPEFromManageTask(_mti, _fid);
            //string useawayfork = Model.CGeneralFunction.GetUseAwayFork(TaskIdx);
            string barcode = ccf.GetBarCodeFromMonitor(TaskIdx);
            //int enddevice = ccf.GetEndDeviceFromManage(_mti, _fid);
            int nexttaskindex = ccf.GetNextMonitorTaskIndex(TaskIdx);
            //string controlbatch = ccf.GetControlBatchFromManageTask(_mti, _fid);
            //20100710
            int AgvNextDeviceKind = 0;
            if ((devKind == 6)&&(order==2))
            {
                AgvNextDeviceKind = ccf.GetDeviceKindIdx(zxy[4]);
            }
            #region 20160501管理任务数量增加1,堆垛机送货,RGV送货
            int mantaskCount = 0; string errText = string.Empty;
            if ((devKind == 1) || (devKind == 4))
            {

                if (_mti!=4)//不统计手工任务和避让任务
                {
                    if ((devKind == 1 && order == 5) || (devKind == 4 && order == 3))
                    {
                        mantaskCount = 1;
                    }
                    //堆垛机和RGV的运行时间统计
                    CStaticClass.UpdateDeviceOEE(DeviceIdx, DateTime.Now.Date, mantaskCount, 0, 0,
                        ccf.GetMobileRunTimeSpan(TaskIdx), 0, 0, 'O', 0, out errText);
                }
            }

            #endregion
            #region 20160501统计上次报警
            Model.MError errs = Model.CGetInfo.GetErrorInfo(Convert.ToInt32(devKind.ToString() + ClearZero.ToString()));
            if (errs != null)
            {
                dtime = DateTime.Now.ToString("u");
                dtime = dtime.Substring(0, dtime.Length - 1);
                sql.Remove(0, sql.Length);
                //sql.Append("UPDATE T_Base_Device_Error_Log SET F_FixDateTime ='").Append(dtime).Append("'  Where F_FixDateTime is null  and F_DeviceIndex=")
                sql.Append("UPDATE T_Base_Device_Error_Log SET F_FixDateTime ='").Append(dtime).Append("',F_End_DateTime='").Append(dtime).Append("'  Where F_FixDateTime is null  and F_DeviceIndex=")
                .Append(DeviceIdx).Append(" and F_ManageTaskNo=").Append(Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIdx));
                dbo.ExceSQL(sql.ToString());
                if (errs.IfAlarm == '1')
                {//20160501
                    CStaticClass.UpdateDeviceOEE(DeviceIdx, DateTime.Now.Date, 0, 0, 0, 0
                    , 0, ccf.GetAlarmTimeSpan(DeviceIdx), errs.ErrorKind, 0, out errText);//统计上次报警
                    dbo.ExecuteSql(string.Format("update T_Base_Device set F_AlarmStartTime='-' where F_DeviceIndex ={0}", DeviceIdx));
                }
                else
                {
                    CStaticClass.UpdateDeviceOEE(DeviceIdx, DateTime.Now.Date, 0, 0, 0, 0
                    , ccf.GetErrorTimeSpan(DeviceIdx), 0, errs.ErrorKind, 0, out errText);//统计上次故障
                    dbo.ExecuteSql(string.Format("update T_Base_Device set F_ErrorStartTime='-' where F_DeviceIndex ={0}", DeviceIdx));
                }
            }
            #endregion
            #region 判断输送机误报完成信号
            
            if (devKind == 2)
            {//20120409判断输送机误报完成信号

                sql.Clear();
                sql.Append("SELECT T_Base_Device.F_DeviceIndex from T_Base_Device,T_Monitor_Task where T_Base_Device.F_DeviceIndex=T_Monitor_Task.F_DeviceIndex and F_DeviceKindIndex=2 AND F_MonitorIndex = ").Append(TaskIdx);
                object obd=dbo.GetSingle(sql.ToString());
                if (obd == null)
                {//不是输送机任务
                    return;
                }
                else
                {
                    if (Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(obd)).S7Connection != devinfo.S7Connection)
                    {//不是同层输送机任务
                        return;
                    }
                }
                
            }

            #endregion

            //20100108
            DataView dvman = new DataView();
            DataView dv = new DataView();
            DataView dvlane = new DataView();
            DataView dvr = new DataView();
            //string dtime=string.Empty ;
            //20121303增加RGV送货完成时的临近取货F_NearGetDevice优先级提高,先执行
            #region RGV送货完成时的临近取货站台的取货任务优先执行
            if ((devKind == 4)&&(order==3))
            {
                int SendDev = zxy[0];
                object obrgv = dbo.GetSingle(string.Format("SELECT F_NearGetDevice FROM T_Base_RGV_Gate WHERE (F_RGVGateDeviceIndex = {0}) AND (F_NearGetDevice > 0)",SendDev));
                if (obrgv != null)
                {//判断DeviceIdx在站台obrgv的取货任务是否是队列中第一个任务且等待执行
                    dv = dbo.ExceSQL(string.Format("SELECT F_ManageTASKKINDINDEX, F_ManageTaskIndex, F_MonitorIndex FROM T_Monitor_Task WHERE (F_DeviceIndex = {0}) AND (F_NumParam1 = {1}) and F_DeviceCommandIndex=2 and  F_Status=0 and  F_MonitorTaskLevel<>10", DeviceIdx, Convert.ToInt32(obrgv))).Tables[0].DefaultView;
                    for (int i = 0; i < dv.Count;i++ )
                    {
                        dvr = dbo.ExceSQL(string.Format("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE F_ManageTASKKINDINDEX={0} and F_ManageTaskIndex={1} order by F_MonitorIndex asc", Convert.ToInt32(dv[i]["F_ManageTASKKINDINDEX"]), Convert.ToInt32(dv[i]["F_ManageTASKINDEX"]))).Tables[0].DefaultView;
                        if (dvr.Count > 0)
                        {
                            if (dvr[0]["F_MonitorIndex"].ToString() == dv[i]["F_MonitorIndex"].ToString())
                            {
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Monitor_Task set F_MonitorTaskLevel=10 where F_ManageTASKKINDINDEX=").Append(Convert.ToInt32(dv[i]["F_ManageTASKKINDINDEX"])).Append(" and F_ManageTaskIndex=").Append(Convert.ToInt32(dv[i]["F_ManageTASKINDEX"])).Append(" and F_DeviceIndex=").Append(DeviceIdx) ;
                                dbo.ExceSQL(sql.ToString());
                                
                                break;
                            }
                        }
                    }
                }



            }
            #endregion

            #region 出库优先携带入库优先策略的处理或者入库优先携带出库优先策略的处理(入出库交替)
            int Pri = ccf.SelectTaskPriPrecept();
            //20091016
            if (((Pri == 21) || (Pri == 12)) && (devKind == 1) && (ccf.GetFCONTROLTASKTYPEFromManageTask(_mti, _fid) == 2))//堆垛机出库优先并且携带入库任务
            {
                sql.Remove(0, sql.Length);
                sql.Append("select * from T_Manage_Task where FTASKLEVEL=10 and FSTACK = " ).Append( DeviceIdx ).Append( " AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '1') ");
                
                //20100108
                dvman=dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView ;
                if (dvman.Count <= 0)
                {//20130122首先看是否有同侧同巷道的入库堆垛机等待任务
                    if (GetNearDeviceInputTask(DeviceIdx, zxystr.ToString()) == false)
                    {
                        //没有了,随便找个入库任务吧
                        sql.Remove(0, sql.Length);
                        sql.Append("SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FSTACK = ").Append(DeviceIdx).Append(") AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '1') order by FTASKLEVEL desc, F_ManageTaskKindIndex desc,FID asc");

                        dvman = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        for (int ii = 0; ii < dvman.Count; ii++)
                        {
                            sql.Remove(0, sql.Length);
                            sql.Append("select * from T_Monitor_Task where F_ManageTASKKINDINDEX=" + dvman[ii]["F_ManageTASKKINDINDEX"] + " and F_ManageTaskIndex=" + dvman[ii]["FID"] + " order by F_MonitorIndex asc");

                            //20100108
                            dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            if (dv.Count > 0)
                            {
                                int stackkind = ccf.GetDeviceKindIdx(Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                                if (stackkind == 1)
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update T_Monitor_Task set F_MonitorTaskLevel=10 where  F_MonitorTaskLevel<10  and F_ManageTASKKINDINDEX=").Append(dvman[ii]["F_ManageTASKKINDINDEX"]).Append(" and F_ManageTaskIndex=").Append(dvman[ii]["FID"]);
                                    dbo.ExceSQL(sql.ToString());
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update T_Manage_Task set FTASKLEVEL=10 where FTASKLEVEL<10  and  F_ManageTASKKINDINDEX=").Append(dvman[ii]["F_ManageTASKKINDINDEX"]).Append(" and FID=").Append(dvman[ii]["FID"]);
                                    dbo.ExceSQL(sql.ToString());

                                    break;
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            //dbo.TransBegin();
            try
            {
                #region 给正在执行单叉取货指令的堆垛机,配上双叉
                //if (_mti!=4&&devKind == 1   && devinfo.IfCorrelDoubleFork == "1"&& order==4&& devinfo.VirtualStack!= DeviceIdx)//非手工任务,取货指令完成时,不能是虚拟堆垛机
                //{
                //    //if ((errrcode ==-1) &&(ClearZero != Model.CGeneralFunction.TASKDELETE))//异常任务 不去关联别的任务,不能是删除任务的操作
                //        if  (ClearZero != Model.CGeneralFunction.TASKDELETE)//异常任务 不去关联别的任务,不能是删除任务的操作
                //        {
                //        //bool a = false;
                //        string sqlstr = string.Empty;
                //        string useawayfork = Model.CGeneralFunction.GetUseAwayFork(TaskIdx);//待配对任务需要的货叉不能是该货叉
                //        bool isDoubleForkTask = Model.CGeneralFunction.GetIfDoubleForkTask(TaskIdx, DeviceIdx);
                //        int ControlType = ccf.GetFCONTROLTASKTYPEFromManageTask(_mti, _fid);
                //        int sendz = zxy[0];
                //        int sendx = zxy[1];
                //        int sendy = zxy[2];
                //        string sendcell = string.Format("{0:D2}-{1:D2}-{2:D2}", zxy[0], zxy[1], zxy[2]);//要查找到该送货位置的任务

                //        int getgate = ccf.GetLaneGateDeviceIndexFromLaneGate(sendcell);//送货位置的设备编号

                //        if (!isDoubleForkTask && useawayfork != "0" && ControlType != 2)//不能是出库任务的取货指令&& (getgate==12014|| getgate == 12018|| getgate == 12022)
                //        {
                //            //获得该任务的取货坐标,查找送货坐标是该位置的任务,且其取货位置是固定站台


                //            string warehouse = Model.CGeneralFunction.GetWAREHOUSEFromSTCELL(DeviceIdx);
                //            int relFID = _fid;
                //            //int lane= ccf.GetLaneWayFromLaneInfo(DeviceIdx);

                //            //取货区域


                //            //查找该堆垛机的等带执行的取货任务,任务类型相同,该任务无关联任务,取货及送货货叉不能与该任务相同,
                //            //需要检测选定任务的AheadDetectOK ,目标调度任务无关联任务

                //            //查找调度任务中的第一条设备指令,是该堆垛机的等带执行的取货任务,且任务类型相同(方向相同)

                //            //sqlstr = string.Format(" SELECT F_MonitorIndex,F_ManageTaskIndex,F_ManageTASKKINDINDEX,F_AheadDetect,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6  FROM  T_Monitor_Task  where F_DeviceIndex = {0} and F_DeviceCommandIndex = 4 and F_Status = 0 and  F_MonitorIndex in(SELECT  min(F_MonitorIndex) as minMidx FROM T_Monitor_Task,T_Manage_Task where FID=F_ManageTaskIndex and  T_Manage_Task. F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTASKKINDINDEX  and FCONTROLTASKTYPE= {1}  group by F_ManageTaskIndex) ", DeviceIdx, ControlType);

                //            sqlstr = string.Format(" SELECT F_MonitorIndex,F_ManageTaskIndex,F_ManageTASKKINDINDEX,F_DeviceIndex,F_AheadDetect,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6  FROM  T_Monitor_Task  where F_NumParam4 = {0} and F_NumParam5 = {1} and  F_NumParam6 = {2}  and  F_DeviceCommandIndex = 4 and F_Status = 0 and  F_MonitorIndex in(SELECT  min(F_MonitorIndex) as minMidx FROM T_Monitor_Task,T_Manage_Task where FID=F_ManageTaskIndex and  T_Manage_Task. F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTASKKINDINDEX  and  FCONTROLTASKTYPE!=1  group by F_ManageTaskIndex) ", sendz, sendx,sendy);
                //            dvman = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                //            if (dvman.Count > 0)
                //            {
                //                for (int i = 0; i < dvman.Count; i++)//筛选出从站台取货的任务
                //                {
                //                    int devicestack = Convert.ToInt32(dvman[i]["F_DeviceIndex"]);

                //                    int z = Convert.ToInt32(dvman[i]["F_NumParam1"]);
                //                    int x = Convert.ToInt32(dvman[i]["F_NumParam2"]);
                //                    int y = Convert.ToInt32(dvman[i]["F_NumParam3"]);

                //                    int z1 = Convert.ToInt32(dvman[i]["F_NumParam4"]);
                //                    int x1 = Convert.ToInt32(dvman[i]["F_NumParam5"]);
                //                    int y1 = Convert.ToInt32(dvman[i]["F_NumParam6"]);


                //                    int anothertask = Convert.ToInt32(dvman[i]["F_MonitorIndex"]);
                //                    int anotherfid = Convert.ToInt32(dvman[i]["F_ManageTaskIndex"]);
                //                    int anotherkind = Convert.ToInt32(dvman[i]["F_ManageTASKKINDINDEX"]);
                //                    string aheaddetect = Convert.ToString(dvman[i]["F_AheadDetect"]);
                //                    string anotherfork = useawayfork == "1" ? "2" : "1";
                //                    bool anotherDoubleForkTask = Model.CGeneralFunction.GetIfDoubleForkTask(anothertask, DeviceIdx);
                //                    string NoDetect = string.Format("I{0}", DeviceIdx);//不检测设备空闲,因为还未应答

                //                    string getcell = string.Format("{0:D2}-{1:D2}-{2:D2}", z, x, y);//要查找到该送货位置的任务

                //                    int gate = ccf.GetLaneGateDeviceIndexFromLaneGate(getcell);//送货位置的设备编号
                //                    Model.MDevice devinfostation = Model.CGetInfo.GetDeviceInfo(gate);

                //                    bool AheadDetectOK = ccl.AheadDetectOK(anothertask, aheaddetect, NoDetect);
                //                    //if (!anotherDoubleForkTask&& AheadDetectOK)//需要检测选定任务的AheadDetectOK ,目标调度任务无关联任务
                //                    if (!anotherDoubleForkTask && devinfostation != null && devinfostation.DeviceKind == 9 && AheadDetectOK)//需要检测选定任务的AheadDetectOK ,目标调度任务无关联任务
                //                    {
                //                        int getFork = Model.CGeneralFunction.GetDoubleForkFromST_CELL(z, x, y, warehouse);//取货坐标需要的货叉
                //                        int sendFork = Model.CGeneralFunction.GetDoubleForkFromST_CELL(z1, x1, y1, warehouse);//送货坐标需要的货叉

                //                        if (getFork.ToString() != useawayfork && sendFork.ToString() != useawayfork)//查找到的任务,取送货对应的货叉都不能与该任务相同
                //                        {
                //                            //设置关联任务,新任务设置对应的货叉
                //                            //关联分配三叉


                //                            sql.Remove(0, sql.Length);
                //                            sql.Append("update T_Manage_Task set  F_RELATIVECONTORLID=").Append(relFID).Append(" where F_ManageTaskKindIndex=").Append(_mti).Append(" and FID=").Append(_fid);
                //                            dbo.ExecuteSql(sql.ToString());

                //                            sql.Remove(0, sql.Length);
                //                            sql.Append("update T_Manage_Task set FUseAwayFork= ").Append(anotherfork).Append(",F_RELATIVECONTORLID=").Append(relFID).Append(" where F_ManageTaskKindIndex=").Append(anotherkind).Append(" and FID=").Append(anotherfid);
                //                            dbo.ExecuteSql(sql.ToString());

                //                            sqlstr = string.Format("UPDATE T_Monitor_Task SET F_UseAwayFork ={0} WHERE F_DeviceIndex={1} and F_ManageTaskIndex ={2}  AND  F_ManageTASKKINDINDEX ={3}", anotherfork, devicestack, anotherfid, anotherkind);
                //                            dbo.ExecuteSql(sqlstr);

                //                            if (devicestack != DeviceIdx)
                //                            {

                //                                object[] ob = new object[4] { DeviceIdx, anotherkind, anotherfid, devicestack };
                //                                dbo.ExecuteSql(string.Format("UPDATE T_Monitor_Task SET F_DeviceIndex ={0},F_MonitorTaskLevel=100  WHERE (F_ManageTASKKINDINDEX = {1}) AND (F_ManageTaskIndex = {2}) AND (F_DeviceIndex = {3})", ob));
                //                                dbo.ExecuteSql(string.Format("UPDATE T_Monitor_Task SET F_AheadDetect =replace(F_AheadDetect,{3},{0})  WHERE (F_ManageTASKKINDINDEX = {1}) AND (F_ManageTaskIndex = {2}) ", ob));

                //                            }
                //                            CommonClassLib.CCarryConvert.WriteDarkCasket("拆零区关联双叉,任务号:", _fid.ToString(), anotherfid.ToString(), DeviceIdx.ToString());
                //                            break;

                //                        }
                //                    }

                //                    //取货及送货货叉不能与该任务相同,

                //                }
                //            }
                //            else
                //            {
                //                //sqlstr = string.Format(" SELECT F_MonitorIndex,F_ManageTaskIndex,F_ManageTASKKINDINDEX,F_AheadDetect,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6  FROM  T_Monitor_Task  where F_DeviceIndex = {0} and F_DeviceCommandIndex = 4 and F_Status = 0 and  F_MonitorIndex in(SELECT  min(F_MonitorIndex) as minMidx FROM T_Monitor_Task,T_Manage_Task where FID=F_ManageTaskIndex and  T_Manage_Task. F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTASKKINDINDEX  and FCONTROLTASKTYPE= {1}  group by F_ManageTaskIndex) ", DeviceIdx, ControlType);

                //                sqlstr = string.Format(" SELECT F_MonitorIndex,F_ManageTaskIndex,F_ManageTASKKINDINDEX,F_DeviceIndex,F_AheadDetect,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6  FROM  T_Monitor_Task  where   F_DeviceCommandIndex = 4 and F_Status = 0 and  F_MonitorIndex in(SELECT  min(F_MonitorIndex) as minMidx FROM T_Monitor_Task,T_Manage_Task where FID=F_ManageTaskIndex and  T_Manage_Task. F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTASKKINDINDEX  and  FCONTROLTASKTYPE= {0}  group by F_ManageTaskIndex) ", ControlType);
                //                dvman = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                //                for (int i = 0; i < dvman.Count; i++)//筛选出从站台取货的任务
                //                {
                //                    int devicestack = Convert.ToInt32(dvman[i]["F_DeviceIndex"]);

                //                    int z = Convert.ToInt32(dvman[i]["F_NumParam1"]);
                //                    int x = Convert.ToInt32(dvman[i]["F_NumParam2"]);
                //                    int y = Convert.ToInt32(dvman[i]["F_NumParam3"]);

                //                    int z1 = Convert.ToInt32(dvman[i]["F_NumParam4"]);
                //                    int x1 = Convert.ToInt32(dvman[i]["F_NumParam5"]);
                //                    int y1 = Convert.ToInt32(dvman[i]["F_NumParam6"]);


                //                    int anothertask = Convert.ToInt32(dvman[i]["F_MonitorIndex"]);
                //                    int anotherfid = Convert.ToInt32(dvman[i]["F_ManageTaskIndex"]);
                //                    int anotherkind = Convert.ToInt32(dvman[i]["F_ManageTASKKINDINDEX"]);
                //                    string aheaddetect = Convert.ToString(dvman[i]["F_AheadDetect"]);
                //                    string anotherfork = useawayfork == "1" ? "2" : "1";
                //                    bool anotherDoubleForkTask = Model.CGeneralFunction.GetIfDoubleForkTask(anothertask, DeviceIdx);
                //                    string NoDetect = string.Format("I{0}", DeviceIdx);//不检测设备空闲,因为还未应答

                //                    string getcell = string.Format("{0:D2}-{1:D2}-{2:D2}", z, x, y);//要查找到该送货位置的任务

                //                    int gate = ccf.GetLaneGateDeviceIndexFromLaneGate(getcell);//送货位置的设备编号
                //                    Model.MDevice devinfostation = Model.CGetInfo.GetDeviceInfo(gate);

                //                    bool AheadDetectOK = ccl.AheadDetectOK(anothertask, aheaddetect, NoDetect);
                //                    if (!anotherDoubleForkTask&& AheadDetectOK)//需要检测选定任务的AheadDetectOK ,目标调度任务无关联任务
                //                    //if (!anotherDoubleForkTask && AheadDetectOK&&(gate == 12014 || gate == 12018 || gate == 12022))//需要检测选定任务的AheadDetectOK ,目标调度任务无关联任务
                //                    {
                //                        int getFork = Model.CGeneralFunction.GetDoubleForkFromST_CELL(z, x, y, warehouse);//取货坐标需要的货叉
                //                        int sendFork = Model.CGeneralFunction.GetDoubleForkFromST_CELL(z1, x1, y1, warehouse);//送货坐标需要的货叉
       

                //                        if (getFork.ToString() != useawayfork && sendFork.ToString() != useawayfork)//查找到的任务,取送货对应的货叉都不能与该任务相同
                //                        {
                //                            //设置关联任务,新任务设置对应的货叉
                //                            //关联分配三叉
                //                            if (devicestack != DeviceIdx)
                //                            {
                //                                ccl.AssignStackNo(devicestack, anothertask, anotherkind, anotherfid, "", "", "", 0, 0, false, ControlType);
                //                            }
                //                            sql.Remove(0, sql.Length);
                //                            sql.Append("update T_Manage_Task set  F_RELATIVECONTORLID=").Append(relFID).Append(" where F_ManageTaskKindIndex=").Append(_mti).Append(" and FID=").Append(_fid);

                //                            dbo.ExecuteSql(sql.ToString());

                //                            sql.Remove(0, sql.Length);
                //                            sql.Append("update T_Manage_Task set FUseAwayFork= ").Append(anotherfork).Append(",F_RELATIVECONTORLID=").Append(relFID).Append(" where F_ManageTaskKindIndex=").Append(anotherkind).Append(" and FID=").Append(anotherfid);
                //                            dbo.ExecuteSql(sql.ToString());

                //                            sqlstr = string.Format("UPDATE T_Monitor_Task SET F_UseAwayFork ={0} WHERE F_DeviceIndex={1} and F_ManageTaskIndex ={2}  AND  F_ManageTASKKINDINDEX ={3}", anotherfork, devicestack, anotherfid, anotherkind);
                //                            dbo.ExecuteSql(sqlstr);

                //                            if (devicestack != DeviceIdx)
                //                            {

                //                                object[] ob = new object[4] { DeviceIdx, anotherkind, anotherfid, devicestack };
                //                                dbo.ExecuteSql(string.Format("UPDATE T_Monitor_Task SET F_DeviceIndex ={0},F_MonitorTaskLevel=100  WHERE (F_ManageTASKKINDINDEX = {1}) AND (F_ManageTaskIndex = {2}) AND (F_DeviceIndex = {3})", ob));
                //                                dbo.ExecuteSql(string.Format("UPDATE T_Monitor_Task SET F_AheadDetect =replace(F_AheadDetect,{3},{0})  WHERE (F_ManageTASKKINDINDEX = {1}) AND (F_ManageTaskIndex = {2}) ", ob));

                //                            }
                //                            CommonClassLib.CCarryConvert.WriteDarkCasket("拆零区入库关联双叉,任务号:", _fid.ToString(), anotherfid.ToString(), DeviceIdx.ToString());
                //                            break;

                //                        }
                //                    }

                //                    //取货及送货货叉不能与该任务相同,

                //                }


                //            }


                //        }
                //    }
                    

                //}

                #endregion
                int tsorder = 0;
                int fid = _fid;
                int mti = _mti;
                int relativeFID = ccf.GetRELATIVECONTORLIDFromManageTask(mti, fid);
                if (relativeFID == -1) relativeFID = 0;
                #region 广西华友出库AGV后续任务  货物到AG取货口报完成时给管理报完成
                //if (DeviceIdx == 32025)
                //{
                //    sql.Remove(0, sql.Length);
                //    sql.Append("update IO_Control set CONTROL_END_TIME =GETDATE(), CONTROL_STATUS=").Append(Model.CGeneralFunction.TASKFINISH).Append(" where CONTROL_ID=").Append(fid);
                //    if (dboM.ExecuteSql(sql.ToString()) > 0)
                //    {
                //        CommonClassLib.CCarryConvert.WriteDarkCasket("ActionComplete", "AGV出库任务提前给管理上报完成:" + Model.CGeneralFunction.TASKFINISH.ToString(), ",条码[" + barcode + "]", ",CONTROL_ID:" + fid);
                //    }
                //}

                #endregion

                int relativeTaskFID = 0;
                string cap;
                
                
                //20101011
                #region 补充逻辑预约锁的解锁(此调度任务的此设备的最后一个命令需要解锁,有关联任务的改为关联任务预约)
                
                if ((devKind == 1) || (devKind == 4))
                {
                    sql.Remove(0, sql.Length);
                    sql.Append("select count(F_MonitorIndex) as counts from T_Monitor_Task " ).Append(
                        " where F_ManageTaskIndex =" ).Append( fid ).Append( " and F_ManageTaskKindIndex= " ).Append( mti ).Append( " and F_DeviceIndex=" ).Append( DeviceIdx);
                    object ob = dbo.GetSingle(sql.ToString());
                    if (Convert.ToInt32(ob) == 1)
                    {
                       
                        #region 有管理任务存在,增加关联任务预约锁//20100710
                        sql.Remove(0, sql.Length);
                        sql.Append("SELECT T_Manage_Task.FID FROM T_Manage_Task ,T_Monitor_Task where T_Manage_Task.FID<>").Append(fid).Append(" and   T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX AND T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex  and (T_Manage_Task.F_RELATIVECONTORLID = ").Append(relativeFID).Append(") AND (T_Manage_Task.F_ManageTaskKindIndex = ").Append(mti).Append(") and F_DeviceIndex=").Append(DeviceIdx).Append("");
                        ob = dbo.GetSingle(sql.ToString());
                        if ((ob != null)&&(devinfo.IfCorrelDoubleFork=="1"))
                        {
                            relativeTaskFID = Convert.ToInt32(ob);
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Base_Device set F_ManTaskReserve=" ).Append( (mti.ToString() + ob.ToString()) ).Append( " where F_ManTaskReserve=" ).Append( (mti.ToString() + fid.ToString()) ).Append( " and F_DeviceIndex=" + DeviceIdx);
                            dbo.ExceSQL(sql.ToString());
                        }
                        else
                        {
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Base_Device set F_ManTaskReserve=0 where F_ManTaskReserve=" ).Append( (mti.ToString() + fid.ToString()) ).Append( " and F_DeviceIndex=" ).Append( DeviceIdx);
                            dbo.ExceSQL(sql.ToString());
                            sql.Remove(0, sql.Length);
                            //sql.Append("update T_Manage_Task set F_RELATIVECONTORLID=-1").Append(" where F_ManageTaskKindIndex=").Append(mti).Append(" and (FID=").Append(fid).Append(" or F_RELATIVECONTORLID=").Append(fid).Append(")");
                            //dbo.ExecuteSql(sql.ToString());
                            
                        }

                        #region 堆垛机送货的输送机解逻辑预约锁
                        //20120409
                        int stackdev = 0;
                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        if (devinfo.VirtualStack>0)
                        {//20111231
                            stackdev = devinfo.VirtualStack;
                        }
                        else
                        {
                            stackdev = DeviceIdx;
                        }
                        sql.Remove(0, sql.Length);
                        sql.Append("SELECT T_Base_Lane_Gate.F_LaneGateDeviceIndex from T_Base_Lane_Gate,T_Base_LaneInfo ").Append(
                            " where T_Base_Lane_Gate.F_LaneIndex = T_Base_LaneInfo.F_LaneDeviceIndex and T_Base_Lane_Gate.F_ZXY='").Append(zxystr).Append("' ").Append(
                            "  and T_Base_LaneInfo.F_StackIndex=").Append(stackdev);
                        dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dvlane.Count > 0)
                        {
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Base_Device set F_ManTaskReserve=0 where F_DeviceIndex=").Append(dvlane[0]["F_LaneGateDeviceIndex"]);
                            dbo.ExceSQL(sql.ToString());
                        }
                        #endregion

                        #endregion
                    }
                }
                #endregion

                if ((errrcode == Model.CGeneralFunction.TASKCHANGESTACK) && (devinfo.VirtualStack > 0) && (order == 5))//20101011倒换堆垛机
                {//解除关联任务,更换堆垛机,追加两个任务,倒库位取货,送到真实货位,管理任务的FExceptionNO==null
                    if (AppendStackMoveCellOperate(mti, fid, DeviceIdx, TaskIdx) == false) return;
                }
                if ((errrcode == Model.CGeneralFunction.TASKEXCHANGE) && (devinfo.VirtualStack > 0) && (order == 5))//20101011缓存站台
                {//解除关联任务,更换堆垛机,追加两个任务,倒库位取货,送到真实货位,管理任务的FExceptionNO==null
                    if (AppendStackMoveExchangeOperate(mti, fid, DeviceIdx, TaskIdx) == false) return;
                }
                //20100108
                sql.Remove(0, sql.Length);
                sql.Append("select count(F_MonitorIndex) as counts from T_Monitor_Task " ).Append(
                    " where F_ManageTaskIndex =" ).Append( fid ).Append( " and F_ManageTaskKindIndex= " ).Append( mti);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    int rowco = 0;


                    #region 最后一个调度任务的处理

                    if ((Convert.ToInt32(dv[0]["counts"]) == 1)) //20091016
                    {
                        //固定路径模式
                        //调度任务的fid的最后一个监控分解任务完成

                        if (mti == 1)
                        {
                            cap = "调度任务";
                            //完成FSTATUS=999;970堆垛机送货重故障异常完成;980堆垛机取空故障异常完成;990条码扫描异常完成;
                            //调度撤销删除调度任务900;950送到拆盘机的不是空托盘组;940人工暂停出库任务
                            //20090902
                            if ((errrcode >= 900) || (ClearZero == Model.CGeneralFunction.TASKDELETE))//异常完成
                            {
                                if(errrcode== Model.CGeneralFunction.TASKDELETE)
                                    ClearZero = errrcode;
                                
                                else if (errrcode == Model.CGeneralFunction.TASKREPEATINPUT)
                                {
                                    errrcode = Model.CGeneralFunction.TASKREPEATINPUT;//聊城修改,以前是Model.CGeneralFunction.TASKFINISH
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update IO_Control set ERROR_TEXT='堆垛机的送货重故障异常完成' where CONTROL_ID=").Append(fid);
                                    dboM.ExceSQL(sql.ToString());
                                }
                                else if (errrcode == Model.CGeneralFunction.TASKEMPTYOUTPUT)
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update IO_Control set ERROR_TEXT='堆垛机取空故障异常完成' where CONTROL_ID=").Append(fid);
                                    dboM.ExceSQL(sql.ToString());
                                }
                                else if (errrcode == Model.CGeneralFunction.TASKABEND)
                                {
                                    ////20120224南京14所异常完成需要插入IO_CONTROL_APPLY
                                    //dtime = DateTime.Now.ToString("u");
                                    //dtime.Remove(dtime.Length - 1, 1);
                                    //StringBuilder sb = new StringBuilder("01");
                                    //if (enddevice == 32025)
                                    //{
                                    //    sb = new StringBuilder("03");
                                    //}
                                    //else
                                    //{
                                    //    sb = new StringBuilder("04");
                                    //}

                                    //int apptype = 3;
                                    //object[] ob = new object[8] { apptype, enddevice, barcode, 0, dtime, "", sb.ToString(), fid };
                                    //try
                                    //{
                                    //    dboM.ExecuteSql(string.Format("INSERT INTO IO_CONTROL_APPLY( CONTROL_APPLY_TYPE,DEVICE_CODE, STOCK_BARCODE, APPLY_TASK_STATUS, CREATE_TIME,CONTROL_APPLY_REMARK,WAREHOUSE_CODE,CONTROL_ID)VALUES ({0},{1},'{2}',{3},'{4}','{5}','{6}',{7})", ob));
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //    RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", "扫码异常,向管理申请时发生错误:" + ex.Message);
                                    //    OnRefreshMonitor(rmea);

                                    //}

                                    sql.Remove(0, sql.Length);
                                    sql.Append("update IO_Control set ERROR_TEXT='条码比对错误异常完成' where CONTROL_ID=").Append(fid);
                                    dboM.ExceSQL(sql.ToString());
                                }
                                else if (errrcode == Model.CGeneralFunction.TASKTYPEERROR)
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update IO_Control set ERROR_TEXT='送到拆盘机的不是空托盘组' where CONTROL_ID=").Append(fid);
                                    dboM.ExceSQL(sql.ToString());
                                }
                                else if (errrcode == Model.CGeneralFunction.TASKSTOPOUTPUT)
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update IO_Control set ERROR_TEXT='人工暂停出库任务' where CONTROL_ID=").Append(fid);
                                    dboM.ExceSQL(sql.ToString());
                                }
                                else if (ClearZero == Model.CGeneralFunction.TASKDELETE)//20141201赵宇发现,删除设备指令队列时对970或者980有影响,可能改为900,最好放在if条件的最下面
                                    errrcode = ClearZero;
                                //20100304
                               
                                switch (CStaticClass.ManDBFactory)
                                {
                                    case "OracleDBFactory":
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update IO_Control set CONTROL_END_TIME =sysdate, CONTROL_STATUS=").Append(errrcode).Append(" where CONTROL_ID=").Append(fid);
                                        rowco=dboM.ExecuteSql(sql.ToString());

                                        break;
                                    case "SQLServerDBFactory":
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update IO_Control set CONTROL_END_TIME =GETDATE(), CONTROL_STATUS=" ).Append( errrcode ).Append( " where CONTROL_ID=" ).Append( fid);
                                        rowco=dboM.ExecuteSql(sql.ToString());
                                        break;
                                    case "OleDBFactory":
                                        dtime = DateTime.Now.ToString("u");
                                        dtime = dtime.Substring(0, dtime.Length - 1);
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update IO_Control set CONTROL_END_TIME ='" ).Append( dtime).Append( "', CONTROL_STATUS=" ).Append( errrcode ).Append( " where CONTROL_ID=" ).Append( fid);
                                        rowco=dboM.ExecuteSql(sql.ToString());
                                        break;
                                }
                                if (rowco > 0)
                                {
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("ActionComplete", "给管理上报完成:" + errrcode.ToString(), ",条码[" + barcode + "]", ",CONTROL_ID:" + fid);
                                }

                            }
                            else
                            {
                                //完成FSTATUS=999
                                switch (CStaticClass.ManDBFactory)
                                {
                                    case "OracleDBFactory":
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update IO_Control set CONTROL_END_TIME =sysdate, CONTROL_STATUS=" ).Append( Model.CGeneralFunction.TASKFINISH ).Append( " where CONTROL_ID=" ).Append( fid);
                                        rowco=dboM.ExecuteSql(sql.ToString());
                                        break;
                                    case "SQLServerDBFactory":
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update IO_Control set CONTROL_END_TIME =GETDATE(), CONTROL_STATUS=" ).Append( Model.CGeneralFunction.TASKFINISH ).Append( " where CONTROL_ID=" ).Append( fid);
                                        rowco = dboM.ExecuteSql(sql.ToString());
                                        break;
                                    case "OleDBFactory":
                                        dtime = DateTime.Now.ToString("u");
                                        dtime = dtime.Substring(0, dtime.Length - 1);
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update IO_Control set CONTROL_END_TIME ='" ).Append( dtime ).Append( "', CONTROL_STATUS=" ).Append( Model.CGeneralFunction.TASKFINISH ).Append( " where CONTROL_ID=" ).Append( fid);
                                        rowco = dboM.ExecuteSql(sql.ToString());
                                        break;
                                }
                                if (rowco > 0)
                                {
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("ActionComplete", "给管理上报完成:" + Model.CGeneralFunction.TASKFINISH.ToString(), ",条码[" + barcode + "]", ",CONTROL_ID:" + fid);
                                }

                            }
                        }
                        else if (mti == 4)
                        {
                            cap = "手工任务";
                        }
                        else
                        {
                            cap = "临时任务";
                        }
                        if ((errrcode == Model.CGeneralFunction.TASKCHANGEFORK) && (devKind == 1) && (devinfo.IfCorrelDoubleFork == "1"))//20101011换货叉处理
                        {//解除关联任务,更换货叉,追加两个任务,倒库位取货,送到真实货位,管理任务的FExceptionNO==null
                            if (AppendMoveCellOperate(mti, fid, DeviceIdx, TaskIdx) == false) return;
                        }
                        else
                        {//20101011
                            //回写管理表//20091128
                            if ((ClearZero == Model.CGeneralFunction.TASKDELETE) || (ClearZero == Model.CGeneralFunction.TASKSTOPOUTPUT))//调度撤销删除调度任务900;人工暂停出库任务940
                            {
                                ReturnManageInfo(fid, mti, cap, false);
                            }
                            else
                            {
                                ReturnManageInfo(fid, mti, cap, true);
                            }
                        }
                    }
                    #endregion
                }

                //被这个任务号锁定的设备全部解锁
                sql.Remove(0, sql.Length);
                sql.Append("update T_Base_Device set F_LockedState=0 where F_LockedState=" ).Append( TaskIdx);
                dbo.ExceSQL(sql.ToString());
                //被这个任务号逻辑有物的全部解开
                sql.Remove(0, sql.Length);
                sql.Append("update T_Base_Device set F_HaveGoods=0  where F_HaveGoods=").Append(TaskIdx);
                dbo.ExceSQL(sql.ToString());
                if ((ClearZero != Model.CGeneralFunction.TASKDELETE) && (errrcode != Model.CGeneralFunction.TASKDELETE))//20120102删除调度任务不置逻辑有物
                {
                    #region 堆垛机接货输送机完成时逻辑无货20100710
                    sql.Remove(0, sql.Length);
                    sql.Append("SELECT F_LaneGateDeviceIndex  FROM T_Base_Lane_Gate where F_LaneGateDeviceIndex=").Append(DeviceIdx);
                    dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                    if (dvlane.Count > 0)
                    {
                        //if (zxy[3] == 0)//20110608
                        //{
                        sql.Remove(0, sql.Length);
                        sql.Append("update T_Base_Device set F_HaveGoods=0  where F_HaveGoods=").Append(TaskIdx);
                        dbo.ExceSQL(sql.ToString());
                        //}
                    }
                    else
                    {//AGV接货输送机完成时逻辑无货20100710
                        //sql.Remove(0, sql.Length);
                        //sql.Append("SELECT F_AGVGateDeviceIndex  FROM T_Base_AGV_Gate where F_AGVGateDeviceIndex=").Append(DeviceIdx);
                        //dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        //if (dvlane.Count > 0)
                        //{
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Base_Device set F_HaveGoods=0  where F_HaveGoods=").Append(TaskIdx);
                            dbo.ExceSQL(sql.ToString());
                        //}
                    }
                    #endregion

                    #region 堆垛机放货、AGV逻辑有物和取货后顶升下降的处理;在输送机取货,置输送机逻辑无物20101011

                    if ((devKind == 1) && ((order == 4) || (order == 5) || (order == 6)))//20101011
                    {

                        bool sh = false;//20101011
                        bool qh = false;//20101011
                        if (order == 5) sh = true;//20101011
                        if (order == 4) qh = true;//20101011
                        if (order == 6)//20101011
                        {
                            sh = true;
                            qh = true;
                        }
                        int stackdev = 0;
                        if (devinfo.VirtualStack > 0)
                        {//20111231
                            stackdev = devinfo.VirtualStack;
                        }
                        else
                        {
                            stackdev = DeviceIdx;
                        }
                        if (sh == true)//20101011
                        {
                            //20090918给堆垛机送货的输送机增加逻辑有物
                            ////20100609改为使用巷道表关联

                            sql.Remove(0, sql.Length);
                            sql.Append("SELECT T_Base_Lane_Gate.F_LaneGateDeviceIndex from T_Base_Lane_Gate,T_Base_LaneInfo ").Append(
                                " where T_Base_Lane_Gate.F_LaneIndex = T_Base_LaneInfo.F_LaneDeviceIndex and T_Base_Lane_Gate.F_ZXY='").Append(zxystr).Append("' ").Append(
                                "  and T_Base_LaneInfo.F_StackIndex=").Append(stackdev);
                            dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            if (dvlane.Count > 0)
                            {
                                #region 20120518如果是倒叉货位nexttaskindex取比当前任务小的第一个任务
                                if (ccf.IfChangeForkCell(stackdev, zxystr.ToString()) == true)
                                {
                                    nexttaskindex = ccf.GetPriorMonitorTaskIndex(TaskIdx);

                                }
                                #endregion

                                int lanegate = Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]);
                                if (lanegate.ToString().Length == 6)
                                {
                                    lanegate = Convert.ToInt32(lanegate.ToString().Substring(0, 5));//20180127
                                }

                                sql.Remove(0, sql.Length);//20120409只有输送机置为逻辑有物
                                //sql.Append("update T_Base_Device set F_HaveGoods=").Append(nexttaskindex).Append(" where F_DeviceKindIndex=2 and F_DeviceIndex=").Append(lanegate);
                                sql.Append("update T_Base_Device set F_HaveGoods=").Append(nexttaskindex).Append(" where  F_DeviceIndex=").Append(lanegate);

                                dbo.ExceSQL(sql.ToString());

                                if (nexttaskindex == 0)//20180522 对于固定站台设置逻辑有物
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update T_Base_Device set F_HaveGoods=").Append(1).Append(" where F_DeviceKindIndex=9 and F_DeviceIndex=").Append(lanegate);
                                    dbo.ExceSQL(sql.ToString());
                                }
                                //放货完成后,设置当前执行设备为站台编号20181106
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Manage_Task set FCurrentLocation=").Append(
                                    lanegate).Append(" where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                                dbo.ExceSQL(sql.ToString());



                            }
                        }
                        if (qh == true)//在输送机取货,置输送机逻辑无物//20101011
                        {

                            zxystr.Remove(0, zxystr.Length);
                            zxystr.Append((zxy[0].ToString().Length == 1 ? "0" + zxy[0].ToString() : zxy[0].ToString())).Append("-").Append(
                                ((zxy[1].ToString().Length == 1) ? ("0" + zxy[1].ToString()) : (zxy[1].ToString()))).Append("-").Append(
                                ((zxy[2].ToString().Length == 1) ? ("0" + zxy[2].ToString()) : (zxy[2].ToString())));
                            sql.Remove(0, sql.Length);
                            sql.Append("SELECT F_LifterDown,F_ChangeForkCell,T_Base_Lane_Gate.F_LaneGateDeviceIndex from T_Base_Lane_Gate,T_Base_LaneInfo ").Append(
                                " where T_Base_Lane_Gate.F_LaneIndex = T_Base_LaneInfo.F_LaneDeviceIndex and T_Base_Lane_Gate.F_ZXY='").Append(zxystr).Append("' ").Append(
                                "  and T_Base_LaneInfo.F_StackIndex=").Append(stackdev);
                            dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            if (dvlane.Count > 0)
                            {
                                int lanegate = Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]);//20180127
                                if (lanegate.ToString().Length == 6)
                                {
                                    lanegate = Convert.ToInt32(lanegate.ToString().Substring(0, 5));
                                }

                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Base_Device set F_HaveGoods=0,F_ManTaskReserve=0,F_PALLETBARCODE='-' where F_DeviceIndex=").Append(lanegate);
                                dbo.ExceSQL(sql.ToString());
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Base_PLC_Ask set F_TaskIndex=0,F_Remark='' where F_DeviceIndex=").Append(lanegate);
                                dbo.ExecuteSql(sql.ToString());//20101011
                                #region 堆垛机在顶升机取货完成时,发送顶升机的下降动作9;//20120906倒库和辊道输送机设备不发送【下降】
                                //if ((dvlane[0]["F_LifterDown"].ToString() == "1"))//(ClearZero >= 1) && 
                                //{//高端的发送到UCode,F_NumParam1是顶升设备,F_NumParam4是顶升设备
                                //    int hidx = ccf.GetTempManageIdx();//20110510
                                //    int hmidx = ccf.GetMonitorIndex(hidx, 2);
                                //    string ah = "";
                                //    int sdev = 0, begindev = 0, arrdev = 0;
                                //    int ucode = ccf.GetUCodeFromDeviceGD(Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]));
                                //    if (ucode > 0)
                                //    {
                                //        sdev = ucode;
                                //        begindev = Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]);
                                //        arrdev = Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]);

                                //    }
                                //    else
                                //    {

                                //        sdev = Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]);
                                //        begindev = 0;
                                //        arrdev = 0;
                                //        ah = string.Format("D-{0}.6;I{0}", sdev.ToString());
                                //    }

                                //    sql.Remove(0, sql.Length);
                                //    sql.Append("insert into T_Monitor_Task(F_MonitorTaskLevel,F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex,").
                                //            Append("F_DeviceIndex,F_DeviceCommandIndex,F_UseAwayFork,F_AheadDetect,F_TxtParam,F_NumParam1,F_NumParam4) ").
                                //            Append("values(2,").Append(GetRouteIDsub(sdev)).Append(",").
                                //            Append(hidx).Append(",2,").Append(hmidx).Append(",").Append(sdev).
                                //             Append(",9,'-','").Append(ah).Append("','").Append(ccf.GetBarCodeFromMonitor(TaskIdx)).Append("',").Append(begindev).Append(",").Append(arrdev).Append(")");//20110510
                                //    dbo.ExecuteSql(sql.ToString());

                                //}
                                #endregion
                            }
                        }
                    }

                    else if ((devKind == 6) && (order == 3) && (AgvNextDeviceKind == 2))//AGV向输送机放货20100710
                    {
                        sql.Remove(0, sql.Length);
                        sql.Append("update T_Base_Device set F_HaveGoods=").Append(nexttaskindex).Append(" where F_DeviceIndex=").Append(zxy[4]);
                        dbo.ExceSQL(sql.ToString());
                    }



                    #endregion
                }
                else
                {
                     #region 删除堆垛机取货,取消多叉关联

                    if ((devKind == 1) && (order == 4) )//20120312
                    {
                        int stackdev = 0;
                        if (devinfo.VirtualStack>0)
                        {//20111231
                            stackdev = devinfo.VirtualStack;
                        }
                        else
                        {
                            stackdev = DeviceIdx;
                        }
                        zxystr.Remove(0, zxystr.Length);
                        zxystr.Append((zxy[0].ToString().Length == 1 ? "0" + zxy[0].ToString() : zxy[0].ToString())).Append("-").Append(
                            ((zxy[1].ToString().Length == 1) ? ("0" + zxy[1].ToString()) : (zxy[1].ToString()))).Append("-").Append(
                            ((zxy[2].ToString().Length == 1) ? ("0" + zxy[2].ToString()) : (zxy[2].ToString())));
                        sql.Remove(0, sql.Length);
                        sql.Append("SELECT F_LifterDown,F_ChangeForkCell,T_Base_Lane_Gate.F_LaneGateDeviceIndex from T_Base_Lane_Gate,T_Base_LaneInfo ").Append(
                            " where T_Base_Lane_Gate.F_LaneIndex = T_Base_LaneInfo.F_LaneDeviceIndex and T_Base_Lane_Gate.F_ZXY='").Append(zxystr).Append("' ").Append(
                            "  and T_Base_LaneInfo.F_StackIndex=").Append(stackdev);
                        dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dvlane.Count > 0)
                        {
                            int lanegate = Convert.ToInt32(dvlane[0]["F_LaneGateDeviceIndex"]);//20180127
                            if (lanegate.ToString().Length == 6)
                            {
                                lanegate = Convert.ToInt32(lanegate.ToString().Substring(0, 5));
                            }
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Base_PLC_Ask set F_TaskIndex=0,F_Remark='' where F_TaskIndex=").Append(TaskIdx).Append(" and F_DeviceIndex=").Append(lanegate);
                            dbo.ExecuteSql(sql.ToString());
                            
                        }
                    }
                     #endregion
                }


                #region 保留AGV、RGV、堆垛机接驳口的输送机的条码20140109
                bool saveBarcode = false;
                sql.Clear();
                sql.Append("SELECT F_AGVGateDeviceIndex FROM T_Base_AGV_Gate where F_AGVGateDeviceIndex=").Append(DeviceIdx);
                if (dbo.GetSingle(sql.ToString()) != null)
                {
                    saveBarcode = true;
                }
                sql.Clear();
                sql.Append("SELECT F_RGVGateDeviceIndex FROM T_Base_RGV_Gate where F_RGVGateDeviceIndex=").Append(DeviceIdx);
                if (dbo.GetSingle(sql.ToString()) != null)
                {
                    saveBarcode = true;
                }
                sql.Clear();
                sql.Append("SELECT F_LaneGateDeviceIndex FROM T_Base_Lane_Gate where F_LaneGateDeviceIndex=").Append(DeviceIdx);
                if (dbo.GetSingle(sql.ToString()) != null)
                {
                    saveBarcode = true;
                }
                if (saveBarcode == true && mti !=4)
                {
                    dbo.ExecuteSql(string.Format("UPDATE T_Base_Device SET F_ManTaskReserve={2},F_PALLETBARCODE =  '{0}' WHERE (F_DeviceIndex = {1})", barcode, DeviceIdx, Convert.ToInt32(mti.ToString()+fid.ToString())));//20140309
                }
                #endregion
                sql.Remove(0, sql.Length);
                sql.Append("delete from T_Monitor_Task   where F_MonitorIndex=" ).Append( TaskIdx);
                dbo.ExceSQL(sql.ToString());
                //dbo.TransCommit();
                //给PLC发送应答头是2,其余都是零
                //根据设备类型判断错误编号
                
                
                if (ClearZero == 1)
                {
                    if (mti == 1)
                    {
                        sql.Remove(0, sql.Length);
                        sql.Append("UPDATE IO_CONTROL  SET  ERROR_TEXT =''  WHERE CONTROL_ID=").Append(fid).Append(" and CONTROL_STATUS<900");
                        dboM.ExceSQL(sql.ToString());
                    }
                    if ((devKind == 1) || (devKind == 6)) //堆垛机、AGV
                    {

                        sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                        sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                    }
                    else
                    {//输送机、RGV故障清零
                        //20130221增加对RGV,AGV等取货站台的应答保护:只有DeviceIdx出口有货时才应答
                        //if (devKind == 2 && UnAccordResponse(DeviceIdx)==true ) { }
                        //else
                        //{
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);

                            sdo.SendDeviceOrder(2, 0, tsorder, DeviceIdx, 0);
                        //}
                    }
                }
                //if (devKind == 1 &&( order ==2||order == 3||order == 5||order == 7))//堆垛机送货完成后
                //{
                //    if (DeviceIdx == 31005 || DeviceIdx==31006)// 双轨堆垛机
                //    {
                //        int x;
                //        if (order == 2 || order == 7)//将取,运动 
                //        {
                //            x = zxy[1];

                //        }
                //        else//将送3,送货5
                //        {
                //            x = zxy[4];
                //        }

                //        if(x>=22&&x<=30)    //   if(x>=22&&x<=30)            
                //        {

                //            string sqlin = "SELECT  min(F_MonitorIndex) as minMidx FROM T_Monitor_Task,T_Manage_Task where FID=F_ManageTaskIndex and  T_Manage_Task. F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTASKKINDINDEX   group by F_ManageTaskIndex";

                //          string   sqlstrs = string.Format("select F_MonitorIndex,F_AheadDetect  from T_Monitor_Task where F_DeviceIndex={0} and F_MonitorIndex in({1}) ", DeviceIdx, sqlin);

                //            //dv = dbo.ExceSQL(string.Format("select F_MonitorIndex from T_Monitor_Task where F_DeviceIndex={0} and F_TxtParam='brbrbr'", DeviceIdx)).Tables[0].DefaultView;
                //            //dv = dbo.ExceSQL(string.Format("select F_MonitorIndex,F_AheadDetect  from T_Monitor_Task where F_DeviceIndex={0}  and  F_ManageTaskIndex={1}  and  F_ManageTASKKINDINDEX={2} ", DeviceIdx, relativeTaskFID,mti)).Tables[0].DefaultView;
                //            //dv = dbo.ExceSQL(string.Format("select F_MonitorIndex,F_AheadDetect  from T_Monitor_Task where F_DeviceIndex={0} and  F_NumParam4 !/={1} and F_NumParam5 != {2}  and F_NumParam6 !={3}", DeviceIdx, zxy[3], zxy[4], zxy[5])).Tables[0].DefaultView;
                //            //dv = dbo.ExceSQL(string.Format("select F_MonitorIndex,F_AheadDetect  from T_Monitor_Task where F_DeviceIndex={0} ", DeviceIdx)).Tables[0].DefaultView;
                //            dv = dbo.ExceSQL(sqlstrs).Tables[0].DefaultView;
                //            bool AheadDetectOK = false;
                //            if (dv.Count > 0)
                //            {
                //                string ahead ;
                //                int task ;
                //                string NoDetect;

                //                for (int  i=0;i<dv.Count;i++)
                //                {
                //                     ahead = Convert.ToString(dv[i]["F_AheadDetect"]);
                //                     task = Convert.ToInt32(dv[i]["F_MonitorIndex"]);

                //                     NoDetect = string.Format("I{0}", DeviceIdx);//不检测设备空闲,因为还未应答

                //                    AheadDetectOK = ccl.AheadDetectOK(task, ahead, NoDetect);
                //                    if (AheadDetectOK)
                //                    { break; }

                //                }

                //                // ahead= Convert.ToString(dv[0]["F_AheadDetect"]);
                //                // task = Convert.ToInt32(dv[0]["F_MonitorIndex"]);

                //                // NoDetect = string.Format("I{0}", DeviceIdx);//不检测设备空闲,因为还未应答

                //                //AheadDetectOK = ccl.AheadDetectOK(task, ahead, NoDetect);
                //                ////AheadDetectOK = true;


                //            }
                //            if (dv.Count <= 0|| !AheadDetectOK)//生成避让任务
                //            {
                //                int hidx = ccf.GetTempManageIdx();
                //                int hmindx = ccf.GetMonitorIndex(hidx, 2);
                //                int rgvorder = 7;//运动
                //                int newz = 0;
                //                int newx = 0;
                //                int newy = 1;
                //                if (DeviceIdx == 31005)
                //                {
                //                    newz = 9;
                //                    newx =60;//20181219
                //                    newy = 1;
                //                }
                //                else
                //                {
                //                     newz = 9;
                //                     newx = 20;
                //                     newy = 1;
                //                }

                //                sql.Remove(0, sql.Length);
                //                sql.Append("insert into T_Monitor_Task(F_MonitorTaskLevel,F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex,").
                //                        Append("F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_TxtParam,F_AheadDetect) ").
                //                        Append("values(2,").Append(ccf.GetRouteIDsub(DeviceIdx)).Append(",").
                //                        Append(hidx).Append(",4,").Append(hmindx).Append(",").Append(DeviceIdx).
                //                        Append(",").Append(rgvorder).Append(",").Append(newz).Append(",").Append(newx).Append(",").Append(newy).Append(",").Append(0).Append(",").Append(0).Append(",").Append(0).Append(",'brbrbr','-')");
                //                dbo.ExecuteSql(sql.ToString());
                //            }


                //        }
                //    }
                //}
                //if (devKind == 4&&order==3)//穿梭车送货完成后
                //{
                //    if (zxy[0] == 13014 || zxy[0] == 13015)//目标位置是转台
                //    {
                //    dv = dbo.ExceSQL(string.Format("select F_MonitorIndex from T_Monitor_Task where F_DeviceIndex={0} and F_TxtParam='brbrbr'", DeviceIdx)).Tables[0].DefaultView;
                //    if (dv.Count <= 0)
                //    {
                //        int hidx = ccf.GetTempManageIdx();
                //        int hmindx = ccf.GetMonitorIndex(hidx, 2);
                //        int rgvorder = 1;
                //        int nextdevice = 13012;
                //        sql.Remove(0, sql.Length);
                //        sql.Append("insert into T_Monitor_Task(F_MonitorTaskLevel,F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex,").
                //                Append("F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_TxtParam,F_AheadDetect) ").
                //                Append("values(2,").Append(ccf.GetRouteIDsub(DeviceIdx)).Append(",").
                //                Append(hidx).Append(",4,").Append(hmindx).Append(",").Append(DeviceIdx).
                //                Append(",").Append(rgvorder).Append(",").Append(nextdevice).Append(",").Append(0).Append(",").Append(0).Append(",").Append(0).Append(",").Append(0).Append(",").Append(0).Append(",'brbrbr','-')");
                //        dbo.ExecuteSql(sql.ToString());
                //    }
                //    }

                //    //放货完成后,设置当前执行设备为站台编号20181106
                //    sql.Remove(0, sql.Length);
                //    sql.Append("update T_Manage_Task set FCurrentLocation=").Append(
                //        zxy[0]).Append(" where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                //    dbo.ExceSQL(sql.ToString());

                //}
                CDataChangeEventArgs dcea = new CDataChangeEventArgs(null, null);
                OnDataChange("ActionComplete",dcea);
                
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("报告完成时:{0}" ,DeviceIdx.ToString()+ ex.StackTrace+ ex.Message));
                OnRefreshMonitor(rmea);
            }
            finally
            {//20100108
                //dvman.Dispose() ;
                //dv.Dispose();
                //dvlane.Dispose() ;
                //dvr.Dispose();
            }
        }

        private bool UnAccordResponse(int DeviceIdx)
        {//20130221
            DataView dv = new DataView();
            bool ifCheckHaveGoods = false;
            try
            {
                dv = dbo.ExceSQL(string.Format("SELECT F_AGVGateDeviceIndex FROM T_Base_AGV_Gate WHERE (F_AGVGateDeviceIndex = {0})", DeviceIdx)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    ifCheckHaveGoods = true;
                }
                if (ifCheckHaveGoods == false)
                {
                    dv = dbo.ExceSQL(string.Format("SELECT F_RGVGateDeviceIndex FROM T_Base_RGV_Gate WHERE (F_RGVGateDeviceIndex = {0})", DeviceIdx)).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        ifCheckHaveGoods = true;
                    }
                }
                if (ifCheckHaveGoods == true)
                {
                    devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                    if (CStaticClass.GetDevicePhotoelectric(devinfo.BindingDeviceOut) != 1) return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("报告完成,UnAccordResponse时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rmea);
                return false;
            }
            finally
            {
                dv.Dispose();
            }
        }

        private bool GetNearDeviceInputTask(int DeviceIdx, string zxystr)
        {
            DataView dv = new DataView();
            DataView dvm = new DataView();
            DataView dm = new DataView();
            try
            {
                int stackdev = 0;
                devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                if (devinfo.VirtualStack>0)
                {//20111231
                    stackdev = devinfo.VirtualStack;
                }
                else
                {
                    stackdev = DeviceIdx;
                }
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_LaneIndex, F_ZXY, F_NearDevice from T_Base_Lane_Gate,T_Base_LaneInfo ").Append(
                    " where T_Base_Lane_Gate.F_LaneIndex = T_Base_LaneInfo.F_LaneDeviceIndex and T_Base_Lane_Gate.F_ZXY='").Append(zxystr).Append("' ").Append(
                    "  and T_Base_LaneInfo.F_StackIndex=").Append(stackdev);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    dv = dbo.ExceSQL(string.Format("SELECT F_LaneIndex, F_ZXY, F_NearDevice from T_Base_Lane_Gate where F_LaneIndex={0} and F_NearDevice={1}",
                        Convert.ToInt32( dv[0]["F_LaneIndex"]),Convert.ToInt32( dv[0]["F_NearDevice"]))).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {//堆垛机在这些货位的取货任务是否为第一个设备指令
                        char[] cc = new char[1] { '-' };
                        string[] sp; int z = 0, x = 0, y = 0;
                        object[] ob = new object[4];

                        for (int i = 0; i < dv.Count; i++)
                        {
                            sp = dv[i]["F_ZXY"].ToString().Split(cc);
                            z =Convert.ToInt32( sp[0]);
                            x = Convert.ToInt32(sp[1]);
                            y = Convert.ToInt32(sp[2]);
                            ob[0] = DeviceIdx;
                            ob[1] = z;
                            ob[2] = x;
                            ob[3] = y;
                            dvm = dbo.ExceSQL(string.Format("SELECT F_ManageTASKKINDINDEX, F_ManageTaskIndex, F_MonitorIndex FROM T_Monitor_Task WHERE (F_DeviceIndex = {0}  and F_DeviceCommandIndex=4 and F_Status=0) AND (F_NumParam1 = {1}) AND (F_NumParam2 = {2}) AND (F_NumParam3 = {3})  order by F_MonitorIndex asc",ob)).Tables[0].DefaultView;
                            if (dvm.Count > 0)
                            {
                                dm = dbo.ExceSQL(string.Format("SELECT F_MonitorIndex,F_ManageTASKKINDINDEX, F_ManageTaskIndex FROM T_Monitor_Task where F_ManageTASKKINDINDEX={0} and  F_ManageTaskIndex={1} order by   F_MonitorIndex asc",Convert.ToInt32( dvm[0]["F_ManageTASKKINDINDEX"]),Convert.ToInt32( dvm[0]["F_ManageTASKINDEX"]))).Tables[0].DefaultView;
                                if (dm.Count > 0)
                                {
                                    if (dm[0]["F_MonitorIndex"].ToString() == dvm[0]["F_MonitorIndex"].ToString())
                                    {
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update T_Monitor_Task set F_MonitorTaskLevel=10 where F_ManageTASKKINDINDEX=").Append(dvm[0]["F_ManageTASKKINDINDEX"]).Append(" and F_ManageTaskIndex=").Append(dvm[0]["F_ManageTaskIndex"]);
                                        dbo.ExceSQL(sql.ToString());
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update T_Manage_Task set FTASKLEVEL=10 where F_ManageTASKKINDINDEX=").Append(dvm[0]["F_ManageTASKKINDINDEX"]).Append(" and FID=").Append(dvm[0]["F_ManageTaskIndex"]);
                                        dbo.ExceSQL(sql.ToString());
                                        return true;
                                    }
                                }
                            }

                        }
                        
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("报告完成时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rmea);
                return false;
            }
            finally
            {
                dv.Dispose();
                dvm.Dispose();
            }

        }

        private int  ControlBatchAlterSendPLC(string conbatch, int DeviceIdx)
        {//码垛批次号对应设备:DeviceIdx+“5”
            DataView dv = new DataView();
            int order = 0;
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32( DeviceIdx.ToString()+"5"));
                
                dv = dbo.ExceSQL(string.Format("SELECT F_BoxBarcode, F_HaveFirstProject FROM T_Base_PLC_Ask WHERE (F_DeviceIndex = {0})",devinfo.DeviceIndex)).Tables[0].DefaultView;
                if (dv.Count>0)
                {//F_BoxBarcode正在码垛的批号;F_HaveFirstProject上次给PLC写入的值1,2
                    if (dv[0]["F_BoxBarcode"].ToString() != conbatch)
                    {//批号不相同
                        //witemnames = new StringBuilder[1] { new StringBuilder("DB1,byte" + devinfo.Dbw1Address.ToString()) };
                        //wv = new StringBuilder[1] { new StringBuilder("2") };
                        if (dv[0]["F_HaveFirstProject"].ToString() == "1")
                        {//写入2
                            //wv[0].Clear();
                            //wv[0].Append("2");
                            order = 2;
                            //sdo = CommLayerFactory.CommModeCreate.CreateSendDeviceOrder(devinfo.DeviceIndex);
                            //if (sdo.WriteDBData(witemnames, wv) == true)
                            //{
                            //    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码垛批次号写入", DeviceIdx.ToString(), "批次:" + conbatch.ToString() + ",2");

                            dbo.ExceSQL(string.Format("update T_Base_PLC_Ask set F_BoxBarcode='{1}',F_HaveFirstProject = '2'  WHERE (F_DeviceIndex = {0})", devinfo.DeviceIndex, conbatch));
                            //}
                            //else
                            //{
                            //    RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成ControlBatchAlterSendPLC时:{0}", "码垛批次号写入失败!"));
                            //    OnRefreshMonitor(rme);
                            //}
                        }
                        else
                        {//写入1
                            //witemnames = new StringBuilder[1] { new StringBuilder("DB1,byte" + devinfo.Dbw1Address.ToString()) };
                            //wv = new StringBuilder[1] { new StringBuilder("1") };
                            //wv[0].Clear();
                            //wv[0].Append("1");
                            order = 1;
                            //sdo = CommLayerFactory.CommModeCreate.CreateSendDeviceOrder(devinfo.DeviceIndex);
                            //if (sdo.WriteDBData(witemnames, wv) == true)
                            //{
                            //    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码垛批次号写入", DeviceIdx.ToString(), "批次:" + conbatch.ToString() + ",1");

                            dbo.ExceSQL(string.Format("update T_Base_PLC_Ask set F_BoxBarcode='{1}',F_HaveFirstProject = '1'  WHERE (F_DeviceIndex = {0})", devinfo.DeviceIndex, conbatch));
                            //}
                            //else
                            //{
                            //    RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成ControlBatchAlterSendPLC时:{0}", "码垛批次号写入失败!"));
                            //    OnRefreshMonitor(rme);
                            //}
                        }
                    }
                    else
                    {//批号相同
                        //witemnames = new StringBuilder[1] { new StringBuilder("DB1,byte" + devinfo.Dbw1Address.ToString()) };
                        //wv = new StringBuilder[1] { new StringBuilder("1") };
                        //wv[0].Clear();
                        //wv[0].Append(dv[0]["F_HaveFirstProject"].ToString());
                        order = Convert.ToInt32(dv[0]["F_HaveFirstProject"]);
                        //sdo = CommLayerFactory.CommModeCreate.CreateSendDeviceOrder(devinfo.DeviceIndex);
                        //if (sdo.WriteDBData(witemnames, wv) == true)
                        //{
                        //    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码垛批次号写入", DeviceIdx.ToString(), "批次:" + conbatch.ToString() + ",1");

                            //dbo.ExceSQL(string.Format("update T_Base_PLC_Ask set F_BoxBarcode='{1}',F_HaveFirstProject = '1'  WHERE (F_DeviceIndex = {0})", devinfo.DeviceIndex, conbatch));
                        //}
                        //else
                        //{
                        //    RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成ControlBatchAlterSendPLC时:{0}", "码垛批次号写入失败!"));
                        //    OnRefreshMonitor(rme);
                        //}
                    }
                }
                else
                {
                    RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成ControlBatchAlterSendPLC时:{0}", "设备不存在!"));
                    OnRefreshMonitor(rme);
                   
                }
                return order;
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成ControlBatchAlterSendPLC时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rme);
                return 0;
            }
            finally
            {
                dv.Dispose();
            }
        }
        private void SendBarCodePLC(string barcode, int DeviceIdx)
        {//码垛口来料箱条码号对应设备:DeviceIdx+“6”
            DataView dv = new DataView();
            try
            {
                dbo.ExceSQL(string.Format("update T_Base_PLC_Ask set F_remark='{0}'   WHERE (F_DeviceIndex = {1})",barcode, DeviceIdx));
                //devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(DeviceIdx.ToString() + "6"));
                //witemnames = new StringBuilder[devinfo.Dbw1SendLength];
                //wv = new StringBuilder[devinfo.Dbw1SendLength];
                //byte[] bytebc = ASCIIEncoding.ASCII.GetBytes(barcode);
                //for (int i = 0; i < devinfo.Dbw1SendLength; i++)
                //{
                //    witemnames[i] = new StringBuilder("DB1,byte" + (devinfo.Dbw1Address + i).ToString());
                //    if (i < bytebc.Length)
                //    {
                //        wv[i] = new StringBuilder(bytebc[i].ToString());
                //    }
                //    else
                //    {
                //        wv[i] = new StringBuilder("0");
                //    }
                //}

                //sdo = CommLayerFactory.CommModeCreate.CreateSendDeviceOrder(devinfo.DeviceIndex);
                //sdo.WriteDBData(witemnames, wv);
                //CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码垛口到位料箱条码", DeviceIdx.ToString(), "条码:" + barcode.ToString());
                
                //return;


            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成IFSameStartDeviceControlBatchLastBox时:{0}", ex.StackTrace+ex.Message));
                OnRefreshMonitor(rme);
                return;
            }
            finally
            {
                dv.Dispose();
            }
        }
        private bool IFSameStartDeviceControlBatchLastBox(int mti, int fid,  int endconveyor)
        {
            DataView dv = new DataView();
            try
            {
                string startdev=string.Empty ,conbatch=string.Empty;
                dv = dbo.ExceSQL(string.Format("SELECT FSTARTDEVICE, FCONTORL_BATCH FROM T_Manage_Task WHERE (F_ManageTaskKindIndex ={0}) AND (FID = {1})",mti,fid)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    startdev = dv[0]["FSTARTDEVICE"].ToString();
                    conbatch = dv[0]["FCONTORL_BATCH"].ToString();
                }
                else
                {
                    return false;
                }
                dv = dbo.ExceSQL(string.Format("SELECT F_MonitorIndex FROM T_Manage_Task,T_Monitor_Task where T_Manage_Task.F_ManageTaskKindIndex = T_Monitor_Task.F_ManageTASKKINDINDEX AND FID = F_ManageTaskIndex and (FSTARTDEVICE = '{0}') AND (FCONTORL_BATCH = '{1}') AND (T_Monitor_Task.F_NumParam4 = {2})",startdev,conbatch,endconveyor)).Tables[0].DefaultView;
                if (dv.Count ==1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
                
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理报完成IFSameStartDeviceControlBatchLastBox时:{0}", ex.StackTrace+ex.Message ));
                OnRefreshMonitor(rme);
                return false;
            }
            finally
            {
                dv.Dispose();
            }
        }
        private bool GetTaskStatus(int taskindex)
        {//20120820
            DataView dv = new DataView();
            try
            { 
                dv = dbo.ExceSQL(string.Format("SELECT F_Status from  T_Monitor_Task  where F_MonitorIndex= {0} and  F_Status>0 ", taskindex)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return true;
                }
                else
                {
                    return  false;
                }
            }

            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("GetTaskStatus时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rmea);
                return false;
            }
            finally
            {
                dv.Dispose();
            }
        }
        private int GetLaneGateDevice(int stackDevice, string zxy)
        {//20120820
            DataView dv = new DataView();
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(stackDevice);
                if (devinfo.VirtualStack>0)
                {
                    stackDevice = devinfo.VirtualStack;
                }
                dv = dbo.ExceSQL(string.Format("SELECT T_Base_Lane_Gate.F_LaneGateDeviceIndex FROM T_Base_Lane_Gate ,T_Base_LaneInfo WHERE  T_Base_Lane_Gate.F_LaneIndex = T_Base_LaneInfo.F_LaneDeviceIndex And (T_Base_LaneInfo.F_StackIndex = {0}) AND (T_Base_Lane_Gate.F_ZXY = '{1}')", stackDevice, zxy)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0][0]);
                }
                else
                {
                    return -1;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        /// <summary>
        /// 处理由于多线程产生死锁的SQL语句
        /// </summary>
        public void ActionDeadLock()
        {//20100108
            DataView dv = new DataView();
            try
            {
                sql.Remove(0, sql.Length);
                sql.Append("select * from T_DeadLock where f_flag=0 order by f_id asc");
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                for (int i = 0; i < dv.Count; i++)
                {
                    try
                    {
                        dbo.ExceSQL(dv[i]["f_SQL"].ToString());
                        sql.Remove(0, sql.Length);
                        sql.Append("update T_DeadLock set f_flag=1 where f_id=" ).Append( dv[i]["f_id"] );
                        dbo.ExceSQL(sql.ToString());
                    }
                    catch
                    {
                        continue;
                    }
                }
            }//20100108
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        
        
        /// <summary>
        /// 回写设备错误状态字(IO_Control,T_Manage_Task,T_Monitor_task)
        /// </summary>
        /// <param name="DeviceIdx">设备索引</param>
        /// <param name="TaskIdx">设备指令索引</param>
        /// <param name="ErrId">错误编号</param>
        public void ActionError(int DeviceIdx, int TaskIdx,int ErrId)
        {
            //dbo.TransBegin();
            //20100108
            DataView dvmon = new DataView();
            DataTable dt = new DataTable();
            DataView dv0 = new DataView();
            DataView dvm = new DataView();
            DataView dvIO = new DataView();
            DataRowView dr = null ;
            

            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                int devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                CDataChangeEventArgs dcea = new CDataChangeEventArgs(null, null);
                //090915
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_MonitorIndex FROM T_Monitor_Task where  F_Status =1 and F_DeviceIndex =" ).Append( DeviceIdx);
                
                //20100108
                dvmon = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if ((dvmon.Count > 0) && (TaskIdx == 0))
                {
                    TaskIdx = Convert.ToInt32(dvmon[0]["F_MonitorIndex"]);
                }
                
                #region 有过记录的故障设备的任务号,不再重复处理
                
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_DeviceIndex FROM T_Base_Device where   F_DeviceIndex=").Append( DeviceIdx ).Append( " and F_ErrorTaskNo=" ).Append( TaskIdx ); 
               
                //20100108
                dt = dbo.ExceSQL(sql.ToString()).Tables[0];
                if (dt.Rows.Count >= 1)
                {
                    sql.Remove(0, sql.Length);
                    sql.Append("update T_Monitor_Task set F_Status= ").Append(ErrId).Append("  where (F_MonitorIndex= ").Append(TaskIdx).Append(") and ((F_Status<> ").Append(ErrId).Append(") and (F_Status<> 3 and F_Status>0))");//20121203
                    int errc=dbo.ExecuteSql(sql.ToString());
                    if (errc > 0)//20110603
                    {
                        
                        OnDataChange("ActionError",dcea);
                    }
                    int[] corrtaskindex=Model.CGeneralFunction.MutiForkIfSync(TaskIdx, DeviceIdx, devKind);
                    if ((corrtaskindex!=null ) && (CStaticClass.DeviceErrorAutoModifyRoutePath == "0"))
                    {//20120328
                        for (int i = 0; i < corrtaskindex.GetLength(0); i++)
                        {
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Monitor_Task set F_Status= ").Append(ErrId).Append("  where (F_MonitorIndex= ").Append(corrtaskindex[i]).Append(") and ((F_Status<> ").Append(ErrId).Append(") and (F_Status<> 3 and F_Status>0))");//20121203
                            dbo.ExecuteSql(sql.ToString());

                        }
                    }
                    return;
                }

                #endregion

                if (GetManage_Kind(TaskIdx) == false) return;
                int fid = _fid;
                int mti = _mti;
                if (fid <= 0) return;

                #region 通用故障处理
                string dtime = DateTime.Now.ToString("u");//20110603

                dtime = dtime.Substring(0, dtime.Length - 1);
                errs = Model.CGetInfo.GetErrorInfo(Convert.ToInt32(devKind.ToString() + ErrId.ToString()));
                if (errs != null)
                {
                    #region 20160501故障或报警数量增加1
                    if (errs.ErrorIndex != 999)
                    {
                        string errText = string.Empty;
                        if (errs.IfAlarm == '1')
                        {
                            CStaticClass.UpdateDeviceOEE(DeviceIdx, DateTime.Now.Date, 0, 0, 1,
                                0, 0, 0, 'O', 0, out errText);
                        }
                        else
                        {
                            CStaticClass.UpdateDeviceOEE(DeviceIdx, DateTime.Now.Date, 0, 1, 0,
                                0, 0, 0, 'O', 0, out errText);
                        }
                    }
                    #endregion
                    if (errs.ErrorIndex > 0)
                    {

                        RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("notifyIcon1", string.Format("警告:{0},{1},发生故障:{2}" , devinfo.DeviceName , DeviceIdx , errs.ErrorName));
                        OnRefreshMonitor(rmea);

                        if (mti == 1)
                        {
                            sql.Remove(0, sql.Length);
                            sql.Append("update IO_Control set ERROR_TEXT='").Append(devinfo.DeviceName).Append(",").Append(DeviceIdx).Append(errs.ErrorName).Append("' where CONTROL_ID=").Append(fid);
                            dboM.ExceSQL(sql.ToString());
                        }
                        //20170111放在线程里面出来故障记录
                        //20100108
                        sql.Remove(0, sql.Length);
                        sql.Append("SELECT F_DeviceIndex, F_ErrorIndex FROM T_Base_Device_Error_Log Where F_FixDateTime is null and  F_ManageTaskNo=").Append(fid).Append(" and F_DeviceIndex=").Append(DeviceIdx).Append(" and F_ErrorIndex=").Append(errs.ErrorIndex);
                        dv0 = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dv0.Count > 0)
                        {//20091107
                            //20190307
                            //sql.Remove(0, sql.Length);
                            //sql.Append("UPDATE T_Base_Device_Error_Log SET F_DateTime ='").Append(dtime).Append("'  Where F_DeviceIndex=").Append(DeviceIdx).Append(" and F_ErrorIndex=").Append(errs.ErrorIndex).Append(" and F_ManageTaskNo=").Append(fid);
                            //dbo.ExceSQL(sql.ToString());
                        }
                        else
                        {
                            sql.Remove(0, sql.Length);
                            sql.Append("INSERT INTO T_Base_Device_Error_Log (F_ManageTaskNo,F_DeviceIndex, F_ErrorIndex, F_DateTime) VALUES (").Append(fid).Append(",").Append(DeviceIdx).Append(",").Append(errs.ErrorIndex).Append(",'").Append(dtime).Append("')");
                            dbo.ExceSQL(sql.ToString());
                        }
                    }
                }


                sql.Remove(0, sql.Length);
                sql.Append("update T_Monitor_Task set F_Status= ").Append(ErrId).Append("  where F_MonitorIndex= ").Append(TaskIdx).Append(" and (F_Status<> 3 and F_Status>0)");//20121203
                dbo.ExceSQL(sql.ToString());
                //记录发生故障的设备正在执行的任务号
                sql.Remove(0, sql.Length);
                sql.Append("update T_Base_Device set F_ErrorTaskNo= " ).Append( TaskIdx ).Append( "  where F_DeviceIndex= " ).Append( DeviceIdx);
                dbo.ExceSQL(sql.ToString());
                sql.Remove(0, sql.Length);
                if (errs != null)
                {//20160501
                    sql.Append("update T_Manage_Task set FERRORCODE='").Append(devinfo.DeviceName).Append(",").Append(DeviceIdx).Append(errs.ErrorName).Append("' where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                }
                else
                {
                    sql.Append("update T_Manage_Task set FERRORCODE='").Append(devinfo.DeviceName).Append(",").Append(DeviceIdx).Append("故障:").Append(ErrId).Append("' where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                }
                dbo.ExceSQL(sql.ToString());

                #endregion
                
                if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                {//故障自动改道处理

                    #region 堆垛机异常处理(取空和送重)
                    if ((devKind == 1) && (mti == 1))//堆垛机
                    {
                        int[] mforkMoninfo=Model.CGeneralFunction.MutiForkIfSync(TaskIdx, DeviceIdx, devKind);
                        StringBuilder  rcontrolidstr=new StringBuilder();StringBuilder errusefork = new StringBuilder();
                        Model.MIOControlStatus mioc= Model.CGetInfo.GetIOControlStatus(ErrId);
                        if (mioc==null)
                        {
                            return;
                        }
                        if (devinfo.IfCorrelDoubleFork == "1")
                        {//多叉
                            char[] cc = new char[1] { ',' };
                            
                            string[] errforks = mioc.ForkNo.Split(cc);
                            for (int i = 0; i < errforks.GetLength(0); i++)
                            {
                                errusefork.Append(" FUseAwayFork='").Append(errforks[i]).Append("' or ");
                            }
                            errusefork.Remove(errusefork.Length - 3, 3);
                            int relcontrolid = ccf.GetRELATIVECONTORLIDFromManageTask(mti, fid);
                            rcontrolidstr.Clear();
                            if (relcontrolid > 0)
                            {//20130704
                                rcontrolidstr.Append(" F_RELATIVECONTORLID =  ").Append(relcontrolid);
                            }
                            else
                            {
                                rcontrolidstr.Append(" FID =  ").Append(fid);
                            }
                        }
                        else
                        {//单叉
                            errusefork.Clear();
                            errusefork.Append(" 1=1 ");
                            rcontrolidstr.Append(" FID =  ").Append(fid);
                        }
                        if (mioc.StatusCode.IndexOf("STACKEMPTYOUTPUT") >= 0)//堆垛机的出库取空处理
                        {
                            #region 堆垛机的取空处理,删除故障任务;异常完成980
                            int[] zxy = ccf.GetCoordinatesFromMonitorTask(TaskIdx);
                            StringBuilder zxystr = new StringBuilder();
                            if (zxy != null)
                            {
                                //堆垛机取货坐标
                                zxystr.Append((zxy[0].ToString().Length == 1 ? "0" + zxy[0].ToString() : zxy[0].ToString())).Append("-").Append(
                                    ((zxy[1].ToString().Length == 1) ? ("0" + zxy[1].ToString()) : (zxy[1].ToString()))).Append("-").Append(
                                    ((zxy[2].ToString().Length == 1) ? ("0" + zxy[2].ToString()) : (zxy[2].ToString())));
                            }
                            sql.Remove(0, sql.Length);
                            sql.Append("SELECT F_ZXY FROM T_Base_Lane_Gate WHERE (F_ZXY = '").Append(zxystr).Append("')");
                            dvIO = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            if (dvIO.Count > 0)
                            {//巷道的出入口输送机对应的货位不处理取空报警
                                return;
                            }
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                            sql.Remove(0, sql.Length);
                            sql.Append("SELECT FID FROM T_Manage_Task WHERE (").Append(rcontrolidstr.ToString()).Append(") AND (F_ManageTaskKindIndex = ").Append(mti).Append(") and (").Append(errusefork).Append(" )");
                            dvm = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            for (int m = 0; m < dvm.Count; m++)
                            {
                                fid = Convert.ToInt32(dvm[m]["FID"]);
                                //删除任务后报告异常完成980
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Monitor_Task set F_STATUS=-1 where F_ManageTaskKindIndex=").Append(mti).Append(" and F_ManageTaskIndex=").Append(fid).Append(" and F_STATUS=0");
                                dbo.ExceSQL(sql.ToString());
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Manage_Task set FExceptionNO=").Append(Model.CGeneralFunction.TASKEMPTYOUTPUT).Append(" where (F_ManageTaskKindIndex = ").Append(mti).Append(") AND (FID = ").Append(fid).Append(")");
                                dbo.ExceSQL(sql.ToString());
                                 
                                sql.Remove(0, sql.Length);
                                sql.Append("select * from T_Monitor_Task WHERE (F_ManageTaskIndex = ").Append(fid).Append(") AND (F_ManageTASKKINDINDEX =").Append(mti).Append(")");
                                dvIO = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                for (int i = 0; i < dvIO.Count; i++)
                                {
                                    ActionComplete(Convert.ToInt32(dvIO[i]["F_DeviceIndex"]), Convert.ToInt32(dvIO[i]["F_MonitorIndex"]), Model.CGeneralFunction.TASKDELETE);
                                    
                                }
                            }
                            #region 多叉关联的已经取货完成的任务报完成
                            if (mforkMoninfo != null && devinfo.IfCorrelDoubleFork == "1")
                            {
                                foreach (int rtask in mforkMoninfo)
                                {
                                    ActionComplete(DeviceIdx, rtask, 1);
                                }
                            }
                            #endregion
                            #endregion
                        }
                        else if (mioc.StatusCode.IndexOf("STACKREPEATINPUT") >= 0)//堆垛机的入库送货重
                        {
                            #region 堆垛机的送货重,需要改路径处理;异常完成970
                            
                            #region 自动在库内更换新货位

                            //#region 堆垛机的送货重需要改路径处理
                            ////20091107
                            ////20100108
                            //dvIO = dboM.ExceSQL("select CONTROL_ID, CONTROL_STATUS from IO_Control where (CONTROL_ID = " + fid + ") AND ((CONTROL_STATUS=" + Model.CGeneralFunction.TASKREPEATINPUT + ") or (CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEREPLY + "))").Tables[0].DefaultView;
                            //if (dvIO.Count <= 0)
                            //{
                            //    //向管理申请修改任务
                            //    //20100108
                            //    dvm = dbo.ExceSQL("select * from T_Manage_Task WHERE (FID = " + fid + ") AND (F_ManageTASKKINDINDEX =" + mti + ")").Tables[0].DefaultView;
                            //    if (dvm.Count > 0)
                            //    {
                            //        fwarehouse = dvm[0]["FWAREHOUSE"].ToString();
                            //        flane = Convert.ToInt32(dvm[0]["FLANEWAY"]);
                            //        fcode = dvm[0]["FENDCELL"].ToString();
                            //        if (ccf.QueryCellIfExit(fwarehouse, flane, fcode) == true)
                            //        {
                            //            //20091128
                            //            //20100108
                            //            dr = dvm[0];
                            //            //20100108
                            //            //DV = dboM.ExceSQL("select IO_CONTROL_APPLY_SEQ.NEXTVAL FROM DUAL").Tables[0].DefaultView;
                            //            int id = dboM.GetManageTableIndex("IO_CONTROL_APPLY");

                            //            string dtime = DateTime.Now.ToString("u");
                            //            dtime = dtime.Substring(0, dtime.Length - 1);
                            //            dboM.TransBegin();
                            //            try
                            //            {

                            //                if (CStaticClass.ManDBFactory == "OracleDBFactory")
                            //                {

                            //                    dboM.ExceSQL("update IO_Control set CONTROL_STATUS=" + Model.CGeneralFunction.TASKREPEATINPUT + ",ERROR_TEXT='" + DeviceIdx + errs.ErrorName + ";原货位:" + "'||END_DEVICE_CODE where CONTROL_ID=" + fid);
                            //                }
                            //                else
                            //                {
                            //                    dboM.ExceSQL("update IO_Control set CONTROL_STATUS=" + Model.CGeneralFunction.TASKREPEATINPUT + ",ERROR_TEXT='" + DeviceIdx + errs.ErrorName + ";原货位:" + "'+END_DEVICE_CODE where CONTROL_ID=" + fid);
                            //                }
                            //                string sql = "INSERT INTO IO_CONTROL_APPLY (CONTROL_APPLY_ID, CONTROL_ID,CONTROL_APPLY_TYPE, WAREHOUSE_CODE, STOCK_BARCODE, DEVICE_CODE,APPLY_TASK_STATUS, FCREATETIME, FREMARK)" +
                            //                "VALUES (" + id + "," + dr["FID"] + ",2,'" + dr["FENDWAREHOUSE"] + "','" + dr["FPALLETBARCODE"] + "','" + dr["FENDDEVICE"] + "',0,'" + dtime + "',null)";
                            //                dboM.ExceSQL(sql);
                            //                dboM.TransCommit();

                            //                dbo.ExceSQL("update T_Manage_Task set FExceptionNO=" + Model.CGeneralFunction.TASKREPEATINPUT + ",FERRORCODE='" + DeviceIdx + errs.ErrorName + ";原货位:" + "'+ FENDCELL where (F_ManageTaskKindIndex = " + mti + ") AND (FID = " + fid + ")");
                            //                //把ManageTaskIdx,ManageKindIdx 的调度任务全部申请改道
                            //                dbo.ExceSQL("UPDATE T_Monitor_Task SET  F_Status = 3 WHERE (F_ManageTaskIndex = " + fid + ") AND (F_ManageTASKKINDINDEX =" + mti + ")");



                            //            }
                            //            catch (Exception ex)
                            //            {
                            //                _CGetStateError = "堆垛机送货时发生送重故障,改道时:" + ex.Message;
                            //                dboM.TransRollback();
                            //            }
                            //        }
                            //    }
                            //}//20091107
                            //#endregion

                            #endregion

                            #region 送出到人工处理口
                            //先清零,删除故障任务,解除lockstate,然后直接改道出口
                            System.Threading.Thread.Sleep(3000);
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                            //20100710
                            int[] zxy = ccf.GetCoordinatesFromMonitorTask(TaskIdx);
                            StringBuilder zxystr = new StringBuilder();
                            if (zxy != null)
                            {
                                //堆垛机送货坐标
                                zxystr.Append((zxy[3].ToString().Length == 1 ? "0" + zxy[3].ToString() : zxy[3].ToString())).Append("-").Append(
                                    ((zxy[4].ToString().Length == 1) ? ("0" + zxy[4].ToString()) : (zxy[4].ToString()))).Append("-").Append(
                                    ((zxy[5].ToString().Length == 1) ? ("0" + zxy[5].ToString()) : (zxy[5].ToString())));
                            }
                            sql.Remove(0, sql.Length);
                            sql.Append("SELECT F_ZXY FROM T_Base_Lane_Gate WHERE (F_ZXY = '").Append(zxystr.ToString()).Append("')");
                            dvIO = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            if (dvIO.Count > 0)
                            {//巷道的出入口输送机对应的货位不处理送空报警
                                return;
                            }
                            sql.Clear();
                            sql.Append("SELECT FID FROM T_Manage_Task WHERE (").Append(rcontrolidstr.ToString()).Append(") AND (F_ManageTaskKindIndex = ").Append(mti).Append(") and (").Append(errusefork).Append(" )");
                            dvm = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                            for (int m = 0; m < dvm.Count; m++)
                            {
                                fid = Convert.ToInt32(dvm[m]["FID"]);
                                //堆垛机的送货重,只保留堆垛机的送货任务
                                //是应急站台,把原来的终点改为起点改道至应急站台
                                int enddevice = devinfo.StackAbendOut;
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Manage_Task set FCONTROLTASKTYPE=2,FSTARTDEVICE=FENDDEVICE,FSTARTCELL=FENDCELL,FENDDEVICE=").Append(enddevice
                                    ).Append(",FENDCELL='-',FExceptionNO=").Append(Model.CGeneralFunction.TASKREPEATINPUT).Append(" where (FID = ").Append(fid).Append(") AND (F_ManageTASKKINDINDEX =").Append(mti).Append(")");
                                dbo.ExceSQL(sql.ToString());
                                sql.Remove(0, sql.Length);
                                sql.Append("select FSTARTDEVICE from T_Manage_Task where (FID = ").Append(fid).Append(") AND (F_ManageTASKKINDINDEX =").Append(mti).Append(")");
                                int sdevice = Convert.ToInt32(dbo.GetSingle(sql.ToString()));
                                sql.Remove(0, sql.Length);
                                sql.Append("select FENDDEVICE from T_Manage_Task where (FID = ").Append(fid).Append(") AND (F_ManageTASKKINDINDEX =").Append(mti).Append(")");
                                int edevice = Convert.ToInt32(dbo.GetSingle(sql.ToString()));

                                int routeidNew = CDisassembleTask.MinRouteID(sdevice, edevice, true, dvm);//20110331
                                if (routeidNew == -1) return;
                                sql.Remove(0, sql.Length);
                                sql.Append("DELETE FROM T_Monitor_Task WHERE (F_ManageTaskIndex = ").Append(fid).Append(") AND (F_ManageTASKKINDINDEX =").Append(mti).Append(")");
                                dbo.ExceSQL(sql.ToString());
                                sql.Remove(0, sql.Length);
                                sql.Append("select * from T_Manage_Task where (FID = ").Append(fid).Append(") AND (F_ManageTASKKINDINDEX =").Append(mti).Append(")");
                                dvIO = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                if (dvIO.Count > 0)
                                {
                                    dr = dvIO[0];
                                }
                                else
                                {
                                    return;
                                }
                                CDisassembleTask.CreateMonitor(mti, fid, routeidNew, dr, 3);
                                sql.Remove(0, sql.Length);
                                sql.Append("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = ").Append(fid
                                    ).Append(") AND (F_ManageTASKKINDINDEX = ").Append(mti).Append(") AND (F_DeviceIndex = ").Append(
                                        DeviceIdx).Append(") AND (F_DeviceCommandIndex = 5) AND (F_RouteID = ").Append(routeidNew).Append(
                                        ") AND (F_Status = 3)");
                                dvIO = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                if (dvIO.Count > 0)
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("delete from T_Monitor_Task where F_MonitorIndex<").Append(dvIO[0]["F_MonitorIndex"]).Append(" and (F_ManageTaskIndex = ").Append(
                                        fid).Append(") AND (F_ManageTASKKINDINDEX = ").Append(mti).Append(") AND (F_Status = 3)");
                                    dbo.ExceSQL(sql.ToString());
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=").Append(DeviceIdx);
                                    dbo.ExceSQL(sql.ToString());
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = ").Append(
                                    fid).Append(") AND (F_ManageTASKKINDINDEX = ").Append(mti).Append(") AND (F_Status = 3)");
                                    dbo.ExceSQL(sql.ToString());
                                }
                            }
                            #region 多叉关联的已发送的送货任务需要重新发送
                            if (mforkMoninfo != null && devinfo.IfCorrelDoubleFork == "1")
                            {
                                foreach (int rtask in mforkMoninfo)
                                {
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=").Append(DeviceIdx);
                                    dbo.ExceSQL(sql.ToString());
                                    sql.Remove(0, sql.Length);
                                    sql.Append("update  T_Monitor_Task set F_Status =0 where F_MonitorIndex=").Append(rtask);
                                    dbo.ExceSQL(sql.ToString());
                                }
                            }
                            #endregion
                            #endregion
                        

                            #endregion

                        }
                        
                        


                        

                    }
                    #endregion

                    #region 高端条码扫描不正确报警需要改道至异常口
                    if ((devKind == 13 || devKind == 31)&&(ErrId==41))//40条码未读到;41条码不正确
                    {
                        int abenddevice = 0, startdev = 40100, startucode =ccf.GetUCodeFromDeviceGD(DeviceIdx);
                        if (startucode > 40100)
                        {
                            abenddevice = 42037;
                            startdev = 40100;
                        }
                        else
                        {
                            abenddevice = 32025;
                            if (startucode <= 30107)
                            {
                                startdev = 30100;
                            }
                            else
                            {
                                startdev = 30200;
                            }
                        }
                        //比对错误,改道异常处理口
                        //修改目标位置至异常口
                        object[] obj = new object[7] { mti, fid, abenddevice, Model.CGeneralFunction.TASKABEND ,startdev,startucode,DeviceIdx };
                        dbo.ExecuteSql(string.Format("UPDATE T_Manage_Task SET FExceptionNO={3},FStartDEVICE ={4},FSTARTUCODE={5}, FStartCELL ='{6}',FENDDEVICE ={2}, FENDCELL ='-',  FENDUCODE =0 WHERE (F_ManageTaskKindIndex ={0}) AND (FID ={1})", obj));
                        ccf.GetUseableRouteIDSubAndModifyRoute(fid, mti, startdev);
                        
                    }
                    #endregion
                }

                if (devinfo.UseCommonDB == "1")
                {
                    return;
                }
                
                OnDataChange("ActionError",dcea);

            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                RefreshMonitorEventArgs rme = new RefreshMonitorEventArgs("tsStatus", string.Format("向管理反馈设备错误时:{0}" ,ex.StackTrace+ex.Message ));
                OnRefreshMonitor(rme);
                
            }
            finally
            {//20100108
                dvmon.Dispose();
                dt.Dispose(); ;
                dv0.Dispose();
                dvm.Dispose();
                dvIO.Dispose();
                dr=null ;
                
            }

        }
        
        /// <summary>
        /// 设备开始运行:
        /// 1-根据任务号和探物情况判断任务执行的位置回写本地管理表
        /// 2-回写调度任务表的开始执行状态
        /// 3-判断是否存在提前触发任务
        /// 
        /// </summary>
        /// <param name="DeviceIdx">设备索引</param>
        /// <param name="TaskIdx">调度任务号</param>
        public void ActionStartRun(int DeviceIdx, int TaskIdx)
        {
           

            if (TaskIdx <= 0)
            {
                
                return;
            }
            
            
            int fid = ccf.GetManageTaskIndexfromMonitor(TaskIdx);
            int mti = ccf.GetManageTaskKindIndexFromMonitor(TaskIdx);
            //dbo.TransBegin();
            if (fid <= 0) return;
            DataView dvlane = new DataView();
            DataView dv = new DataView();
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                int devKind = ccf.GetDeviceKindIdx(DeviceIdx);

                if (mti == 1)
                {//20100714
                    int updatestatus = Model.CGeneralFunction.TASKRUN;
                    if (devKind==1)
                    {
                        updatestatus = 11;
                    }
                    sql.Remove(0, sql.Length);
                    sql.Append("update IO_CONTROL set CONTROL_STATUS=").Append(updatestatus).Append(" where CONTROL_STATUS <> ").Append(updatestatus).Append(" and CONTROL_ID=").Append(fid);
                    dboM.ExecuteSql(sql.ToString());
                }
                #region 修改调度任务状态20101124
                sql.Remove(0, sql.Length);
                sql.Append("update T_Monitor_Task set F_ErrorCode='', F_Status=2 where   F_MonitorIndex=" + TaskIdx);//20110505
                //20110405
                int urow=dbo.ExecuteSql(sql.ToString());
                if (urow > 0)
                {
                    //devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                    //int devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                    int order = ccf.GetDeviceOrderFromMonitor(TaskIdx);
                    if (devKind == 4)//(((devKind == 2) && (devinfo.IfClearDB1 == "1")) )//20121203|| (devKind == 4)
                    {//输送机、RGV DB1清零
                        int[] sendmes = new int[5] { 0, 0, 0, DeviceIdx, 0 };
                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        if (CStaticClass.IsEquals(devinfo.SendMessage, sendmes, 5) == false)
                        {
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(0, 0, 0, DeviceIdx, 0);

                        }
                    }
                    else if ((devKind == 1)) //堆垛机
                    {
                        int[] sendmes = new int[10] { 0, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0 };
                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        if (CStaticClass.IsEquals(devinfo.SendMessage, sendmes, 10) == false)
                        {
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(0, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                        }
                    }
                    
                    CDataChangeEventArgs cea = new CDataChangeEventArgs(null, null);
                    OnDataChange("ActionStartRun",cea);
                #endregion
                    
                    
                    
                }//20110405
                

                #region 根据任务号和探物情况判断任务执行的位置回写本地管理表


                sql.Remove(0, sql.Length);
                sql.Append("update T_Manage_Task set FCurrentLocation=" ).Append(
                    DeviceIdx ).Append( " where F_ManageTaskKindIndex=" ).Append( mti ).Append( " and FID=" ).Append( fid);
                dbo.ExceSQL( sql.ToString());
                //调度任务表也记录当前位置,主要是给输送机链用
                sql.Remove(0, sql.Length);
                sql.Append("update T_Monitor_Task set F_CurrentLocation=" ).Append(
                    DeviceIdx ).Append( " where F_MonitorIndex=" ).Append( TaskIdx);
                dbo.ExceSQL(sql.ToString());
                //20120518设备逻辑有物

                //20090918给堆垛机送货的输送机逻辑有物解锁F_HaveGoods=0
                //20100108
                //sql.Remove(0, sql.Length);
                //sql.Append("SELECT F_LaneGateDeviceIndex  FROM T_Base_Lane_Gate where F_LaneGateDeviceIndex like '" ).Append( DeviceIdx).Append("%'");
                //dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                //if (dvlane.Count > 0)
                //{
                    sql.Remove(0, sql.Length);
                    sql.Append("update T_Base_Device set F_HaveGoods=0  where F_HaveGoods=").Append(TaskIdx);
                    dbo.ExceSQL(sql.ToString());
                //}
                //else
                //{//20100710
                    sql.Remove(0, sql.Length);
                    sql.Append("SELECT F_AGVGateDeviceIndex  FROM T_Base_AGV_Gate where F_AGVGateDeviceIndex=").Append(DeviceIdx);
                    dvlane = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                    if (dvlane.Count > 0)
                    {
                        sql.Remove(0, sql.Length);
                        sql.Append("update T_Base_Device set F_HaveGoods=0  where F_HaveGoods=").Append(TaskIdx);
                        dbo.ExceSQL(sql.ToString());
                    }
                //}

                #endregion
                //dbo.TransCommit();
                //RefreshControlMonitor(DeviceIdx);
                //20091107
                if (CStaticClass.MovedDeviceAheadTrigger == "1")
                {
                    #region 判断是否存在提前触发任务(设备号-调度任务号)
                    //当设备运行时,触发调度任务号运行F_AheadTrigger
                    //20100108
                    sql.Remove(0, sql.Length);
                    sql.Append("select F_AheadTrigger from T_Monitor_Task " ).Append(
                        "where F_MonitorIndex=" ).Append( TaskIdx ).Append( " and F_AheadTrigger like '" ).Append( DeviceIdx.ToString() ).Append( "-" ).Append( "%'");
                    dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {
                        //发送提前触发的命令调度任务
                        char[] cc = new char[1] { '-' };
                        string[] sp = dv[0]["F_AheadTrigger"].ToString().Split(cc);
                        if (sp.GetLength(0) > 0)
                        {
                            int TriTask = Convert.ToInt32(sp[1]);
                            if (ccl.SendMonitorTask(TriTask) == true)
                            {
                                //清除触发命令
                                sql.Remove(0, sql.Length);
                                sql.Append("update T_Monitor_Task set F_AheadTrigger ='' where F_MonitorIndex=" ).Append( TaskIdx);
                                dbo.ExceSQL(sql.ToString());
                            }

                        }

                    }
                    #endregion
                }
                ////20161224
                //if (DeviceIdx == 22012 || DeviceIdx == 22030)
                //{
                //    int enddevice = ccf.GetEndTransDeviceWithTaskIndex(DeviceIdx, TaskIdx);
                //    if (enddevice>0)
                //    {
                //        ActionComplete(DeviceIdx, TaskIdx, 0);
                //    }

                //}
 

                
            }
            catch (Exception ex)
            {
                CGetStateError = string.Format("ControlSystem.CGetState.报告执行时发生错误:{0}" , ex.StackTrace+ex.Message );
                
            }
            finally
            {//20100108
                
                dvlane.Dispose(); 
                dv.Dispose(); 
            }
        }
        public bool GetManage_Kind(int taskidx)
        {//20100108
            DataSet ds = new DataSet();
            try
            {
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_ManageTaskIndex, F_ManageTaskKindIndex, F_MonitorIndex FROM T_Monitor_Task Where F_MonitorIndex=" ).Append( taskidx);
                ds = dbo.ExceSQL(sql.ToString());
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    _fid = Convert.ToInt32(ds.Tables[0].DefaultView[0]["F_ManageTaskIndex"]);
                    _mti = Convert.ToInt32(ds.Tables[0].DefaultView[0]["F_ManageTaskKindIndex"]);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {//20100108
                ds.Dispose();
            }
        }





        public void ReturnManageInfo(int fid, int mti, string cap, bool IFOK)
        {
            string dtime = DateTime.Now.ToString("u");//20101028
            dtime = dtime.Substring(0, dtime.Length - 1);//20101028
            char[] cc = new char[1] { '-' };
            string[] fcc;
            DataView dv = new DataView();
            try
            {
                //200906240111增加货位记录:入库1-结束位置有货;出库2-起始位置无货;倒库3-起始位置无货,结束位置有货
                //20100108
                sql.Remove(0, sql.Length);
                sql.Append("SELECT * FROM T_Manage_Task where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (IFOK == true)
                    {

                        switch (dv[0]["FCONTROLTASKTYPE"].ToString())
                        {
                            case "1":
                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET FRUNSTATUS=0,FCELLSTATUS = 1,FPALLETBARCODE='").Append(dv[0]["FPALLETBARCODE"]).Append("' WHERE (FLaneWay=").Append(dv[0]["FENDDEVICE"]).Append(" and F_Z='").Append(
                                    fcc[0]).Append("' and F_X='").Append(fcc[1]).Append("' and F_Y='").Append(fcc[2]).Append("')");
                                    dbo.ExceSQL(sql.ToString());
                                }
                                break;
                            case "2":

                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET FRUNSTATUS=0,FCELLSTATUS =0,FPALLETBARCODE='-' WHERE (FLaneWay=").Append(dv[0]["FSTARTDEVICE"]).Append("  and F_Z=").Append(
                                    fcc[0]).Append(" and F_X=").Append(fcc[1]).Append(" and F_Y=").Append(fcc[2]).Append(")");
                                    dbo.ExceSQL(sql.ToString());
                                }

                                break;
                            case "3":

                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);//FRUNSTATUS=0,
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET  FRUNSTATUS=0,FCELLSTATUS = 1,FPALLETBARCODE='").Append(dv[0]["FPALLETBARCODE"]).Append("'  WHERE (FLaneWay=").Append(dv[0]["FENDDEVICE"]).Append(" and F_Z=").Append(
                                    fcc[0]).Append(" and F_X=").Append(fcc[1]).Append(" and F_Y=").Append(fcc[2]).Append(")");
                                    dbo.ExceSQL(sql.ToString());
                                }
                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);//20160418 FRUNSTATUS=0,
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET  FRUNSTATUS=0,FCELLSTATUS =0,FPALLETBARCODE='-'  WHERE (FLaneWay=").Append(dv[0]["FSTARTDEVICE"]).Append("  and F_Z=").Append(
                                    fcc[0]).Append(" and F_X=").Append(fcc[1]).Append(" and F_Y=").Append(fcc[2]).Append(")");
                                    dbo.ExceSQL(sql.ToString());
                                }


                                break;
                            default:
                                break;
                        }

                        if (CStaticClass.StopTestLane == false && dv[0]["F_ManageTaskKindIndex"].ToString() != "1")
                        {
                            #region 测试时把入库任务完成时生成出库任务
                            if (dv[0]["FCONTROLTASKTYPE"].ToString() == "1" && CStaticClass.TestOutEnd == false)
                            {
                                int startdevice = Convert.ToInt32(dv[0]["FSTARTDEVICE"]);
                                if (startdevice == 1202 || startdevice == 1205)//生成出库任务
                                {

                                    int Laneindex = Convert.ToInt32(dv[0]["FLANEWAY"]);
                                    int enddevice = startdevice-1;//出库到入库口
                                    string CellCode = CStaticClass.SelectGoodsCell(Laneindex, enddevice);
                                    if (CellCode != "-")
                                    {
                                        string stack = dv[0]["FSTACK"].ToString();//堆垛机FSTACK
                                        string barcode = CStaticClass.GetCellBarCode(CellCode, Laneindex);//托盘条码

                                        int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                        //int ifrevolve = 0;// ccf.GetIFRevolve(startdevice, string.Empty, enddevice, string.Empty);

                                        //int boxtype = 1;

                                        string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer,FLOGIC_AREA) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15},'{16}')", AutoManageIdx, barcode, 2, 2, 1, Laneindex, CellCode, 1, enddevice, "-", Laneindex, stack, "0", dtime, 0, 0, enddevice);

                                        dbo.ExceSQL(sqlstr);
                                    }


                                }
                                //else
                                //    if (startdevice == 13205)//生成出库任务
                                //    {

                                //        int Laneindex = Convert.ToInt32(dv[0]["FLANEWAY"]);
                                //        int enddevice = 23207;//出库到入库口
                                //        string CellCode = CStaticClass.SelectGoodsCell(Laneindex, enddevice);
                                //        if (CellCode != "-")
                                //        {

                                //            string stack = dv[0]["FSTACK"].ToString();//堆垛机FSTACK
                                //            string barcode = CStaticClass.GetCellBarCode(CellCode, Laneindex);//托盘条码

                                //            int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                //            int ifrevolve = 0;// ccf.GetIFRevolve(startdevice, string.Empty, enddevice, string.Empty);

                                //            int boxtype = 2;

                                //            string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer,FLOGIC_AREA,BOX_TYPE,IFRevolve) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15},'{16}',{17},{18})", AutoManageIdx, barcode, 2, 2, 1, Laneindex, CellCode, 1, enddevice, "-", Laneindex, stack, "0", dtime, 0, 0, enddevice, boxtype, ifrevolve);

                                //            dbo.ExceSQL(sqlstr);
                                //        }

                                //    }

                            }
                            #endregion
                            //#region 测试时把移库任务完成时生成入库任务
                            //if (dv[0]["FCONTROLTASKTYPE"].ToString() == "2" && CStaticClass.TestInEnd == false)
                            //{

                            //    int enddevice;
                            //    int startdevice = Convert.ToInt32(dv[0]["FENDDEVICE"]);


                            //    if (startdevice >= 12007 && startdevice <= 12013)//生成出库任务
                            //    {
                            //        string CellCode = ccf.GetAvailableCellCode(startdevice, "18"); //CStaticClass.SelectEmptyCell(Laneindex);
                            //        if (CellCode != "-")
                            //        {
                            //            string dtimes = DateTime.Now.ToString("u");//20101028
                            //            dtimes = dtimes.Substring(0, dtimes.Length - 1);//20101028
                            //            int Laneindex = ccf.GetLanewayFromCellCode(CellCode, 1);
                            //            if (Laneindex != -1)
                            //            {
                            //                enddevice = Laneindex;
                            //                int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                            //                string stack = "0";//堆垛机FSTACK

                            //                string barcodes = CStaticClass.GetCellBarCode(CellCode, Laneindex);//托盘条码

                            //                int ifrevolve = 0;// ccf.GetIFRevolve(startdevice, string.Empty, enddevice, string.Empty);
                            //                int controltype = 1;//入库
                            //                int boxtype = 2;
                            //                string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15})", AutoManageIdx, barcodes, controltype, 2, 1, startdevice, "-", 1, enddevice, CellCode, Laneindex, stack, "-", dtimes, 0, 0);

                            //                dbo.ExceSQL(sqlstr);
                            //                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "自动生成入库任务", startdevice.ToString(), AutoManageIdx.ToString());

                            //            }

                            //        }

                            //    }

                            //}
                            //#endregion
                            #region RGV测试

                            string strEndDevice = dv[0]["FSTARTDEVICE"].ToString();
                            int iTemp = strEndDevice.IndexOf("12");


                            if ((CStaticClass.TestInEnd == false)&&(iTemp != -1))
                            {
                                #region 获得新的任务起点和终点
                                int lastenddevice = Convert.ToInt32(dv[0]["FSTARTDEVICE"]);
                                int enddevice = 0;
                                int startdevice = Convert.ToInt32(dv[0]["FENDDEVICE"]);
                                switch (lastenddevice)
                                {
                                    case 12001:
                                        enddevice = 12003;
                                        break;
                                    case 12003:
                                        enddevice = 12001;
                                        break;
                                    case 12004:
                                        enddevice = 12005;
                                        break;
                                    case 12005:
                                        enddevice = 12006;
                                        break;
                                    case 12006:
                                        enddevice = 12007;
                                        break;
                                    case 12007:
                                        enddevice = 12004;
                                        break;

                                }

                                #endregion
                                if (enddevice != 0)
                                {
                                    string dtimes = DateTime.Now.ToString("u");//20101028
                                    dtimes = dtimes.Substring(0, dtimes.Length - 1);//20101028

                                    int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                    string stack = "0";//堆垛机FSTACK

                                    string barcodes = AutoManageIdx.ToString();//托盘条码

                                    int controltype = 3;//移库
                                    string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15})", AutoManageIdx, barcodes, controltype, 2, 1, startdevice, "-", 1, enddevice, "-", 0, stack, "-", dtimes, 0, 0);

                                    dbo.ExceSQL(sqlstr);
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "自动生成RGV移库任务:" + AutoManageIdx.ToString(), startdevice.ToString(), enddevice.ToString());


                                }

                            }
                            #endregion
                        }
                        //货位测试
                        #region 货位测试 20150126
                        int Lane = Convert.ToInt32(dv[0]["FLANEWAY"]);

                        if (CStaticClass.StopTest.ContainsKey(Lane) == true && !CStaticClass.StopTest[Lane] && dv[0]["F_ManageTaskKindIndex"].ToString() != "1")//测试
                        {
                            int startdevice;
                            int enddevice;
                            string dtimes = DateTime.Now.ToString("u");//20101028
                            dtimes = dtimes.Substring(0, dtimes.Length - 1);//20101028
                            //出库后生成移库任务,要找到移库任务的终点
                            //if (dv[0]["FCONTROLTASKTYPE"].ToString() == "2")
                            //{
                            //    startdevice = Convert.ToInt32(dv[0]["FENDDEVICE"]);
                            //    enddevice = ccf.GetLaneGate(startdevice, Lane);



                            //    int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                            //    string stack = "0";//堆垛机FSTACK

                            //    string barcodes = AutoManageIdx.ToString();//托盘条码

                            //    int ifrevolve = 2;
                            //    int controltype = 3;//移库

                            //    int boxtype = Convert.ToInt32(dv[0]["BOX_TYPE"]);

                            //    string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer,BOX_TYPE,IFRevolve) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15},{16},{17})", AutoManageIdx, barcodes, controltype, 2, 1, startdevice, "-", 1, enddevice, "-", Lane, stack, "-", dtimes, 0, 0, boxtype, ifrevolve);

                            //    dbo.ExceSQL(sqlstr);
                            //    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "自动生成移库任务:" + AutoManageIdx.ToString(), startdevice.ToString(), enddevice.ToString());


                            //}
                            //else
                            if (dv[0]["FCONTROLTASKTYPE"].ToString() == "2" &&  CStaticClass.StopIn[Lane] == false)// 3移库后生成入库任务
                                {
                                  
                                   startdevice = Convert.ToInt32(dv[0]["FENDDEVICE"]);
                                   if (startdevice == 12001 || startdevice == 12009)
                                {
                                   if (CStaticClass.ContainAGV)
                                   {
                                       int sLaneindex = 18003;
                                       int eLaneindex = 18003;
                                           enddevice = 18003;
                                        if (startdevice == 12009)//出库完成后生成移库任务   18003/12009 - 12002/-
                                        {
                                            sLaneindex = 18003;
                                            eLaneindex = 12002;
                                            enddevice = 0;
                                        }
                                        else
                                            if (startdevice == 12001)//出库完成后生成移库任务  18003/12001 - 18003/12008
                                        {
                                            sLaneindex = 18003;
                                            eLaneindex = 18003;

                                            enddevice = 12008;
                                        }
                                            int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                            string stack = "0";//堆垛机FSTACK

                                            string barcodes = AutoManageIdx.ToString();//托盘条码

                                            int controltype = 3;//移库

                                            string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15})", AutoManageIdx, barcodes, controltype, 2, 1, sLaneindex, startdevice, 1, eLaneindex, enddevice, Lane, stack, "-", dtimes, 0, 0);

                                            dbo.ExceSQL(sqlstr);
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "自动生成AGV移库任务", startdevice.ToString(), AutoManageIdx.ToString());

                                        
                                    }
                                }
                                   else

                                    if (startdevice==22116)
                                   {
                                    string CellCode;
                                    if (CStaticClass.TestKind == 1)
                                    {
                                        CellCode = ccf.GetAvailableCellCode(startdevice, "18");
                                    }
                                    else
                                    { 
                                        CellCode = ccf.GetNextCell(startdevice, Lane, 1);
                                    }

                                    if (CellCode != "-")
                                    {


                                        enddevice = Lane;
                                        int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                        string stack = "0";//堆垛机FSTACK

                                        string barcodes = AutoManageIdx.ToString();//托盘条码

                                        int ifrevolve = 2;
                                        int controltype = 1;//入库
                                        //int boxtype = 2;
                                        string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15})", AutoManageIdx, barcodes, controltype, 2, 1, startdevice, "-", 1, enddevice, CellCode, Lane, stack, "-", dtimes, 0, 0);

                                        dbo.ExceSQL(sqlstr);
                                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "自动生成入库任务:" + AutoManageIdx.ToString(), startdevice.ToString(), enddevice.ToString() + ":" + CellCode);


                                    }
                                   }

                                }
                                else
                                    if (dv[0]["FCONTROLTASKTYPE"].ToString() == "1"&&CStaticClass.StopOut[Lane]==false)//入库后生成出库任务
                                    {
                                        enddevice = Convert.ToInt32(dv[0]["FSTARTDEVICE"]);// Convert.ToInt32(WcfControlMonitorLib.CStaticClass.TestEndDevice[Lane]);
                                        if (enddevice==0)
                                        {
                                        string CellCode = CStaticClass.SelectGoodsCell(Lane, enddevice);
                                        //string CellCode = Convert.ToString(dv[0]["FENDCELL"]); 
                                            if (CellCode != "-")
                                            {




                                                if (enddevice == 22134)
                                                {
                                                    enddevice = 22116;

                                                }

                                                if (enddevice == 12002)
                                                {
                                                    enddevice = 12001;

                                                }
                                                if (enddevice == 12008)
                                                {
                                                    enddevice = 12009;

                                                }
                                                startdevice = Lane;
                                                int AutoManageIdx = ccf.GetTempManageIdx(); //调度任务索引
                                                //string stack = "0";//堆垛机FSTACK
                                                string stack = dv[0]["FSTACK"].ToString(); //堆垛机FSTACK
                                                string barcodes = AutoManageIdx.ToString(); //托盘条码

                                                //int ifrevolve = 2;
                                                int controltype = 2; //入库
                                                //int boxtype = Convert.ToInt32(dv[0]["BOX_TYPE"]);
                                                string sqlstr =
                                                    string.Format(
                                                        "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer,FLOGIC_AREA) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15},'{16}')",
                                                        AutoManageIdx, barcodes, controltype, 2, 1, startdevice,
                                                        CellCode, 1, enddevice, "-", Lane, stack, "0", dtime, 0, 0,
                                                        enddevice);

                                                dbo.ExceSQL(sqlstr);
                                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient",
                                                    "自动生成出库任务:" + AutoManageIdx.ToString(),
                                                    startdevice.ToString() + ":" + CellCode, enddevice.ToString());

                                            }

                                        }

                                    }
                                    else
                                        if (dv[0]["FCONTROLTASKTYPE"].ToString() == "3" && CStaticClass.StopIn[Lane] == false)//巷道内移库任务
                                    {  
                                        startdevice = Lane ;
                                        enddevice = Lane;

                                           string CellCode;
                                           string startcell = dv[0]["FENDCELL"].ToString();
                                           CellCode = ccf.GetNextCell(startcell, Lane);
                                           

                                           if (CellCode != "-")
                                           {


                                            
                                               int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                               string stack = dv[0]["FSTACK"].ToString(); //堆垛机FSTACK

                                               string barcodes = AutoManageIdx.ToString();//托盘条码

                                               //int ifrevolve = 2;
                                               int controltype = 3;//移库
                                               //int boxtype = 2;
                                               string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15})", AutoManageIdx, barcodes, controltype, 2, 1, startdevice, startcell, 1, enddevice, CellCode, Lane, stack, "0", dtimes, 0, 0);

                                               dbo.ExceSQL(sqlstr);
                                               CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "自动生成移库任务:" + AutoManageIdx.ToString(), startdevice.ToString(), enddevice.ToString() + ":" + CellCode);


                                           }
                                          
                                        
                                    }


                        }

                        #endregion
                        //20101028
                        sql.Remove(0, sql.Length);
                        sql.Append("update T_Manage_Task set FSTATUS=999,FENDTIME='").Append(dtime).Append("'  where  FID=").Append(fid).Append(" and F_ManageTaskKindIndex= ").Append(mti);
                        dbo.ExceSQL(sql.ToString());
                    }
                    else
                    {
                        switch (dv[0]["FCONTROLTASKTYPE"].ToString())
                        {
                            case "1":
                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE='' WHERE (FLaneWay=").Append(dv[0]["FENDDEVICE"]).Append(" and F_Z='").Append(
                                    fcc[0]).Append("' and F_X='").Append(fcc[1]).Append("' and F_Y='").Append(fcc[2]).Append("')");
                                    dbo.ExceSQL(sql.ToString());
                                }
                                break;
                            case "2":
                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE='").Append(dv[0]["FPALLETBARCODE"]).Append("' WHERE (FLaneWay=").Append(dv[0]["FSTARTDEVICE"]).Append("  and F_Z=").Append(
                                    fcc[0]).Append(" and F_X=").Append(fcc[1]).Append(" and F_Y=").Append(fcc[2]).Append(")");
                                    dbo.ExceSQL(sql.ToString());
                                }
                                break;
                            case "3":
                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE=''  WHERE (FLaneWay=").Append(dv[0]["FENDDEVICE"]).Append(" and F_Z=").Append(
                                    fcc[0]).Append(" and F_X=").Append(fcc[1]).Append(" and F_Y=").Append(fcc[2]).Append(")");
                                    dbo.ExceSQL(sql.ToString());
                                }
                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                    sql.Remove(0, sql.Length);
                                    sql.Append("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE='").Append(dv[0]["FPALLETBARCODE"]).Append("'  WHERE (FLaneWay=").Append(dv[0]["FSTARTDEVICE"]).Append("  and F_Z=").Append(
                                    fcc[0]).Append(" and F_X=").Append(fcc[1]).Append(" and F_Y=").Append(fcc[2]).Append(")");
                                    dbo.ExceSQL(sql.ToString());
                                }

                                break;
                            default:
                                break;
                        }
                        //20101028
                        sql.Remove(0, sql.Length);
                        sql.Append("update T_Manage_Task set FSTATUS=900,FENDTIME='").Append(dtime).Append("'  where  FID=").Append(fid).Append(" and F_ManageTaskKindIndex= ").Append(mti);
                        dbo.ExceSQL(sql.ToString());
                    }
                }
                //20101028
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO T_Manage_Task_BAK SELECT * FROM T_Manage_Task where  FID=").Append(fid).Append(" and F_ManageTaskKindIndex>=1");
                dbo.ExecuteSql(sql.ToString());
                sql.Remove(0, sql.Length);
                sql.Append("delete from T_Manage_Task   where  FID=").Append(fid).Append(" and F_ManageTaskKindIndex= ").Append(mti);
                dbo.ExceSQL(sql.ToString());
                CDataChangeEventArgs cea = new CDataChangeEventArgs(null, null);
                OnDataChange("ReturnManageInfo", cea);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        /// <summary>
        /// 分类查找设备状态
        /// </summary>
        /// 任务报完成传参数 SCONTROL 里传的参数
        /// <param name="TaskIdx">设备指令索引</param>
        /// <param name="DeviceIdx">设备编号</param>
        /// <param name="State">设备状态</param>
        public void GetKindDeviceState(int TaskIdx, int DeviceIdx, int State)
        {

            int fid = ccf.GetManageTaskIndexfromMonitor(TaskIdx);
            int mti = ccf.GetManageTaskKindIndexFromMonitor(TaskIdx);
            if (fid <= 0) return;
            if (State >= 10)//故障
            {
                //回写设备错误状态字(IO_Control,T_Manage_Task,T_Monitor_task)

                ActionError(DeviceIdx, TaskIdx, State);//
                #region 多叉关联任务能同步运行的同时报告故障
                //devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                //if (devinfo.IfCorrelDoubleFork == "1")
                //{
                //    if (Model.CGeneralFunction.DoubleForkIfSync(TaskIdx, DeviceIdx, 1) == true)
                //    {
                //        string[] df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                //        if (df != null)
                //        {
                //            ActionError(Convert.ToInt32(df[2]), Convert.ToInt32(df[0]), States[1]);
                //        }
                //    }
                //}
                #endregion
                //刷新监控中心显示

            }


            switch (ccf.GetDeviceKindIdx(DeviceIdx))
            {
                //正在运行的设备如果有探物就是说托盘运行到此设备
                //根据任务号判断是否为调度任务,改写T_Manage_Task的当前位置
                //根据任务号和当前位置判断是否有提前触发任务
                //任务号传递到当前设备时,把本路径的前一设备的运行锁解除,
                //同时把当前设备加运行锁

                case 1://堆垛机:
                    //1-正在运行 2-完成;3-要求调度重发命令;
                    //4-通知调度取消当前任务;其它值表示错误
                    if (State == 1)//开始运行
                    {//正在运行的设备如果有探物就是说托盘运行到此设备
                        ActionStartRun(DeviceIdx, TaskIdx);
                        
                        #region 多叉关联任务,能同步的同时报告运行
                        //20100323
                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        if (devinfo.IfCorrelDoubleFork == "1")
                        {
                            int[] corrtasks=Model.CGeneralFunction.MutiForkIfSync(TaskIdx, DeviceIdx, 1);
                            if (corrtasks!=null )
                            {
                                Dictionary<int, string[]> df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                                if (df != null)
                                {
                                    foreach (int corrtask in corrtasks)
                                    {
                                        ActionStartRun(Convert.ToInt32(df[corrtask][2]), corrtask);
                                        //if (mti == 1)
                                        //{//20100714
                                        //    fid = ccf.GetManageTaskIndexfromMonitor(corrtask);
                                        //    sql.Remove(0, sql.Length);
                                        //    sql.Append("update IO_CONTROL set CONTROL_STATUS=11 where CONTROL_ID=").Append(fid);
                                        //    dboM.ExecuteSql(sql.ToString());
                                        //}
                                    }
                                }
                            }
                        }
                        #endregion
                        //刷新监控中心显示
                    }
                    if (State == 2)//报告完成,应该也有坐标
                    {//20120616

                       Dictionary<int,  string[]> df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                        int[] snyc = Model.CGeneralFunction.MutiForkIfSync(TaskIdx, DeviceIdx, 1);
                        ActionComplete(DeviceIdx, TaskIdx, 1);
                        
                        #region 多叉关联任务,能同步的同时报告完成;异步的直接执行关联的命令
                        //20100323
                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        if ((devinfo.IfCorrelDoubleFork == "1") && (df != null))
                        {

                            if (snyc != null)//20100702
                            {
                                foreach (int cortask in snyc)
                                {
                                    if (GetTaskStatus(cortask))//只处理已经发送的任务20190323

                                    { ActionComplete(DeviceIdx, cortask, 1);
                                        df.Remove(cortask);
                                    }
                                }

                            }
                            
                            
                        }
                        #endregion
                    }

                    break;
                case 2://输送机

                    if (State == 1)//开始运行
                    {//正在运行的设备如果有探物就是说托盘运行到此设备
                        ActionStartRun(DeviceIdx, TaskIdx);
                        #region 多叉关联任务,能同步的同时报告运行
                        //20100323
                        devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        if (devinfo.IfCorrelDoubleFork == "1")
                        {
                            int[] corrtasks= Model.CGeneralFunction.MutiForkIfSync(TaskIdx, DeviceIdx, 2);
                            if (corrtasks!=null)
                            {
                                Dictionary<int, string[]> df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                                if (df != null)
                                {
                                    foreach (int i in corrtasks)
                                    {
                                        ActionStartRun(Convert.ToInt32(df[i][2]), i);
                                    }
                                }
                            }
                        }
                        #endregion
                        //刷新监控中心显示

                    }
                    if (State == 2)//报告完成
                    {//20120616
                        Dictionary<int, string[]> df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                        int[] snyc = Model.CGeneralFunction.MutiForkIfSync(TaskIdx, DeviceIdx, 2);
                        ActionComplete(DeviceIdx, TaskIdx, 1);
                        //刷新监控中心显示
                        #region 多叉关联任务,能同步的同时报告完成;异步的直接执行关联的命令
                        //20100323
                        //devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIdx);
                        //if (devinfo.IfCorrelDoubleFork == "1")
                        //{

                        //    if ((devinfo.IfCorrelDoubleFork == "1") && (df != null))//20100702
                        //    {

                        //        if (snyc != null)
                        //        {
                        //            foreach (int corrtask in snyc)
                        //            {
                        //                ActionComplete(DeviceIdx, corrtask , 1);
                        //                df.Remove(corrtask);
                        //            }
                        //        }
                                
                        //    }
                        //}
                        #endregion
                    }
                    #region 输送机输送超时,错误代码34//20110608

                    //string begintime = Model.CGeneralFunction.GetMonitorTaskBeginTime(TaskIdx);
                    //if (begintime != "-")
                    //{
                    //    if (Convert.ToDateTime(begintime.Substring(0, 19), CultureInfo.CurrentCulture).AddMinutes(int.Parse(CStaticClass.TransportTimeout)) <= DateTime.Now)
                    //    {
                    //        ActionError(DeviceIdx, TaskIdx, 34);
                    //    }
                    //}
                    //int moindex = ccf.GetMonitorTaskIndexFromRunTimeoutDevice(DeviceIdx);
                    //if (moindex > -1)
                    //{
                    //    ActionError(DeviceIdx, moindex, 34);
                    //}
                    #endregion
                    break;
                case 31://高端
                    if (State == 1)
                    {//正在运行的设备如果有探物就是说托盘运行到此设备
                        ActionStartRun(DeviceIdx, TaskIdx);
                        //刷新监控中心显示

                    }
                    if (State == 2)//报告完成
                    {
                        ActionComplete(DeviceIdx, TaskIdx, 1);
                        //刷新监控中心显示

                    }

                    break;
                case 4://穿梭车
                    if (State == 1)
                    {//正在运行的设备如果有探物就是说托盘运行到此设备
                        ActionStartRun(DeviceIdx, TaskIdx);
                        //刷新监控中心显示

                    }
                    if (State == 2)//报告完成
                    {
                        ActionComplete(DeviceIdx, TaskIdx, 1);
                        //刷新监控中心显示

                    }

                    break;
                case 5://叠盘机

                    break;
                case 6://AGV车

                    break;
                case 7://条码扫描仪:需要在IO_ControlDetail表比对条码值

                    break;
                case 8://称重设备:向IO_ControlDetail表写入重量值

                    break;
                case 9://站台

                    break;
                case 10://巷道

                    break;
                case 11://分拣机

                    break;
                case 12://虚拟端点

                    break;
                case 13://空设备

                    break;
                case 14://确认按钮

                    break;
                case 15://定时器

                    break;
                case 16://指示灯

                    break;
                case 17://码垛机

                    break;
                case 18://检测开关

                    break;


            }


        }
        
        
        /// <summary>
        /// 追加倒库货位至真实终点货位的取货和送货指令
        /// </summary>
        /// <param name="mti">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="device">设备索引</param>
        /// <param name="monitorindex">设备指令索引</param>
        bool AppendMoveCellOperate(int mti, int fid, int device,int monitorindex)
        {//20120820
            DataView dv = new DataView();
            try
            {
                string newuseawayfork = string.Empty;
                sql.Remove(0, sql.Length);
                sql.Append("update T_Manage_Task set FExceptionNO=NULL where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                dbo.ExecuteSql(sql.ToString());
                sql.Remove(0, sql.Length);
                sql.Append("update T_Base_Device set F_ManTaskReserve=").Append((mti.ToString() + fid.ToString())).Append(" where  F_DeviceIndex=").Append(device);
                dbo.ExceSQL(sql.ToString());
                //获取管理任务送货坐标,当前调度任务的路径,条码,优先级;远近货叉,提前检测
                sql.Remove(0, sql.Length);
                sql.Append("SELECT FENDCELL FROM T_Manage_Task WHERE (FID = ").Append(fid).Append(") AND (F_ManageTaskKindIndex = ").Append(mti).Append(")");

                char[] cc = new char[1] { '-' };
                string[] spcell = dbo.GetSingle(sql.ToString()).ToString().Split(cc);

                sql.Remove(0, sql.Length);
                sql.Append("select F_NumParam4, F_NumParam5,F_NumParam6, F_RouteID,F_MonitorTaskLevel, F_UseAwayFork, F_TxtParam, F_AGVTask, F_AGVNextTask,F_ChangeStackCell from T_Monitor_Task where F_MonitorIndex=").Append(monitorindex);////20120820
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count <= 0) return false;
                //发送命令时根据目标位置定位货叉newuseawayfork
                newuseawayfork = "0";
                int snextq = int.Parse(dv[0]["F_AGVTask"].ToString());//20120518
                int snexts = int.Parse(dv[0]["F_AGVNextTask"].ToString());//20120518
                int lev = int.Parse(dv[0]["F_MonitorTaskLevel"].ToString());
                int routeid = int.Parse(dv[0]["F_RouteID"].ToString());
                int fnp1 = int.Parse(dv[0]["F_NumParam4"].ToString());
                int fnp2 = int.Parse(dv[0]["F_NumParam5"].ToString());
                int fnp3 = int.Parse(dv[0]["F_NumParam6"].ToString());
                string pcode = dv[0]["F_TxtParam"].ToString();
                string ChangeStackCell = dv[0]["F_ChangeStackCell"].ToString();//20120820
                StringBuilder aheaddet = new StringBuilder("I" + device.ToString());
                //根据目标货位检测货叉是否有货
                int forkno = Convert.ToInt32(ccf.GetLimitXForkNo(Convert.ToInt32(spcell[1]), ccf.GetLaneWayNoFromStack(device)));
                if (forkno > 0)
                {
                    newuseawayfork = forkno.ToString();//20140214补充货叉
                    aheaddet.Append(";D").Append(device.ToString()).Append(".").Append(Convert.ToInt32(forkno - 1));
                }
                int mindex = snextq;//20120518
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel,").Append(
                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5,").Append(
                    " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork,f_ChangeStackCell)VALUES ").Append(
                    "(").Append(fid).Append(",").Append(mti).Append(",").Append(mindex).Append(",").Append(lev).Append(",").Append(device).Append(",4,").Append(routeid).Append(",0,").Append(fnp1).Append(",").Append(fnp2).Append(",").Append(fnp3).Append(",").Append(
                    spcell[0]).Append(",").Append(spcell[1]).Append(",").Append(spcell[2]).Append(",'").Append(pcode).Append("','").Append(aheaddet.ToString()).Append("','").Append(newuseawayfork).Append("','").Append(ChangeStackCell).Append("')");//20120820
                dbo.ExecuteSql(sql.ToString());
                mindex = snexts;//20120518
                aheaddet = new StringBuilder("I" + device.ToString());
                if (forkno > 0)
                {
                    aheaddet.Append(";D-").Append(device.ToString()).Append(".").Append(Convert.ToInt32(forkno - 1));
                }
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel,").Append(
                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5,").Append(
                    " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork)VALUES ").Append(
                    "(").Append(fid).Append(",").Append(mti).Append(",").Append(mindex).Append(",").Append(lev).Append(",").Append(device).Append(",5,").Append(routeid).Append(",0,").Append(fnp1).Append(",").Append(fnp2).Append(",").Append(fnp3).Append(",").Append(
                    spcell[0]).Append(",").Append(spcell[1]).Append(",").Append(spcell[2]).Append(",'").Append(pcode).Append("','").Append(aheaddet.ToString()).Append("','").Append(newuseawayfork).Append("')");//20120820
                dbo.ExecuteSql(sql.ToString());
                return true;
            }
            
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("报告完成时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rmea);
                return false;
            }
            finally
            {
                dv.Dispose();
                
            }

        }
        bool AppendStackMoveCellOperate(int mti, int fid, int device, int monitorindex)
        {//20120820
            string newuseawayfork=string.Empty;
            char[] cc = new char[1] { '-' };
            DataView dvl = new DataView(); DataView dv = new DataView();
            string sqlstr = string.Empty;
            try
            {
                //如果当前指令的终点位置 不是最终位置,还要继续生成倒库任务

                //获取管理任务送货坐标,当前调度任务的路径,条码,优先级;远近货叉,提前检测
                sql.Remove(0, sql.Length);
                sql.Append("SELECT FREMARK FROM T_Manage_Task WHERE (FID = ").Append(fid).Append(") AND (F_ManageTaskKindIndex = ").Append(mti).Append(")");
                object arrcell = dbo.GetSingle(sql.ToString());
                if (arrcell == null) return false  ;


                sql.Remove(0, sql.Length);
                sql.Append("select F_NumParam4, F_NumParam5,F_NumParam6, F_RouteID,F_MonitorTaskLevel, F_UseAwayFork, F_TxtParam,F_AheadDetect,F_PriorMonitor,F_AGVTask,F_AGVNextTask,F_ChangeStackCell from T_Monitor_Task where F_MonitorIndex=").Append(monitorindex);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count <= 0) return false  ;
                //发送命令时根据目标位置定位货叉newuseawayfork
                newuseawayfork = dv[0]["F_UseAwayFork"].ToString();
                int lev = int.Parse(dv[0]["F_MonitorTaskLevel"].ToString());
                int routeid = int.Parse(dv[0]["F_RouteID"].ToString());
                int fnp1 = int.Parse(dv[0]["F_NumParam4"].ToString());//当前任务放到的货位
                int fnp2 = int.Parse(dv[0]["F_NumParam5"].ToString());
                int fnp3 = int.Parse(dv[0]["F_NumParam6"].ToString());
                string pcode = dv[0]["F_TxtParam"].ToString();
                int lifterUp = int.Parse(dv[0]["F_PriorMonitor"].ToString());
                int snextq = int.Parse(dv[0]["F_AGVTask"].ToString());
                int snexts = int.Parse(dv[0]["F_AGVNextTask"].ToString());
                string ChangeStackCell = dv[0]["F_ChangeStackCell"].ToString();//18001;Z-X-Y
                int olddev = device;

                int snextqtemp = Convert.ToInt32(dv[0]["F_AGVTask"]) + 1;
                int snextstemp = Convert.ToInt32(dv[0]["F_AGVNextTask"]) + 1;
                devinfo = Model.CGetInfo.GetDeviceInfo(device);
                int StackIndex = devinfo.VirtualStack;
                //device = devinfo.MutexStack;
                //查找能在当前放货位置执行任务的所有堆垛机

                string SendCell = string.Format("{0:D2}-{1:D2}-{2:D2}", fnp1, fnp2, fnp3);//当前的送货位置
                //查找该倒库位置对应的设备编号

                int lanegate =ccf.GetLaneGateDeviceIndexFromLaneGate(SendCell);//获得倒库货位对应的设备编号
                if (lanegate==0) return false;

                    sqlstr = string.Format("SELECT F_StackIndex FROM  T_Base_StackInfo WHERE F_ChangeStackCell like  '%{0}%' and F_StackIndex !={1}", lanegate, device);

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

                    device = Convert.ToInt32(dv[0]["F_StackIndex"]);//找到接下来执行倒库任务的堆垛机
                }
                else
                {
                    device = devinfo.MutexStack;
                }




                //判读新的堆垛机能否执行最终货位的任务
                 string newcell = ccf.GetIfStackCanWorkFromCellAndLaneGate(arrcell.ToString(), device, lanegate);
                 if (newcell == arrcell.ToString())//如果送货位置是终点位置,则表示不需要进行再次倒换堆垛机
                {
                    ChangeStackCell = "";//执行最后一个送货指令时,可以执行其他倒库任务了
                 sql.Remove(0, sql.Length);
                 sql.Append("update T_Manage_Task set FExceptionNO=NULL where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);
                 dbo.ExecuteSql(sql.ToString());
                }
                //string[] spcell = arrcell.ToString().Split(cc);//最终要放到的货位
                 string[] spcell = newcell.ToString().Split(cc);//最终要放到的货位

                StringBuilder aheaddet = new StringBuilder("I" + device.ToString());
                int laneway = 0;
                dvl = dbo.ExceSQL(string.Format("SELECT F_LaneDeviceIndex FROM  T_Base_LaneInfo WHERE (F_StackIndex = {0})", StackIndex)).Tables[0].DefaultView;
                if (dvl.Count > 0)
                {
                    laneway = Convert.ToInt32(dvl[0]["F_LaneDeviceIndex"]);
                }

                //如果终点位置是设备
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_LaneGateDeviceIndex FROM T_Base_Lane_Gate WHERE (F_ZXY = '").Append(newcell.ToString()).Append("') and F_LaneIndex=").Append(laneway);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {//20120420高端高位信号是.2;物流输送机高位信号是.6

                    int lanegateindex = Convert.ToInt32(dv[0][0]);
                    int devicekind=ccf.GetDeviceKindIdx(lanegateindex);
                    if (devicekind == 2|| devicekind == 9)
                    {

                        string[] cdi = ccf.GetLanewayDeviceInfoFromStackDev(StackIndex, lanegateindex);
                        if (cdi != null)
                        {///20120906检测被堆垛机送货的顶升机构在顶升高位,无物,近巷道5和远巷道6也无物
                            if (cdi[1] != "")
                            {
                                aheaddet.Append(";D-").Append(cdi[1]);//是否允许信号
                            }

                            aheaddet.Append(";D").Append(cdi[3]);//检测是否有货
                        }

                        aheaddet.Append(";N").Append(lanegateindex).Append(";I").Append(lanegateindex);//检测是否逻辑有货,空闲
                    }

                }
                //StringBuilder aht = new StringBuilder(aheaddet.ToString());
                //int forkno = Convert.ToInt32(ccf.GetLimitXForkNo(Convert.ToInt32(spcell[1]), ccf.GetLaneWayNoFromStack(device)));
                //if (forkno > 0)
                //{
                //    newuseawayfork = forkno.ToString();//20140214补充货叉
                //    aht.Append(";D").Append(device.ToString()).Append(".").Append(Convert.ToInt32(forkno - 1));
                //}
                int mindex =snextq;
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel,").Append(
                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5,").Append(
                    " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork,F_PriorMonitor,F_ChangeStackCell,F_AgvTask,F_AGVNextTask)VALUES ").Append(
                    "(").Append(fid).Append(",").Append(mti).Append(",").Append(mindex).Append(",").Append(lev).Append(",").Append(device).Append(",4,").Append(routeid).Append(",0,").Append(fnp1).Append(",").Append(fnp2).Append(",").Append(fnp3).Append(",").Append(
                    spcell[0]).Append(",").Append(spcell[1]).Append(",").Append(spcell[2]).Append(",'").Append(pcode).Append("','").Append(aheaddet).Append("','").Append(newuseawayfork).Append("',").Append(lifterUp).Append(",'").Append(ChangeStackCell).Append("',").Append(snextqtemp).Append(",").Append(snextstemp).Append(")");
                dbo.ExecuteSql(sql.ToString());
                mindex = snexts;
                sql.Remove(0, sql.Length);//到最后终点货位的送货指令中不用插入F_ChangeStackCell,因为取货执行完就是安全的了
                sql.Append("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel,").Append(
                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5,").Append(
                    " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork,F_PriorMonitor,F_ChangeStackCell,F_AgvTask,F_AGVNextTask)VALUES ").Append(
                    "(").Append(fid).Append(",").Append(mti).Append(",").Append(mindex).Append(",").Append(lev).Append(",").Append(device).Append(",5,").Append(routeid).Append(",0,").Append(fnp1).Append(",").Append(fnp2).Append(",").Append(fnp3).Append(",").Append(
                    spcell[0]).Append(",").Append(spcell[1]).Append(",").Append(spcell[2]).Append(",'").Append(pcode).Append("','").Append(aheaddet).Append("','").Append(newuseawayfork).Append("',").Append(lifterUp).Append(",'").Append(ChangeStackCell).Append("',").Append(snextqtemp).Append(",").Append(snextstemp).Append(")");
                dbo.ExecuteSql(sql.ToString());
                return true;
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("报告完成时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rmea);
                return false;
            }
            finally
            {
                dv.Dispose();
                dvl.Dispose();
            }

        }
        bool AppendStackMoveExchangeOperate(int mti, int fid, int device, int monitorindex)
        {//20120820
            string newuseawayfork = string.Empty;
            char[] cc = new char[1] { '-' };
            DataView dvl = new DataView(); DataView dv = new DataView();
            string sqlstr = string.Empty;
            try
            {
                //如果当前指令的终点位置 不是最终位置,还要继续生成倒库任务

                //获取管理任务送货坐标,当前调度任务的路径,条码,优先级;远近货叉,提前检测
                sql.Remove(0, sql.Length);
                sql.Append("SELECT FREMARK FROM T_Manage_Task WHERE (FID = ").Append(fid).Append(") AND (F_ManageTaskKindIndex = ").Append(mti).Append(")");
                object arrcell = dbo.GetSingle(sql.ToString());
                if (arrcell == null) return false;


                sql.Remove(0, sql.Length);
                sql.Append("select F_NumParam4, F_NumParam5,F_NumParam6, F_RouteID,F_MonitorTaskLevel, F_UseAwayFork, F_TxtParam,F_AheadDetect,F_PriorMonitor,F_AGVTask,F_AGVNextTask,F_ChangeStackCell from T_Monitor_Task where F_MonitorIndex=").Append(monitorindex);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count <= 0) return false;
                //发送命令时根据目标位置定位货叉newuseawayfork
                newuseawayfork = dv[0]["F_UseAwayFork"].ToString();
                int lev = int.Parse(dv[0]["F_MonitorTaskLevel"].ToString());
                int routeid = int.Parse(dv[0]["F_RouteID"].ToString());
                int fnp1 = int.Parse(dv[0]["F_NumParam4"].ToString());//当前任务放到的货位
                int fnp2 = int.Parse(dv[0]["F_NumParam5"].ToString());
                int fnp3 = int.Parse(dv[0]["F_NumParam6"].ToString());
                string pcode = dv[0]["F_TxtParam"].ToString();
                int lifterUp = int.Parse(dv[0]["F_PriorMonitor"].ToString());
                int snextq = int.Parse(dv[0]["F_AGVTask"].ToString());
                int snexts = int.Parse(dv[0]["F_AGVNextTask"].ToString());
                string ChangeStackCell = dv[0]["F_ChangeStackCell"].ToString();//18001;Z-X-Y
                int olddev = device;

                int snextqtemp = Convert.ToInt32(dv[0]["F_AGVTask"]) + 1;
                int snextstemp = Convert.ToInt32(dv[0]["F_AGVNextTask"]) + 1;
                devinfo = Model.CGetInfo.GetDeviceInfo(device);
                int StackIndex = devinfo.VirtualStack;
                //device = devinfo.MutexStack;
                //查找能在当前放货位置执行任务的所有堆垛机

                string SendCell = string.Format("{0:D2}-{1:D2}-{2:D2}", fnp1, fnp2, fnp3);//当前的送货位置
                //查找该倒库位置对应的设备编号

                int lanegate = ccf.GetLaneGateDeviceIndexFromLaneGate(SendCell);//获得倒库货位对应的设备编号
                if (lanegate == 0) return false;

                //if (changetype == Model.CGeneralFunction.TASKCHANGESTACK)//20181009
                //{
                //    sqlstr = string.Format("SELECT F_StackIndex FROM  T_Base_StackInfo WHERE F_ChangeStackCell like  '%{0}%' and F_StackIndex !={1}", lanegate, device);

                //    dv = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                //    if (dv.Count <= 0) return false;
                //    device = Convert.ToInt32(dv[0]["F_StackIndex"]);//找到接下来执行倒库任务的堆垛机
                //}
                //else
                //{

                string Enddevice = ccf.GetEndDeviceFromManage(mti, fid);
                string[] EndGroup = Enddevice.Split(';');
                //中转完后,判断终点位置能放货的堆垛机,如果有多个就是用虚拟堆垛机,如果有一个就用那一个
                //device = StackIndex;//使用虚拟堆垛机
                //
                


                //判读新的堆垛机能否执行最终货位的任务
                string newcell = arrcell.ToString();
                string[] spcell = newcell.ToString().Split(cc);//最终要放到的货位
                string workstack = ccf.GetWorkStackNoFromCell(newcell, device);//查找能执行该货位任务的堆垛机

                string[] stacks = workstack.Split(';');

                if(stacks.Length==1&& EndGroup.Length>=2)//
                {
                    device = Convert.ToInt32( workstack);//使用堆垛机
                }
                else
                {
                    device = StackIndex;//使用虚拟堆垛机
                }

                //if (newcell == arrcell.ToString())//如果送货位置是终点位置,则表示不需要进行再次倒换堆垛机
                //{

                ChangeStackCell = "";//执行最后一个送货指令时,可以执行其他倒库任务了
                sql.Remove(0, sql.Length);
                sql.Append("update T_Manage_Task set  FExceptionNO=NULL where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);//接触双叉关联
                dbo.ExecuteSql(sql.ToString());

                if (EndGroup.Length<2)
                {

                    sql.Remove(0, sql.Length);
                    sql.Append("update T_Manage_Task set F_RELATIVECONTORLID = - 1   where F_ManageTaskKindIndex=").Append(mti).Append(" and FID=").Append(fid);//接触双叉关联
                    dbo.ExecuteSql(sql.ToString());
                }
                //}



                StringBuilder aheaddet = new StringBuilder("I" + device.ToString());
                int laneway = 0;
                dvl = dbo.ExceSQL(string.Format("SELECT F_LaneDeviceIndex FROM  T_Base_LaneInfo WHERE (F_StackIndex = {0})", StackIndex)).Tables[0].DefaultView;
                if (dvl.Count > 0)
                {
                    laneway = Convert.ToInt32(dvl[0]["F_LaneDeviceIndex"]);
                }

                //如果终点位置是设备
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_LaneGateDeviceIndex FROM T_Base_Lane_Gate WHERE (F_ZXY = '").Append(newcell.ToString()).Append("') and F_LaneIndex=").Append(laneway);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {//20120420高端高位信号是.2;物流输送机高位信号是.6

                    int lanegateindex = Convert.ToInt32(dv[0][0]);
                    int devicekind = ccf.GetDeviceKindIdx(lanegateindex);
                    if (devicekind == 2|| devicekind == 9)
                    {

                        string[] cdi = ccf.GetLanewayDeviceInfoFromStackDev(StackIndex, lanegateindex);
                        if (cdi != null)
                        {///20120906检测被堆垛机送货的顶升机构在顶升高位,无物,近巷道5和远巷道6也无物
                            if (cdi[1] != "")
                            {
                                aheaddet.Append(";D-").Append(cdi[1]);//是否允许信号
                            }

                            aheaddet.Append(";D").Append(cdi[3]);//检测是否有货
                        }

                        aheaddet.Append(";N").Append(lanegateindex).Append(";I").Append(lanegateindex);//检测是否逻辑有货,空闲
                    }

                }
                //StringBuilder aht = new StringBuilder(aheaddet.ToString());
                //int forkno = Convert.ToInt32(ccf.GetLimitXForkNo(Convert.ToInt32(spcell[1]), ccf.GetLaneWayNoFromStack(device)));
                //if (forkno > 0)
                //{
                //    newuseawayfork = forkno.ToString();//20140214补充货叉
                //    aht.Append(";D").Append(device.ToString()).Append(".").Append(Convert.ToInt32(forkno - 1));
                //}
                int mindex = snextq;
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel,").Append(
                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5,").Append(
                    " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork,F_PriorMonitor,F_ChangeStackCell,F_AgvTask,F_AGVNextTask)VALUES ").Append(
                    "(").Append(fid).Append(",").Append(mti).Append(",").Append(mindex).Append(",").Append(lev).Append(",").Append(device).Append(",4,").Append(routeid).Append(",0,").Append(fnp1).Append(",").Append(fnp2).Append(",").Append(fnp3).Append(",").Append(
                    spcell[0]).Append(",").Append(spcell[1]).Append(",").Append(spcell[2]).Append(",'").Append(pcode).Append("','").Append(aheaddet).Append("','").Append(newuseawayfork).Append("',").Append(lifterUp).Append(",'").Append(ChangeStackCell).Append("',").Append(snextqtemp).Append(",").Append(snextstemp).Append(")");
                dbo.ExecuteSql(sql.ToString());
                mindex = snexts;
                sql.Remove(0, sql.Length);//到最后终点货位的送货指令中不用插入F_ChangeStackCell,因为取货执行完就是安全的了
                sql.Append("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel,").Append(
                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5,").Append(
                    " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork,F_PriorMonitor,F_ChangeStackCell,F_AgvTask,F_AGVNextTask)VALUES ").Append(
                    "(").Append(fid).Append(",").Append(mti).Append(",").Append(mindex).Append(",").Append(lev).Append(",").Append(device).Append(",5,").Append(routeid).Append(",0,").Append(fnp1).Append(",").Append(fnp2).Append(",").Append(fnp3).Append(",").Append(
                    spcell[0]).Append(",").Append(spcell[1]).Append(",").Append(spcell[2]).Append(",'").Append(pcode).Append("','").Append(aheaddet).Append("','").Append(newuseawayfork).Append("',").Append(lifterUp).Append(",'").Append(ChangeStackCell).Append("',").Append(snextqtemp).Append(",").Append(snextstemp).Append(")");
                dbo.ExecuteSql(sql.ToString());
                return true;
            }
            catch (Exception ex)
            {
                RefreshMonitorEventArgs rmea = new RefreshMonitorEventArgs("tsStatus", string.Format("报告完成时:{0}", ex.StackTrace + ex.Message));
                OnRefreshMonitor(rmea);
                return false;
            }
            finally
            {
                dv.Dispose();
                dvl.Dispose();
            }

        }
        int GetRouteIDsub(int device)
        {
            DataView dv = new DataView();
            try
            {
                dv = dbo.ExceSQL("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;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        string GetUseAwayForkFromLaneGate(int device)
        {//20120820
            DataView dv = new DataView();
            try
            {
                dv = dbo.ExceSQL(string.Format("SELECT F_UseAwayFork FROM T_Base_Lane_Gate WHERE (F_LaneGateDeviceIndex = {0}) ", device)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return dv[0]["F_UseAwayFork"].ToString();
                }
                else
                {
                    return "0";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        int GetStackGetXCoordinateFromLaneGate(int stackIndex, int devIndex)
        {
            DataView dv = new DataView();
            int LaneWay = ccf.GetLaneWayFromLaneInfo(stackIndex);
            char[] cc = new char[1] { '-' };
            try
            {
                sql.Remove(0, sql.Length);
                sql.Append("select * from T_Base_Lane_Gate where F_LaneGateDeviceIndex=").Append(devIndex).Append(" and F_LaneIndex=").Append(LaneWay);
                dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                    return Convert.ToInt32(dv[0]["F_ZXY"].ToString().Split(cc)[1]);//列X
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                CGetStateError = "ControlSystem.CGetState.GetStackGetXCoordinateFromLaneGate:" +ex.StackTrace+ ex.Message;
                return -1;
            }
            finally
            {
                dv.Dispose();
            }
        }
        
    }
}