using RGD.Common;
using RGD.DataService;
using RGD.DBUtility;
using RGD.MdsAPI;
using RGD.MdsAPI.WMS;
using RGD.OPCClient;
using System;
using System.Data;

namespace RGD.WCS
{
    /// <summary>
    /// Creator:RGD
    /// 获得设备状态类
    /// 需要做的工作：
    /// 1.下位机给上位机发送设备（任务）状态信息（正在执行状态或者报警的设备所处调度路径的F_SerialNumber》=当前值）
    /// 2.（单独处理）下位机给上位机发送条码信息（托盘条码，烟箱一号工程码）
    /// 3.（单独处理）下位机给上位机发送现场控制触摸屏申请信号：1-重发当前设备指令
    ///     2-申请修改当前设备所执行任务的目标位置
    /// 4.跟踪货物运行到的位置（多个调度任务在执行同一个调度任务，取有探物的为当前位置）
    ///     并且判断是否存在提前触发任务
    /// 5.获取调度任务的优先策略判断：最短路径优先，
    /// 入库优先携带出库，出库优先携带入库等
    /// 6.任务号传递到当前设备时，把本路径的前一设备的运行锁解除，
    ///     同时把当前设备加运行锁
    /// 7.（根据故障点单独处理）调度路径是否可用的分析以及给管理进行反馈
    /// 8.（单独处理）创建自动调度任务
    /// 9.动画显示设备状态
    /// </summary>
    public class CGetState
    {
        private Model.MError errs;
        private Model.MDevice devinfo;
        private ISendDeviceOrder sdo;
        private CCommonFunction ccf = new CCommonFunction();
        private CControl ccl = new CControl();
        private string _CGetStateError = "";//监控调度类错误说明

        public string CGetStateError
        {
            get { return _CGetStateError; }
            set { _CGetStateError = value; }
        }

        public int[] _States;
        private int _fid;

        /// <summary>
        /// ManageTypeIndex
        /// </summary>
        private int _mti;

        private string _start_cell;
        private string _fmanageid;

        /// <summary>
        /// 获得所有正在执行设备的状态
        /// </summary>
        public CGetState()
        {
        }

        /// <summary>
        /// 获得反馈信息
        ///电器反馈该设备的"完成"时 删除设备指令 , 解除设备表占用状态F_LockedState=0；
        ///路径明细表F_LockedDeviceIndex里的所有对应设备索引解锁;
        ///
        ///判断是最后一个设备指令吗? 是,回写调度任务IO_Control的FSTATUS=2即"搬运完成";
        /// T_Manage_Task的正在执行状态FSTATUS=2
        /// </summary>
        /// <returns></returns>
        public void GetDeviceState()
        {
            try
            {
                DataView dv = new DataView();
                DataView dvm = new DataView();
                DataView dvmo = new DataView();
                int devKind;
                int DeviceIdx;
                int MonitorIndex = 0;
                string[] wv = new string[1] { "2" };
                string[] witemnames = new string[1];
                //分类查找的设备类型
                DataView dd = DbHelperSQL.Query("SELECT F_DeviceIndex,F_DeviceKindIndex,F_MaxSendCount,F_SendInterval FROM T_Base_Device WHERE F_DeviceKindIndex in(1,2,5,32,33,34)").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"]);
                    if (devKind != 1)
                    {
                        devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
                        //分类查找设备状态
                        GetKindDeviceState(MonitorIndex, DeviceIdx, 0);
                    }
                    else
                    {
                        continue;
                    }
                }
                dv = null; dvm = null; dvmo = null; dd = null;

                #region 任务STOPPING处理
                DataView dv_task = DbHelperSQL.Query("select * from t_warehouse").Tables[0].DefaultView;
               
                Object RFIDCount = DbHelperSQL.GetSingle("select count from T_InTask_QTY");
                //任务停止状态 且 出库任务 且 有尾箱结束标志
                if (dv_task[0]["F_TASK_STATUS"].ToString() == "STOPPING" || (dv_task[0]["F_LASTBOX_REACH_FLAG"] != DBNull.Value && ((bool)dv_task[0]["F_LASTBOX_REACH_FLAG"])) || dv_task[0]["F_TASK_TYPE"].Equals("Out") || RFIDCount.ToString() == "0")
                {
                    DataView dv_manage = DbHelperSQL.Query("select * from t_manage_task where fmanageid='" + dv_task[0]["F_TASK_NO"] + "'").Tables[0].DefaultView;
                    //且无调度任务
                    if (dv_manage.Count == 0)
                    {
                        {
                            DataView dv_rfid = DbHelperSQL.Query("select SOURCE_CELL_CODE from IO_RFID where STATION_CODE in ('" + CConfig.Device_Rfid + "') and not SOURCE_CELL_CODE='' and SOURCE_CELL_CODE is not null").Tables[0].DefaultView;
                            //且射频无物
                            if (dv_rfid.Count == 0)
                            {
                                bool cleared = true;
                                DataSet ds_diepan = DbHelperSQL.Query("select * from t_base_plc_ask where f_askkind=2 and not f_barcode='' and f_barcode is not null and not f_barcode='-'");
                                if (ds_diepan.Tables[0].Rows.Count > 0)
                                {   //叠盘机有物时，入库命令下达
                                    foreach (DataRow dr in ds_diepan.Tables[0].Rows)
                                    {
                                        //sdo = CommModeCreate.CreateSendDeviceOrder(14001);
                                        //sdo.SendDeviceOrder(3, 0, 0, 14001, 0);
                                        //sdo = CommModeCreate.CreateSendDeviceOrder(12003);
                                        //sdo.SendDeviceOrder(3, 0, 0, 12003, 0);
                                        sdo = CommModeCreate.CreateSendDeviceOrder(int.Parse(dr["f_bindingdevice"].ToString()));
                                        sdo.SendDeviceOrder(3, 0, 0, int.Parse(dr["f_bindingdevice"].ToString()), 0);
                                        LogUtil.WriteLog("", "任务STOPPING处理;叠盘放行指令下达:" + int.Parse(dr["f_bindingdevice"].ToString()));
                                    }
                                    cleared = false;
                                }
                                /*//判断当前任务状态是否为停止,且设备指令只存在送货任务,入库或回库时,设备指令只剩下堆垛机送货任务,查询非送货任务数量,若为0,则调用机器人离开接口
                                DataView monitortask = DbHelperSQL.Query("select * from t_monitor_task where F_DeviceCommandIndex !='5'").Tables[0].DefaultView;
                                if (dv_task[0]["F_TASK_STATUS"].ToString() == "STOPPING" && monitortask.Count == 0)
                                {
                                    ApplyResult ar = SendDataToAgv.LetGo();
                                }*/
                                //叠盘机无物且任务状态停止
                                if (cleared && dv_task[0]["F_TASK_STATUS"].ToString() == "STOPPING")
                                {   //停止成功
                                    DbHelperSQL.ExecuteSql("update t_warehouse set f_task_no='',f_task_type='',f_task_status='FREE',f_equip_type='',F_IO_WH_SORT_CODE='',F_LASTBOX_REACH_FLAG=0");
                                    DataView dv_task_list = DbHelperSQL.Query("select top 1 * from t_task_list where task_status ='Waiting'").Tables[0].DefaultView;
                                    if (dv_task_list.Count > 0)
                                    {
                                        string sResult = string.Empty;
                                        //开启下一个等待中的任务
                                        new RGD.MdsAPI.HouseBase().InvokeHouse(dv_task_list[0]["METHOD_NAME"].ToString(), dv_task_list[0]["XMLIN"].ToString(), out sResult);
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion 任务STOPPING处理
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("获取设备状态时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "获取设备状态时：" + ex.Message, true);
                }
            }
        }

        /// <summary>
        /// 分类查找设备状态
        /// </summary>
        /// <param name="TaskIdx">设备指令索引</param>
        /// <param name="DeviceIdx">设备编号</param>
        /// /// <param name="RouteIDSub">调度路径的子路径的编号</param>
        public void GetKindDeviceState(int TaskIdx, int DeviceIdx, int RouteIDSub)
        {
            int[] States;
            try
            {
                States = CStaticClass.GetDeviceState(DeviceIdx);//[0]读写标志;[1]状态;[2]任务号；[3]X坐标;[4]Y坐标;[5]设备索引
                if (States == null || States.Length < 2)
                {
                    return;
                }
                DbHelperSQL.ExecuteSql("update t_base_device set f_runstate='" + States[1] + "' where F_DeviceIndex='" + DeviceIdx + "'");
            }
            catch (Exception ex)
            {
                DbHelperSQL.ExecuteSql("update t_base_device set f_runstate='" + ex.Message + "' where F_DeviceIndex='" + DeviceIdx + "'");
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("获取状态时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "获取状态时：" + ex.Message, true);
                }
                return;
            }
            _States = States;
            if (States == null)//没接收到任何返回值
            {
                return;
            }
            else
            {
                #region 状态处理
                TaskIdx = States[2];
                int fid = ccf.GetManageTaskIndexfromMonitor(TaskIdx);//dzf根据指令号找到任务号 这里参数TaskIdx是从PLC上读上来的，PLC中的TaskIdx是上位机send任务带的指令号
                int mti = ccf.GetManageTaskKindIndexFromMonitor(TaskIdx);//dzf根据指令号找到任务类型，1 调度 2自动 4手动等
                if (States[1] >= 30)//故障
                {
                    ActionError(DeviceIdx, TaskIdx, States[1]);//设备号 指令号 故障码
                }
                switch (BaseDeviceService.GetDeviceKindIdx(DeviceIdx))
                {
                    //正在运行的设备如果有探物就是说托盘运行到此设备
                    //根据任务号判断是否为调度任务，改写T_Manage_Task的当前位置
                    //根据任务号和当前位置判断是否有提前触发任务
                    //任务号传递到当前设备时，把本路径的前一设备的运行锁解除，
                    //同时把当前设备加运行锁
                    case 1:
                        #region 堆垛机:
                        //1-正在运行 2-完成;3-要求调度重发命令;
                        //4-通知调度取消当前任务;其它值表示错误
                        if ((States[1] == 1))
                        {
                            //开始运行，设置T_Monitor_Task的F_Status=2// || (States[0] == 2)
                            //正在运行的设备如果有探物就是说托盘运行到此设备
                            ActionStartRun(DeviceIdx, TaskIdx);
                            if (mti == 1)
                            {
                            }
                            #region 双叉关联任务，能同步的同时报告运行 暂无
                            devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
                            if (devinfo.IfCorrelDoubleFork == "1")
                            {
                                if (CGeneralFunction.DoubleForkIfSync(TaskIdx, DeviceIdx, 1) == true)
                                {
                                    string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                                    if (df != null)
                                    {
                                        ActionStartRun(Convert.ToInt32(df[2]), Convert.ToInt32(df[0]));
                                        if (mti == 1)
                                        {//20100714
                                            fid = ccf.GetManageTaskIndexfromMonitor(Convert.ToInt32(df[0]));
                                        }
                                    }
                                }
                            }
                            #endregion 双叉关联任务，能同步的同时报告运行 暂无
                        }
                        if (States[1] == 2)//报告完成,应该也有坐标
                        {
                            string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                            bool snyc = CGeneralFunction.DoubleForkIfSync(TaskIdx, DeviceIdx, 1);
                            ActionComplete(DeviceIdx, TaskIdx, 1);
                            //刷新监控中心显示
                            #region 双叉关联任务，能同步的同时报告完成；异步的直接执行关联的命令
                            devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
                            if ((devinfo.IfCorrelDoubleFork == "1") && (df != null))
                            {
                                if (snyc == true)//双叉关联任务是否能同步运行
                                {
                                    ActionComplete(DeviceIdx, Convert.ToInt32(df[0]), 1);
                                }
                                else
                                {
                                    ccl.SendMonitorTask(Convert.ToInt32(df[0]));
                                }
                            }
                            #endregion 双叉关联任务，能同步的同时报告完成；异步的直接执行关联的命令
                        }
                        break;
                    #endregion 堆垛机:
                    case 2:
                        #region 输送机
                        if ((States[1] == 1))//开始运行，设置T_Monitor_Task的F_Status=2// || (States[0] == 2)
                        {
                            //正在运行的设备如果有探物就是说托盘运行到此设备
                            ActionStartRun(DeviceIdx, TaskIdx);
                            #region 双叉关联任务，能同步的同时报告运行
                            devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
                            if (devinfo.IfCorrelDoubleFork == "1")
                            {
                                if (CGeneralFunction.DoubleForkIfSync(TaskIdx, DeviceIdx, 2) == true)
                                {
                                    string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                                    if (df != null)
                                    {
                                        ActionStartRun(Convert.ToInt32(df[2]), Convert.ToInt32(df[0]));
                                    }
                                }
                            }
                            #endregion 双叉关联任务，能同步的同时报告运行
                            //刷新监控中心显示
                        }
                        if (States[1] == 2)//报告完成
                        {
                            string[] df = CGeneralFunction.GetDoubleForkMonitorInfo(TaskIdx, DeviceIdx);
                            bool snyc = CGeneralFunction.DoubleForkIfSync(TaskIdx, DeviceIdx, 2);
                            devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
                            if (devinfo.IfCorrelDoubleFork == "1")
                            {
                                int updowndevice = new CommonService().GetUpAndDownDevices(DeviceIdx, devinfo.Dbw1Address);
                                if (-1 != updowndevice)
                                {
                                    GetKindDeviceState(0, updowndevice, 0);
                                }
                            }
                            ActionComplete(DeviceIdx, TaskIdx, 1);
                            //刷新监控中心显示
                            #region 双叉关联任务，能同步的同时报告完成；异步的直接执行关联的命令
                            if ((devinfo.IfCorrelDoubleFork == "1") && (df != null))
                            {
                                if (snyc == true)
                                {
                                    ActionComplete(DeviceIdx, Convert.ToInt32(df[0]), 1);
                                }
                                else
                                {
                                    ccl.SendMonitorTask(Convert.ToInt32(df[0]));
                                }
                            }
                            #endregion 双叉关联任务，能同步的同时报告完成；异步的直接执行关联的命令
                        }
                        break;
                    #endregion 输送机
                    case 4:
                        #region 穿梭车
                        if ((States[1] == 1)) //开始运行，设置T_Monitor_Task的F_Status=2// || (States[0] == 2)
                        {//正在运行的设备如果有探物就是说托盘运行到此设备
                            ActionStartRun(DeviceIdx, TaskIdx);
                            //刷新监控中心显示
                        }
                        if (States[1] == 2)//报告完成
                        {
                            ActionComplete(DeviceIdx, TaskIdx, 1);
                        }
                        break;
                    #endregion 穿梭车
                    case 32:
                        #region 拣选
                        if ((States[1] == 1))//开始运行，设置T_Monitor_Task的F_Status=2// || (States[0] == 2)
                        {//正在运行的设备如果有探物就是说托盘运行到此设备
                            ActionStartRun(DeviceIdx, TaskIdx);
                        }
                        if (States[1] == 2)//报告完成
                        {
                            ActionComplete(DeviceIdx, TaskIdx, 1);
                        }
                        break;
                    #endregion 拣选
                    case 33:
                        #region 贴标
                        if ((States[1] == 1))//开始运行，设置T_Monitor_Task的F_Status=2// || (States[0] == 2)
                        {//正在运行的设备如果有探物就是说托盘运行到此设备
                            ActionStartRun(DeviceIdx, TaskIdx);
                        }
                        if (States[1] == 2)//报告完成
                        {
                            ActionComplete(DeviceIdx, TaskIdx, 1);
                        }
                        break;
                    #endregion 贴标
                    case 34:
                        #region AGV
                        if ((States[1] == 1))//开始运行，设置T_Monitor_Task的F_Status=2// || (States[0] == 2)
                        {//正在运行的设备如果有探物就是说托盘运行到此设备
                            ActionStartRun(DeviceIdx, TaskIdx);
                        }
                        if (States[1] == 10)//将取报告完成
                        {
                            string sql = "select F_DeviceIndex from T_Monitor_Task where F_MonitorIndex=" + TaskIdx;

                            DataView dv = DbHelperSQL.Query(sql).Tables[0].DefaultView;

                            if (dv.Count > 0 && dv[0]["F_DeviceIndex"].ToString() == DeviceIdx.ToString())
                            {
                                ActionComplete(DeviceIdx, TaskIdx, 1);
                            }
                        }
                        break;
                        #endregion AGV
                }
                #endregion 状态处理
            }
        }

        /// <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 mti = ccf.GetManageTaskIndexfromMonitor(TaskIdx);
            int mtikind = ccf.GetManageTaskKindIndexFromMonitor(TaskIdx);

            DataView dvlane;
            DataView dv;
            try
            {
                //修改调度任务状态
                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_Status=2 where F_Status=1 and F_MonitorIndex=" + TaskIdx);

                #region 根据任务号和探物情况判断任务执行的位置回写本地管理表
                DbHelperSQL.ExecuteSql("update T_Manage_Task set FCurrentLocation=" + DeviceIdx + " where F_ManageTaskKindIndex=" + mtikind + " and FID=" + mti + "");
                //调度任务表也记录当前位置，主要是给输送机链用
                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_CurrentLocation=" + DeviceIdx + " where F_MonitorIndex=" + TaskIdx);
                //设备逻辑有物
                //20090918给堆垛机送货的输送机逻辑有物解锁F_HaveGoods=0
                dvlane = DbHelperSQL.Query("SELECT F_LaneGateDeviceIndex  FROM T_Base_Lane_Gate where F_LaneGateDeviceIndex=" + DeviceIdx).Tables[0].DefaultView;
                if (dvlane.Count > 0)
                {
                    DbHelperSQL.ExecuteSql("update T_Base_Device set F_HaveGoods=0 where F_DeviceIndex=" + DeviceIdx);
                }
                else
                {
                    //AGV暂无
                    dvlane = DbHelperSQL.Query("SELECT F_AGVGateDeviceIndex  FROM T_Base_AGV_Gate where F_AGVGateDeviceIndex=" + DeviceIdx).Tables[0].DefaultView;
                    if (dvlane.Count > 0)
                    {
                        DbHelperSQL.ExecuteSql("update T_Base_Device set F_HaveGoods=0 where F_DeviceIndex=" + DeviceIdx);
                    }
                }
                DbHelperSQL.ExecuteSql("update T_Base_Lane_Gate set F_LogicHave = 0 where F_LogicHave =" + TaskIdx);//清理堆垛机发送后给巷道出口设备置的指令号
                #endregion 根据任务号和探物情况判断任务执行的位置回写本地管理表

                if (CStaticClass.MovedDeviceAheadTrigger == "1")
                {
                    #region 判断是否存在提前触发任务(设备号－调度任务号) 堆垛机
                    //当设备运行时，触发调度任务号运行F_AheadTrigger
                    dv = DbHelperSQL.Query("select F_AheadTrigger from T_Monitor_Task " + "where F_MonitorIndex=" + TaskIdx + " and F_AheadTrigger like '" + DeviceIdx.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)
                            {
                                //清除触发命令
                                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_AheadTrigger ='' where F_MonitorIndex=" + TaskIdx);
                            }
                        }
                    }
                    #endregion 判断是否存在提前触发任务(设备号－调度任务号) 堆垛机
                }
            }
            catch (Exception ex)
            {
                _CGetStateError = "ControlSystem.CGetState发生错误：" + ex.Message;
            }
            finally
            {
                dvlane = null;
                dv = null;
            }
        }
        /// <summary>
        /// 报告完成
        ///电器反馈该设备的"完成"时 删除设备指令 , 解除设备表占用状态F_LockedState=0；
        ///路径明细表F_LockedDeviceIndex里的所有对应设备索引解锁
        ///
        ///判断是最后一个设备指令吗? 是,回写调度任务IO_Control的FSTATUS=2即"搬运完成";
        /// T_Manage_Task的正在执行状态FSTATUS=2 ；
        /// </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;
            }
            devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
            int devKind = BaseDeviceService.GetDeviceKindIdx(DeviceIdx);
            int[] zxy = ccf.GetCoordinatesFromMonitorTask(TaskIdx);
            string zxystr = "";
            if (zxy != null)
            {
                //送货点坐标
                zxystr = (zxy[3].ToString().Length == 1 ? "0" + zxy[3].ToString() : zxy[3].ToString()) + "-" + ((zxy[4].ToString().Length == 1) ? ("0" + zxy[4].ToString()) : (zxy[4].ToString())) + "-" + ((zxy[5].ToString().Length == 1) ? ("0" + zxy[5].ToString()) : (zxy[5].ToString()));
            }
            int order = ccf.GetDeviceOrderFromMonitor(TaskIdx);
            if (order == -1)
            {
                _CGetStateError = "电器反馈的调度任务号没有记忆！";
                return;
            }
            if (GetManage_Kind(TaskIdx) == false)
            {
                //没有调度任务 返回
                return;
            }
            LogUtil.WriteLog("", "电气任务报完成;DeviceIdx:" + DeviceIdx + ";TaskIdx:" + TaskIdx);

            int errrcode = new ManageTaskService().GetExceptionNOFromManageTask(_fid, _mti);
            //任务类型
            int ControlType = ccf.GetFCONTROLTASKTYPEFromManageTask(_mti, _fid);
            //20100710
            int AgvNextDeviceKind = 0;//设备类型
            if ((devKind == 6) && (order == 2))
            {
                AgvNextDeviceKind = BaseDeviceService.GetDeviceKindIdx(zxy[4]);
            }

            int ErrorCount = 0;
            DataView dvtemp = DbHelperSQL.Query("select F_ErrorCount from t_base_device where F_DeviceIndex=" + DeviceIdx).Tables[0].DefaultView;
            if (dvtemp.Count > 0)
            {
                if (dvtemp[0][0] == DBNull.Value)
                {
                    ErrorCount = 0;
                }
                else
                {
                    ErrorCount = ((int)dvtemp[0][0]);
                }
            }
            if (ErrorCount > 1)
            {
                //设备有异常将无法完成
                return;
            }
            DataView dvman;
            DataView dv;
            DataView dvlane;

            #region 出库优先携带入库优先策略的处理（入出库交替）
            if ((devKind == 1) && (ccf.GetFCONTROLTASKTYPEFromManageTask(_mti, _fid) == 2))//堆垛机出库优先并且携带入库任务
            {
                string mansql = "select * from T_Manage_Task where FTASKLEVEL=10 and FSTACK = " + DeviceIdx + " AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '1') ";
                dvman = DbHelperSQL.Query(mansql).Tables[0].DefaultView;
                if (dvman.Count <= 0)
                {
                    mansql = "SELECT FID, F_ManageTaskKindIndex, FCONTROLTASKTYPE FROM T_Manage_Task WHERE (FSTACK = " + DeviceIdx + ") AND (FCONTROLTASKTYPE = 1) AND (FIntoStepOK = '1') order by FTASKLEVEL desc, F_ManageTaskKindIndex desc,FID asc";
                    dvman = DbHelperSQL.Query(mansql).Tables[0].DefaultView;
                    for (int ii = 0; ii < dvman.Count; ii++)
                    {
                        string sql = "select * from T_Monitor_Task where F_ManageTASKKINDINDEX=" + dvman[ii]["F_ManageTASKKINDINDEX"] + " and F_ManageTaskIndex=" + dvman[ii]["FID"] + " order by F_MonitorIndex asc";
                        dv = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            int stackkind = BaseDeviceService.GetDeviceKindIdx(Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                            if (stackkind == 1)
                            {
                                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_MonitorTaskLevel=10 where F_ManageTASKKINDINDEX=" + dvman[ii]["F_ManageTASKKINDINDEX"] + " and F_ManageTaskIndex=" + dvman[ii]["FID"] + "");
                                DbHelperSQL.ExecuteSql("update T_Manage_Task set FTASKLEVEL=10 where F_ManageTASKKINDINDEX=" + dvman[ii]["F_ManageTASKKINDINDEX"] + " and FID=" + dvman[ii]["FID"] + "");
                                break;
                            }
                        }
                    }
                }
            }
            #endregion 出库优先携带入库优先策略的处理（入出库交替）

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            try
            {
                int fid = _fid;
                int mti = _mti;
                string BOX_LABLE = string.Empty;
                bool TASK_TYPE = false;

                #region [堆垛机任务]补充逻辑预约锁的解锁（此调度任务的此设备的最后一个命令需要解锁，有关联任务的改为关联任务预约）
                if (devKind == 1)
                {
                    object ob = DbHelperSQL.GetSingle("select count(F_MonitorIndex) as counts from T_Monitor_Task " +
                        " where F_ManageTaskIndex =" + fid + " and F_ManageTaskKindIndex= " + mti + " and F_DeviceIndex=" + DeviceIdx);
                    if (Convert.ToInt32(ob) == 1)//dzf同一任务的同一设备的最后一条指令
                    {
                        #region 有管理任务存在，增加关联任务预约锁//20100710
                        ob = DbHelperSQL.GetSingle("SELECT T_Manage_Task.FID FROM T_Manage_Task ,T_Monitor_Task where  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 = " + fid + ") AND (T_Manage_Task.F_ManageTaskKindIndex = " + mti + ") and F_DeviceIndex=" + DeviceIdx + "");
                        if (ob != null)
                        {
                            DbHelperSQL.ExecuteSql("update T_Base_Device set F_ManTaskReserve=" + (mti.ToString() + ob.ToString()) + " where F_ManTaskReserve=" + (mti.ToString() + fid.ToString()) + " and F_DeviceIndex=" + DeviceIdx);
                        }
                        else
                        {
                            DbHelperSQL.ExecuteSql("update T_Base_Device set F_ManTaskReserve=0 where F_ManTaskReserve=" + (mti.ToString() + fid.ToString()) + " and F_DeviceIndex=" + DeviceIdx);
                        }
                        #endregion 有管理任务存在，增加关联任务预约锁//20100710
                    }
                }
                #endregion [堆垛机任务]补充逻辑预约锁的解锁（此调度任务的此设备的最后一个命令需要解锁，有关联任务的改为关联任务预约）

                //dv = DbHelperSQL.Query("select count(F_MonitorIndex) as counts from T_Monitor_Task ").Tables[0].DefaultView;
                dv = DbHelperSQL.Query("select count(F_MonitorIndex) as counts from T_Monitor_Task " + " where F_ManageTaskIndex =" + fid + " and F_ManageTaskKindIndex= " + mti).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    #region 最后一个调度任务的处理
                    if ((Convert.ToInt32(dv[0]["counts"]) == 1))
                    {
                        //回写管理表//20091128
                        if ((ClearZero != CGeneralFunction.TASKDELETE) && (ClearZero != CGeneralFunction.TASKSTOPOUTPUT))//调度撤销删除调度任务900；人工暂停出库任务940
                        {
                            bool IS_PICKUP = true;
                            Object dt1 = DbHelperSQL.GetSingle("select F_DeviceCommandIndex from T_Monitor_Task");
                            if (dt1.ToString() == "9")
                            {
                                IS_PICKUP = false;
                            }
                            string Task_NO = "";
                            //固定路径模式
                            //调度任务的fid的最后一个监控分解任务完成
                            if (mti == 1)
                            {
                                //完成FSTATUS=999；970堆垛机送货重故障异常完成；980堆垛机取空故障异常完成；990条码扫描异常完成；
                                //调度撤销删除调度任务900;950送到拆盘机的不是空托盘组;940人工暂停出库任务
                                bool bResult = true;
                                string sResult = string.Empty;
                                DataView dvt = DbHelperSQL.Query("SELECT * FROM T_Manage_Task where F_ManageTaskKindIndex=" + mti + " and FID=" + fid + "").Tables[0].DefaultView;
                                DataView dv_task = DbHelperSQL.Query("select * from t_WareHouse").Tables[0].DefaultView;

                                //if (dv_task[0]["F_TASK_TYPE"].ToString() == "In" && dvt[0]["FENDDEVICE"].ToString()!="12001")
                                //{
                                //    TASK_TYPE = true;
                                //}
                                BOX_LABLE = dvt[0]["BOX_LABLE"].ToString();
                                Task_NO = dvt[0]["fmanageid"].ToString();
                                //flaneway任务所在巷道的设备索引
                                if (dvt[0]["flaneway"].ToString() != "-1")
                                {
                                    #region 盘点 出入库 堆垛机
                                    string IO_FLAG, LOC_NO;

                                    {
                                        if (dvt[0]["FSTARTCELL"].ToString() == "-")
                                        {
                                            //入库
                                            IO_FLAG = "02";
                                            LOC_NO = dvt[0]["FENDCELL"].ToString();
                                        }
                                        else
                                        {
                                            IO_FLAG = "01";
                                            LOC_NO = dvt[0]["FSTARTCELL"].ToString();

                                            //出库时候由输送线上报完成 入库时候agv报完成
                                            bResult = (new uploadStackIODet()).Notify(dvt[0]["fmanageid"].ToString(), IO_FLAG, LOC_NO, out sResult);
                                            if (!bResult)
                                            {
                                                throw new Exception("接口调用失败。" + DateTime.Now.ToString() + "\r\n接口：uploadStackIODet。任务编号：" + TaskIdx + "\r\n错误信息：" + sResult);
                                            }
                                        }
                                    }
                                    #endregion 盘点 出入库 堆垛机
                                }

                                //更新叠盘机箱标签
                                if (dvt[0]["FENDDEVICE"].ToString() == CConfig.Device_Stacker.ToString())
                                {
                                    if (dvt[0]["BOX_LABLE"].ToString().Contains("IS_RESTACK"))
                                    {
                                        DbHelperSQL.ExecuteSql("update T_Base_PLC_Ask set F_BOX_LABLE='" + dvt[0]["BOX_LABLE"].ToString().Replace("IS_RESTACK|", "") + "' where (F_BindingDevice=" + DeviceIdx + ")");
                                    }
                                    else
                                    {
                                        DbHelperSQL.ExecuteSql("update T_Base_PLC_Ask set F_BOX_LABLE='" + dvt[0]["BOX_LABLE"].ToString() + "' where (F_BindingDevice=" + DeviceIdx + ")");
                                    }
                                }

                                // 任务终点是射频门,软启动射频
                                if (zxy != null && (zxy[3] == CConfig.Device_Rfid))
                                {
                                    DbHelperSQL.ExecuteSql("update IO_RFID set BEGIN_TIME='" + DateTime.Now.ToString() + "',SOURCE_CELL_CODE='" + dvt[0]["FSTARTCELL"] + "',box_barcode='" + dvt[0]["FPALLETBARCODE"] + "' where (STATION_CODE='" + zxy[3] + "')");
                                }
                                if (!bResult)
                                {
                                    bResult = (new uploadWhExceptionInfo()).Notify(DeviceIdx.ToString(), devinfo.DeviceName, sResult, DateTime.Now.ToString(), out sResult);
                                    if (!bResult)
                                    {
                                        throw new Exception("接口调用失败。" + DateTime.Now.ToString() + "\r\n接口：uploadWhExceptionInfo。任务编号：" + TaskIdx + "\r\n错误信息：" + sResult);
                                    }
                                    ErrorCountAdd(DeviceIdx);
                                }
                                else
                                {//处理成功，清除设备故障计数
                                    DbHelperSQL.ExecuteSql("update t_base_device set F_ErrorCount=0 where F_DeviceIndex=" + DeviceIdx);
                                }
                            }
                            ReturnManageInfo(fid, mti, true);
                        }
                        else
                        {
                            ReturnManageInfo(fid, mti, false);
                        }
                    }
                    #endregion
                }

                //被这个任务号锁定的设备全部解锁
                DbHelperSQL.ExecuteSql("update T_Base_Device set F_LockedState=0 where F_LockedState=" + TaskIdx);
                DbHelperSQL.ExecuteSql("update T_Base_Device set F_CreateLock='0' where F_DeviceIndex=" + DeviceIdx);
                if (ClearZero != CGeneralFunction.TASKDELETE)//20100710删除调度任务不置逻辑有物
                {
                    //堆垛机接货输送机完成时逻辑无货20100710
                    dvlane = DbHelperSQL.Query("SELECT F_LaneGateDeviceIndex  FROM T_Base_Lane_Gate where F_LaneGateDeviceIndex=" + DeviceIdx).Tables[0].DefaultView;
                    if (dvlane.Count > 0)
                    {
                        DbHelperSQL.ExecuteSql("update T_Base_Device set F_HaveGoods=0 where F_DeviceIndex=" + DeviceIdx + " and F_HaveGoods=1");
                    }
                    else
                    {
                        //AGV接货输送机完成时逻辑无货20100710
                        dvlane = DbHelperSQL.Query("SELECT F_AGVGateDeviceIndex  FROM T_Base_AGV_Gate where F_AGVGateDeviceIndex=" + DeviceIdx).Tables[0].DefaultView;
                        if (dvlane.Count > 0)
                        {
                            DbHelperSQL.ExecuteSql("update T_Base_Device set F_HaveGoods=0 where F_DeviceIndex=" + DeviceIdx);
                        }
                    }
                    //根据出口巷道设备里面置的指令号来置逻辑无货
                    DataView dvj = DbHelperSQL.Query("select F_LaneGateDeviceIndex from T_Base_Lane_Gate where F_LogicHave =" + TaskIdx).Tables[0].DefaultView;
                    if (dvj.Count > 0)
                    {
                        DbHelperSQL.ExecuteSql("update T_Base_Device set F_HaveGoods=0 where F_DeviceIndex='" + dvj[0]["F_LaneGateDeviceIndex"] + "'");
                        DbHelperSQL.ExecuteSql("update T_Base_Lane_Gate set F_LogicHave = 0 where F_LogicHave =" + TaskIdx);// 清除出口巷道设备里面置的指令号
                    }
                }

                #region 堆垛机、AGV逻辑有物的处理20101011
                if (ClearZero != CGeneralFunction.TASKDELETE)//删除调度任务不置为逻辑有物
                {
                    if ((devKind == 1) && ((order == 4) || (order == 5) || (order == 6)))//20101011 4取5送
                    {
                        bool sh = false;//20101011
                        if (order == 5) sh = true;//20101011
                        if (sh == true)//20101011
                        {
                            //20090918给堆垛机送货的输送机增加逻辑有物
                            ////20100609改为使用巷道表关联
                            dvlane = DbHelperSQL.Query("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_Lane_Gate.F_ZXY='" + zxystr + "' " +
                                "  and T_Base_LaneInfo.F_StackIndex=" + DeviceIdx).Tables[0].DefaultView;
                            if (dvlane.Count > 0)
                            {
                                //dbo.ExceSQL("update T_Base_Device set F_HaveGoods=1 where F_DeviceIndex=" + dvlane[0]["F_LaneGateDeviceIndex"]);
                                DataView dvv = DbHelperSQL.Query("select F_MonitorIndex from T_Monitor_Task where F_ManageTaskIndex =" + fid + "and F_MonitorIndex>" + TaskIdx + "order by F_MonitorIndex asc").Tables[0].DefaultView;//增加 将出库堆垛机送出后的下一条指令号写在出口巷道设备里面
                                if (dvv.Count > 0)
                                {
                                    DbHelperSQL.ExecuteSql("update T_Base_Lane_Gate set F_LogicHave = '" + dvv[0]["F_MonitorIndex"] + "'  where F_LaneGateDeviceIndex =" + dvlane[0]["F_LaneGateDeviceIndex"]);
                                }
                            }
                        }
                    }
                    else if ((devKind == 6) && (order == 2) && (AgvNextDeviceKind == 2))//AGV向输送机放货20100710
                    {
                        DbHelperSQL.ExecuteSql("update T_Base_Device set F_HaveGoods=1 where F_DeviceIndex=" + zxy[4]);
                    }
                }

                #endregion

                #region 向设备发送清零命令
                if (ClearZero == 1)
                {
                    sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                    if ((devKind == 34) || (devKind == 2) || (devKind == 32) || (devKind == 33))
                    {
                        //输送机、RGV故障清零
                        if (zxy != null && (DeviceIdx == CConfig.Device_Stacker))
                        {
                            //叠盘机上箱标签
                            DataView dv_plc_ask = DbHelperSQL.Query("select * from t_base_plc_ask where f_bindingdevice=" + DeviceIdx).Tables[0].DefaultView;
                            //到此叠盘机的任务
                            DataView dv_manage_other = DbHelperSQL.Query("select * from t_manage_task where FENDDEVICE=" + DeviceIdx).Tables[0].DefaultView;
                            LogUtil.WriteLog("", "TaskIdx:" + TaskIdx + ";GetState_叠盘机缓存:" + dv_plc_ask[0]["F_BarCode"].ToString() + ";叠盘机尾箱标签:" + dv_plc_ask[0]["F_BOX_LABLE"].ToString());
                            //输送线有到叠盘的任务 且 叠盘机有缓存（实际完成当前箱并未修改） 且 剩余任务标签与叠盘机最后标签不一致 dv_plc_ask[0]["F_BarCode"].ToString() != ""
                            //只要出现IS_RESTACK 必定不与缓存一致
                            if (dv_manage_other.Count > 0 && (1 == 1 && dv_manage_other[0]["BOX_LABLE"].ToString() != dv_plc_ask[0]["F_BOX_LABLE"].ToString()))
                            {
                                //有执行中任务，且，第一条标签不同
                                //sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                                //Thread.Sleep(100);
                                sdo.SendDeviceOrder(3, 0, 0, DeviceIdx, 0);
                                LogUtil.WriteLog("", "TaskIdx:" + TaskIdx + ";任务完成叠盘放行;箱号:" + new MonitorTaskService().GetBarCodeFromMonitor(TaskIdx) + ";当前任务标签: " + dv_manage_other[0]["BOX_LABLE"].ToString());
                            }
                            else
                            {
                                sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                                LogUtil.WriteLog("", "TaskIdx:" + TaskIdx + ";任务完成叠盘应答;箱号:" + new MonitorTaskService().GetBarCodeFromMonitor(TaskIdx));
                                //}
                            }
                        }
                        else
                        {
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                        }
                    }
                    else if (devKind == 1) //堆垛机
                    {
                        sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                    }
                }
                #endregion

                // 每次叠盘任务完成时更新叠盘机条码信息
                if (zxy != null && zxy[3] == 12003)
                {
                    DbHelperSQL.ExecuteSql("update T_Base_PLC_Ask set F_BarCode=F_BarCode +'" + ccf.GetBarCodeFromMonitor(TaskIdx) + "|' where (F_BindingDevice=" + DeviceIdx + ")");
                }

                DbHelperSQL.ExecuteSql("delete from T_Monitor_Task  where F_MonitorIndex=" + TaskIdx);
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("报告完成时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "报告完成时：" + ex.Message, true);
                }
                ErrorCountAdd(DeviceIdx);
                LogUtil.WriteLog("", "Error:" + ex.Message + "-" + ex.Source);
                //throw ex;
            }
            finally
            {
                dvman = null;
                dv = null;
                dvlane = null;
            }
        }
        private void ErrorCountAdd(int DeviceIndex)
        {
            int ErrorCount = 0;
            DataView dv = DbHelperSQL.Query("select F_ErrorCount from t_base_device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0][0] == DBNull.Value)
                {
                    ErrorCount = 1;
                }
                else
                {
                    ErrorCount = ((int)dv[0][0]) + 1;
                }
            }
            DbHelperSQL.ExecuteSql("update t_base_device set F_ErrorCount=" + ErrorCount + " where F_DeviceIndex=" + DeviceIndex);
        }

        /// <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)
        {
            DataView dvmon;
            DataTable dt;
            DataView dv0;
            try
            {
                //090915
                string monsql = "SELECT F_MonitorIndex FROM T_Monitor_Task where  F_Status =1 and F_DeviceIndex =" + DeviceIdx;
                //20100108
                dvmon = DbHelperSQL.Query(monsql).Tables[0].DefaultView;
                if ((dvmon.Count > 0) && (TaskIdx == 0))
                {
                    TaskIdx = Convert.ToInt32(dvmon[0]["F_MonitorIndex"]);
                }
                //090915
                //有过记录的故障设备的任务号，不再重复处理
                string devstr = "SELECT F_DeviceIndex FROM T_Base_Device where F_DeviceIndex=" + DeviceIdx + " and F_ErrorTaskNo=" + TaskIdx + "";
                //20100108
                dt = DbHelperSQL.Query(devstr).Tables[0];
                if (dt.Rows.Count >= 1)
                {
                    DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_Status= " + ErrId + "  where (F_MonitorIndex= " + TaskIdx + ") and ((F_Status<> " + ErrId + ") and (F_Status<> 3))");
                    return;
                }
                devinfo = BaseDeviceService.GetDeviceInfo(DeviceIdx);
                int devKind = BaseDeviceService.GetDeviceKindIdx(DeviceIdx);

                if (GetManage_Kind(TaskIdx) == false) return;
                int fid = _fid;
                int mti = _mti;
                //string fwarehouse = "";
                //string fcode = "";
                //int flane = 0;
                errs = BaseDeviceService.GetErrorInfo(Convert.ToInt32(devKind.ToString() + ErrId.ToString()));

                if (errs.ErrorIndex > 0)
                {
                    FrmMain.FormInstance.notifyIcon1.BalloonTipText = "警告:" + devinfo.DeviceName + "," + DeviceIdx + "发生故障：" + errs.ErrorName;
                    FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", devinfo.DeviceName + "," + DeviceIdx + "发生故障：" + errs.ErrorName, System.Windows.Forms.ToolTipIcon.Warning);
                    if (mti == 1)
                    {
                        string sResult;
                        RGD.MdsAPI.WMS.uploadWhExceptionInfo ss = new RGD.MdsAPI.WMS.uploadWhExceptionInfo();
                        ss.Notify(DeviceIdx.ToString(), devinfo.DeviceName, errs.ErrorName, DateTime.Now.ToString(), out sResult);
                    }
                    //20100108
                    dv0 = DbHelperSQL.Query("SELECT F_DeviceIndex, F_ErrorIndex FROM T_Base_Device_Error_Log Where F_ManageTaskNo=" + fid + " and F_DeviceIndex=" + DeviceIdx + " and F_ErrorIndex=" + errs.ErrorIndex).Tables[0].DefaultView;
                    string dtime = DateTime.Now.ToString("u");//20110603

                    dtime = dtime.Substring(0, dtime.Length - 1);
                    if (dv0.Count > 0)
                    {//20091107
                        DbHelperSQL.ExecuteSql("UPDATE T_Base_Device_Error_Log SET F_DateTime ='" + dtime + "'  Where F_DeviceIndex=" + DeviceIdx + " and F_ErrorIndex=" + errs.ErrorIndex + " and F_ManageTaskNo=" + fid);
                    }
                    else
                    {
                        DbHelperSQL.ExecuteSql("INSERT INTO T_Base_Device_Error_Log (F_ManageTaskNo,F_DeviceIndex, F_ErrorIndex, F_DateTime) VALUES (" + fid + "," + DeviceIdx + "," + errs.ErrorIndex + ",'" + dtime + "')");
                    }
                }
                //20090915
                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_Status= " + ErrId + "  where F_MonitorIndex= " + TaskIdx + " and (F_Status<> 3)");
                //记录发生故障的设备正在执行的任务号
                DbHelperSQL.ExecuteSql("update T_Base_Device set F_ErrorTaskNo= " + TaskIdx + "  where F_DeviceIndex= " + DeviceIdx);
                DbHelperSQL.ExecuteSql("update T_Manage_Task set FERRORCODE='" + devinfo.DeviceName + "," + DeviceIdx + errs.ErrorName + "' where F_ManageTaskKindIndex=" + mti + " and FID=" + fid);

                if (devinfo.UseCommonDB == "1")
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("向管理反馈设备错误时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "向管理反馈设备错误时：" + ex.Message, true);
                }
            }
            finally
            {//20100108
                dvmon = null;
                dt = null;
                dv0 = null;
            }
        }

        public bool GetManage_Kind(int taskidx)
        {//20100108
            DataSet ds;
            try
            {
                //CCommonFunction ccf=new CCommonFunction();
                ds = DbHelperSQL.Query("SELECT F_ManageTaskIndex, T_Monitor_Task.F_ManageTaskKindIndex, F_MonitorIndex,FSTARTCELL,FMANAGEID FROM T_Monitor_Task,T_Manage_Task Where F_ManageTaskIndex=FID and F_MonitorIndex=" + taskidx);
                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"]);
                    _start_cell = ds.Tables[0].DefaultView[0]["FSTARTCELL"].ToString();
                    _fmanageid = ds.Tables[0].DefaultView[0]["FMANAGEID"].ToString();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {//20100108
                ds = null;
            }
        }

        //刷新监控中心显示
        public void RefreshControlMonitor(int devidx)
        {//_States[5] == DeviceIdx
            try
            {
                if (CStaticClass.RealRefresh == true)
                {
                    //显示设备指令
                    DataSet ds = DbHelperSQL.Query("select * from V_Monitor_Task where " + CStaticClass.Monstatus);
                    FrmControlMonitor.FormInstance.MonitorRefresh(ds.Tables[0].DefaultView);
                    //显示调度任务
                    FrmControlMonitor.FormInstance.ManagerRefresh(
                        DbHelperSQL.Query("select * from V_Manage_Task where " + CStaticClass.Manstatus).Tables[0].DefaultView);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 增加货位记录
        /// </summary>
        /// <param name="fid"></param>
        /// <param name="mti"></param>
        /// <param name="IFOK"></param>
        public void ReturnManageInfo(int fid, int mti, 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;
            try
            {
                //200906240111增加货位记录:入库1-结束位置有货；出库2-起始位置无货；倒库3-起始位置无货，结束位置有货
                //20100108
                dv = DbHelperSQL.Query("SELECT * FROM T_Manage_Task where F_ManageTaskKindIndex=" + mti + " and FID=" + fid + "").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);
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FRUNSTATUS=0,FCELLSTATUS = 1,FPALLETBARCODE='" + dv[0]["FPALLETBARCODE"] + "' WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + " and F_Z='" +
                                    fcc[0] + "' and F_X='" + fcc[1] + "' and F_Y='" + fcc[2] + "')");
                                }
                                break;

                            case "2":
                                {
                                    if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                    {
                                        fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                        DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FRUNSTATUS=0,FCELLSTATUS =0,FPALLETBARCODE='-' WHERE (FLaneWay=" + dv[0]["FSTARTDEVICE"] + "  and F_Z=" +
                                        fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                    }
                                }
                                break;

                            case "3":
                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);//FRUNSTATUS=0,
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FCELLSTATUS = 1,FPALLETBARCODE='" + dv[0]["FPALLETBARCODE"] + "'  WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + " and F_Z=" +
                                    fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FBIAOZHI =1 WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + "  and F_Z=" +
                                    fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                }
                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);//FRUNSTATUS=0,
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FCELLSTATUS =0,FPALLETBARCODE='-'  WHERE (FLaneWay=" + dv[0]["FSTARTDEVICE"] + "  and F_Z=" +
                                    fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                }

                                break;

                            default:
                                break;
                        }
                        //20101028
                        DbHelperSQL.ExecuteSql("update T_Manage_Task set FSTATUS=999,FENDTIME='" + dtime + "'  where  FID=" + fid + " and F_ManageTaskKindIndex= " + mti);
                    }
                    else
                    {
                        switch (dv[0]["FCONTROLTASKTYPE"].ToString())
                        {
                            case "1":
                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE='' WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + " and F_Z='" +
                                    fcc[0] + "' and F_X='" + fcc[1] + "' and F_Y='" + fcc[2] + "')");
                                }
                                break;

                            case "2":
                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE='" + dv[0]["FPALLETBARCODE"] + "' WHERE (FLaneWay=" + dv[0]["FSTARTDEVICE"] + "  and F_Z=" +
                                    fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                }
                                break;

                            case "3":
                                if (dv[0]["FENDCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FENDCELL"].ToString().Split(cc);
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE=''  WHERE (FLaneWay=" + dv[0]["FENDDEVICE"] + " and F_Z=" +
                                    fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                }
                                if (dv[0]["FSTARTCELL"].ToString().IndexOf("-") > 0)//20100905
                                {
                                    fcc = dv[0]["FSTARTCELL"].ToString().Split(cc);
                                    DbHelperSQL.ExecuteSql("UPDATE ST_CELL SET FRUNSTATUS=0,FPALLETBARCODE='" + dv[0]["FPALLETBARCODE"] + "'  WHERE (FLaneWay=" + dv[0]["FSTARTDEVICE"] + "  and F_Z=" +
                                    fcc[0] + " and F_X=" + fcc[1] + " and F_Y=" + fcc[2] + ")");
                                }

                                break;

                            default:
                                break;
                        }
                        //20101028
                        DbHelperSQL.ExecuteSql("update T_Manage_Task set FSTATUS=900,FENDTIME='" + dtime + "'  where  FID=" + fid + " and F_ManageTaskKindIndex= " + mti);
                    }
                }
                DbHelperSQL.ExecuteSql("delete from T_Manage_Task where  FID=" + fid + " and F_ManageTaskKindIndex= " + mti);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv = null;
            }
        }

        /// <summary>
        /// 追加倒库货位至真实终点货位的取货和送货指令
        /// </summary>
        /// <param name="mti">任务类型</param>
        /// <param name="fid">调度任务索引</param>
        /// <param name="device">设备索引</param>
        /// <param name="monitorindex">设备指令索引</param>
        private void AppendMoveCellOperate(int mti, int fid, int device, int monitorindex)
        {
            //获取管理任务送货坐标，当前调度任务的路径，条码，优先级；远近货叉，提前检测
            string manzxy = DbHelperSQL.GetSingle("SELECT FENDCELL FROM T_Manage_Task WHERE (FID = " + fid + ") AND (F_ManageTaskKindIndex = " + mti + ")").ToString();
            char[] cc = new char[1] { '-' };
            string[] spcell = manzxy.Split(cc);
            string newuseawayfork;
            DataView dv = DbHelperSQL.Query("select F_NumParam4, F_NumParam5,F_NumParam6, F_RouteID,F_MonitorTaskLevel, F_UseAwayFork, F_TxtParam from T_Monitor_Task where F_MonitorIndex=" + monitorindex).Tables[0].DefaultView;
            if (dv[0]["F_UseAwayFork"].ToString() == "1")
            {
                newuseawayfork = "0";
            }
            else
            {
                newuseawayfork = "1";
            }
            DbHelperSQL.ExecuteSql("update T_Manage_Task set FExceptionNO=NULL,FUseAwayFork='" + newuseawayfork + "' where F_ManageTaskKindIndex=" + mti + " and FID=" + fid);

            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 aheaddetect=;
            int mindex = ccf.GetMonitorIndex(fid, mti);
            DbHelperSQL.ExecuteSql("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel," +
                " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5," +
                " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork)VALUES " +
                "(" + fid + "," + mti + "," + mindex + "," + lev + "," + device + ",4," + routeid + ",0," + fnp1 + "," + fnp2 + "," + fnp3 + "," +
                spcell[0] + "," + spcell[1] + "," + spcell[2] + ",'" + pcode + "',NULL,'" + newuseawayfork + "')");
            mindex = ccf.GetMonitorIndex(fid, mti);
            DbHelperSQL.ExecuteSql("INSERT INTO T_Monitor_Task (F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex, F_MonitorTaskLevel," +
                " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam2, F_NumParam3, F_NumParam4, F_NumParam5," +
                " F_NumParam6, F_TxtParam, F_AheadDetect, F_UseAwayFork)VALUES " +
                "(" + fid + "," + mti + "," + mindex + "," + lev + "," + device + ",5," + routeid + ",0," + fnp1 + "," + fnp2 + "," + fnp3 + "," +
                spcell[0] + "," + spcell[1] + "," + spcell[2] + ",'" + pcode + "',NULL,'" + newuseawayfork + "')");
        }
    }
}