using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DBFactory;
using System.Threading;
using Microsoft.VisualBasic;
using System.Windows.Forms;
using static ControlSystem.CreateMonitor;
using System.Data.SqlTypes;
using System.Linq;

namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 获取调度任务
    /// </summary>
    public static class CObtainTask
    {
        static CGetState cgs = new CGetState();
        static CCommonFunction ccf = new CCommonFunction();
        static Thread mythread;
        static bool exitThread = false;//20091107
        static Model.MDevice devinfo;
        private static void BeginListen()
        {//20091107
            while (!exitThread )
            {
                try
                {
                    GetManagerTask();
                    
                }
                catch (Exception  ex)
                {
                    _CObtainTaskError = ex.Message;
                }
            }
        }
        public static void EndListen()
        {//20091107
            exitThread = true;
            
            if (mythread != null)
            {
                
                dbo.Close();
                dboM.Close();
                mythread.Abort();
                mythread = null;
            }
        }
        public static void StartListen()
        {
            exitThread = false;
            mythread = new Thread(new ThreadStart(BeginListen));
            mythread.IsBackground = true;
            mythread.Start();
        }

        static string _CObtainTaskError="";

        public static string CObtainTaskError
        {
            get { return _CObtainTaskError; }
            set { _CObtainTaskError = value; }
        }
        static DBOperator dbo = new DBOperator();
        static DBOperator dboM = new DBOperator("ManConnString", "ManDBFactory");
        public static int IsInv = 0;//是否是盘库 0 不是  1是盘库
        /// <summary>
        /// 获得调度任务
        /// </summary>
        public static int GetManagerTask()
        {
            //是否考虑同时读取IO_CONTROLDETAIL表的数据到本地数据库
            DataSet dsIOC ;
            DataView dvIOC;
            
            DataView dv;
            DataView dvnew;
            DataView dvmi;
            DataView DMAN;
            DataView dvc;
            string[] wv = new string[1] { "2" };
            string[] witemnames = new string[1];
            object obj = null;
            try
            {
                int RecCount = 0;
                //等待执行的；已批复的申请改道的

                string sql = "select * from IO_CONTROL where ((CONTROL_STATUS=" + Model.CGeneralFunction.TASKWAIT + ") or (CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEREPLY + ")) " + " order by CONTROL_TASK_LEVEL desc,CONTROL_ID asc";

                dsIOC = dboM.ExceSQL(sql);
                dvIOC = dsIOC.Tables[0].DefaultView;
                //string sstite, estite;
                if (dvIOC.Count > 0)
                {
                     string FENDCELL = ""; char[] cc = new char[1] { '-' };
                     int FENDDEVICE = 0;
                    for (int i = 0; i < dvIOC.Count; i++)
                    {
                        #region 任务暂停和恢复
                        ////20091128
                        //if ((dvIOC[i]["CONTROL_STATUS"].ToString() == "0") && (dvIOC[i]["CONTROL_ISRETURN"].ToString() == "3"))
                        //{//任务恢复
                        //    dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK=0 where (FID = " + Convert.ToInt32(dvIOC[i]["FID"]) + ") AND (F_ManageTASKKINDINDEX =1) and (FIntoStepOK='-')");
                        //    dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //    continue;
                        //}
                        //if ((dvIOC[i]["CONTROL_STATUS"].ToString() == "0") && (dvIOC[i]["CONTROL_ISRETURN"].ToString() == "2"))
                        //{   //未拆分的任务暂停
                        //    int rs = dbo.ExecuteSql("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) and (FIntoStepOK='0')");
                        //    if (rs == 0)
                        //    {
                        //        //已拆分未执行的任务暂停
                        //        dvMT = dbo.ExceSQL("select fid from T_Manage_Task  where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) and (FIntoStepOK='1') and (FSTATUS=0)").Tables[0].DefaultView;
                        //        if (dvMT.Count > 0)
                        //        {
                        //            dbo.ExceSQL("delete from T_Monitor_Task where (F_ManageTaskIndex= " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //            dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");

                        //        }

                        //    }
                        //    //dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //    continue;
                        //}
                        //else
                        //{
                        //    //上报管理FSTATUS=940
                        //    #region 正在执行的任务暂停
                        //    if (dvIOC[i]["CONTROL_ISRETURN"].ToString() == "2")
                        //    {
                        //        //正在执行的任务暂停
                        //        dvMT = dbo.ExceSQL("select fid from T_Manage_Task  where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) and (FIntoStepOK='1') and (FSTATUS>0)").Tables[0].DefaultView;
                        //        if (dvMT.Count > 0)
                        //        {
                        //            //只有暂停“正在运行的堆垛机非送货指令”或者“等待执行的堆垛机送货指令”，输送机无法暂停
                        //            dvMT = dbo.ExceSQL("select F_MonitorIndex,F_Status,F_DeviceIndex,F_DeviceCommandIndex from T_Monitor_Task where (F_ManageTaskIndex= " +
                        //                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) order by F_MonitorIndex asc").Tables[0].DefaultView;
                        //            if (dvMT.Count > 0)
                        //            {
                        //                if (ccf.GetDeviceKindIdx(Convert.ToInt32(dvMT[0]["F_DeviceIndex"])) == 1)
                        //                {
                        //                    if ((dvMT[0]["F_DeviceCommandIndex"].ToString() == "5") && (Convert.ToInt32(dvMT[0]["F_Status"]) == 0))
                        //                    {//等待执行的堆垛机送货指令可以改道原货位
                        //                        dbo.ExceSQL("update T_Manage_Task set  FExceptionNO='940' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");

                        //                        dbo.ExceSQL("update T_Monitor_Task set F_AheadDetect='',F_NumParam4=F_NumParam1,F_NumParam5=F_NumParam2,F_NumParam6=F_NumParam3 where F_MonitorIndex=" + dvMT[0]["F_MonitorIndex"]);
                        //                        dbo.ExceSQL("update T_Monitor_Task set F_Status=-1 where F_MonitorIndex>" + dvMT[0]["F_MonitorIndex"]
                        //                            + " and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                        dvMT = dbo.ExceSQL("select * from T_Monitor_Task  where F_Status=-1 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"])).Tables[0].DefaultView;
                        //                        for (int ii = 0; ii < dvMT.Count; ii++)
                        //                        {
                        //                            cgs.ActionComplete(Convert.ToInt32(dvMT[ii]["F_DeviceIndex"]), Convert.ToInt32(dvMT[ii]["F_MonitorIndex"]), 900);
                        //                        }
                        //                        dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                        //dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                    }
                        //                    else if (dvMT[0]["F_DeviceCommandIndex"].ToString() == "2")
                        //                    {//正在执行堆垛机将取指令，后续任务都取消；等待执行的堆垛机将取指令和后续任务都取消
                        //                        dbo.ExceSQL("update T_Manage_Task set  FExceptionNO='940' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                        dbo.ExceSQL("update T_Monitor_Task set F_Status=-1 where F_MonitorIndex>=" + dvMT[0]["F_MonitorIndex"]
                        //                            + " and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                        dvMT = dbo.ExceSQL("select * from T_Monitor_Task  where F_MonitorIndex>=" + dvMT[0]["F_MonitorIndex"]
                        //                            + " and F_Status=-1 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"])).Tables[0].DefaultView;
                        //                        for (int ii = 0; ii < dvMT.Count; ii++)
                        //                        {
                        //                            cgs.ActionComplete(Convert.ToInt32(dvMT[ii]["F_DeviceIndex"]), Convert.ToInt32(dvMT[ii]["F_MonitorIndex"]), 900);
                        //                        }
                        //                        dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                        //dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                    }
                        //                    else if (dvMT[0]["F_DeviceCommandIndex"].ToString() == "4")
                        //                    {//正在执行堆垛机取货指令，后续任务都改道原货位；等待执行的堆垛机取货指令和后续任务都取消
                        //                        dbo.ExceSQL("update T_Manage_Task set  FExceptionNO='940' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                        if (Convert.ToInt32(dvMT[0]["F_Status"]) >= 1)
                        //                        {
                        //                            dbo.ExceSQL("update T_Monitor_Task set F_AheadDetect='',F_NumParam4=F_NumParam1,F_NumParam5=F_NumParam2,F_NumParam6=F_NumParam3 where F_MonitorIndex>" +
                        //                                dvMT[0]["F_MonitorIndex"] + " and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                            //删除送货之后的输送机任务
                        //                            dvSend = dbo.ExceSQL("select F_MonitorIndex from T_Monitor_Task where F_DeviceIndex=" + dvMT[0]["F_DeviceIndex"]
                        //                                + " and F_DeviceCommandIndex=5 and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"])).Tables[0].DefaultView;
                        //                            if (dvSend.Count > 0)
                        //                            {
                        //                                dbo.ExceSQL("update T_Monitor_Task set F_Status=-1 where F_MonitorIndex>" + dvSend[0]["F_MonitorIndex"]
                        //                            + " and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                                dvMT = dbo.ExceSQL("select * from T_Monitor_Task  where F_MonitorIndex>" + dvSend[0]["F_MonitorIndex"]
                        //                                + " and F_Status=-1 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"])).Tables[0].DefaultView;
                        //                                for (int ii = 0; ii < dvMT.Count; ii++)
                        //                                {
                        //                                    cgs.ActionComplete(Convert.ToInt32(dvMT[ii]["F_DeviceIndex"]), Convert.ToInt32(dvMT[ii]["F_MonitorIndex"]), 900);
                        //                                }
                        //                            }
                        //                            //dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                        }
                        //                        else if (dvMT[0]["F_Status"].ToString() == "0")
                        //                        {
                        //                            dbo.ExceSQL("update T_Monitor_Task set F_Status=-1 where F_MonitorIndex>=" + dvMT[0]["F_MonitorIndex"]
                        //                            + " and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                            dvMT = dbo.ExceSQL("select * from T_Monitor_Task  where F_MonitorIndex>=" + dvMT[0]["F_MonitorIndex"]
                        //                            + " and F_Status=-1 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["FID"])).Tables[0].DefaultView;
                        //                            for (int ii = 0; ii < dvMT.Count; ii++)
                        //                            {
                        //                                cgs.ActionComplete(Convert.ToInt32(dvMT[ii]["F_DeviceIndex"]), Convert.ToInt32(dvMT[ii]["F_MonitorIndex"]), 900);
                        //                            }
                        //                            //dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                        }
                        //                        dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                    }
                        //                    else if (dvMT[0]["F_DeviceCommandIndex"].ToString() == "3")
                        //                    {//正在执行堆垛机将送指令，后续任务都改道原货位；等待执行的堆垛机将送指令和后续任务都改道原货位
                        //                        dbo.ExceSQL("update T_Manage_Task set  FExceptionNO='940' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                        if (dvMT[0]["F_Status"].ToString() == "0")
                        //                        {
                        //                            dbo.ExceSQL("update T_Monitor_Task set F_AheadDetect='',F_NumParam4=F_NumParam1,F_NumParam5=F_NumParam2,F_NumParam6=F_NumParam3 where F_MonitorIndex>=" +
                        //                                dvMT[0]["F_MonitorIndex"] + " and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                            //dboM.ExceSQL("update IO_CONTROL set  CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                        }
                        //                        else if (Convert.ToInt32(dvMT[0]["F_Status"]) >= 1)
                        //                        {
                        //                            dbo.ExceSQL("update T_Monitor_Task set F_AheadDetect='',F_NumParam4=F_NumParam1,F_NumParam5=F_NumParam2,F_NumParam6=F_NumParam3 where F_MonitorIndex>" +
                        //                                dvMT[0]["F_MonitorIndex"] + " and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                            //dboM.ExceSQL("update IO_CONTROL set CONTROL_ISRETURN=0 where CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                        }
                        //                        //删除送货之后的输送机任务
                        //                        dvSend = dbo.ExceSQL("select F_MonitorIndex from T_Monitor_Task where F_DeviceIndex=" + dvMT[0]["F_DeviceIndex"]
                        //                                + " and F_DeviceCommandIndex=5 and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"])).Tables[0].DefaultView;
                        //                        if (dvSend.Count > 0)
                        //                        {
                        //                            dbo.ExceSQL("update T_Monitor_Task set F_Status=-1 where F_MonitorIndex>" + dvSend[0]["F_MonitorIndex"]
                        //                        + " and F_Status=0 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
                        //                            dvMT = dbo.ExceSQL("select * from T_Monitor_Task  where F_MonitorIndex>" + dvSend[0]["F_MonitorIndex"]
                        //                            + " and F_Status=-1 and F_ManageTASKKINDINDEX=1 and F_ManageTaskIndex=" + Convert.ToInt32(dvIOC[i]["CONTROL_ID"])).Tables[0].DefaultView;
                        //                            for (int ii = 0; ii < dvMT.Count; ii++)
                        //                            {
                        //                                cgs.ActionComplete(Convert.ToInt32(dvMT[ii]["F_DeviceIndex"]), Convert.ToInt32(dvMT[ii]["F_MonitorIndex"]), 900);
                        //                            }
                        //                        }
                        //                        dbo.ExceSQL("update T_Manage_Task set  FIntoStepOK='-' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) ");
                        //                    }


                        //                }
                        //                continue;
                        //            }

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

                        if (dvIOC[i]["MANAGE_TASK_TYPE"].ToString() == "3")
                        {
                            string Aisle = "18001";
                            if (dvIOC[i]["STOCK_BARCODE"].ToString() == "11002")
                            {
                                Aisle = "18002";
                            }
                            DataSet invs = dboM.ExceSQL($"select CellNo from PurchaseOrders_Inv where Aisle = '{Aisle}' group by CellNo");

                            var fullList = CreateMonitor.DataSetToList<PurchaseOrdersInv>(invs);

                            var sortedList = fullList.OrderBy(item =>
                            {
                                var parts = item.CellNo.Split('-');
                                int row = int.Parse(parts[0]);    // 排号
                                int col = int.Parse(parts[1]);    // 列号
                                int layer = int.Parse(parts[2]);  // 层号
                                return (col, layer, row);
                            }).ToList();
                            int startIndex = int.Parse(dvIOC[i]["STOCK_BARCODE"].ToString());
                            int CONTROL_ID = Convert.ToInt32(dvIOC[i]["CONTROL_ID"]);
                            foreach (var item in sortedList)
                            {
                                //盘库逻辑，拆分盘库任务
                                CreateMonitor.CreateMoveInv(startIndex, item.CellNo, 4,CONTROL_ID);//先取货
                                CreateMonitor.CreateMoveInv(startIndex, item.CellNo, 5, CONTROL_ID);//再放货
                            }
                            dboM.ExceSQL("update IO_control set CONTROL_status=" + Model.CGeneralFunction.TASKRUN + " where (CONTROL_ID = " + CONTROL_ID + ")");
                            if (CStaticClass.RealRefresh == true)
                            {
                                //显示设备指令
                                DataSet ds = dbo.ExceSQL("select * from V_Monitor_Task where " + CStaticClass.Monstatus);
                                FrmControlMonitor.FormInstance.MonitorRefresh(ds.Tables[0].DefaultView);
                                //显示调度任务
                                FrmControlMonitor.FormInstance.ManagerRefresh(
                                    dbo.ExceSQL("select * from V_Manage_Task where " + CStaticClass.Manstatus).Tables[0].DefaultView);
                            }
                            IsInv = 1;
                            continue;
                        }


                        #region  不同结束位置任务数控制 
                       
                        string END_DEVICE_CODE = dvIOC[i]["END_DEVICE_CODE"].ToString();
                        int managecount = ManageCountControl(END_DEVICE_CODE);
                        DataView dvchaipan= dbo.ExceSQL("select * from T_Manage_Task where FENDDEVICE ='" + END_DEVICE_CODE + "'").Tables[0].DefaultView;
                        if (dvchaipan.Count >= managecount)
                           {
                               continue;
                           }
                        #endregion

                        bool UseOldRoute = false;
                        #region 新任务
                        //判断(FSTATUS='0')
                        if (dvIOC[i]["CONTROL_STATUS"].ToString() == Model.CGeneralFunction.TASKWAIT.ToString())
                        {
                            #region 20101011同一个逻辑区域可以同时执行的不同批次数在此控制
                            
                            #endregion

                            string UseAwayFork="-";
                            //20100329双叉关联调度任务在此同时获取，否则等待，获取后并且直接分配远近货叉（增加一个函数处理关联任务的获取，返回主任务的远近货叉）
                            if (dvIOC[i]["RELATIVE_CONTROL_ID"].ToString() != "-1")
                            {
                                dv = dboM.ExceSQL("select CONTROL_ID from IO_CONTROL where CONTROL_ID=" + dvIOC[i]["RELATIVE_CONTROL_ID"] + "").Tables[0].DefaultView;
                                if (dv.Count > 0)
                                {
                                    UseAwayFork = ObtainDoubleForkTask(dvIOC[i]["RELATIVE_CONTROL_ID"],"-");
                                    RecCount++;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            ObtainDoubleForkTask(dvIOC[i]["CONTROL_ID"],UseAwayFork);//主任务
                            RecCount++;
                        }

                        #endregion

                        #region 修改路径的答复

                        else if (dvIOC[i]["CONTROL_STATUS"].ToString() == Model.CGeneralFunction.TASKALTERROUTEREPLY.ToString())
                        {
                            if (Information.IsNumeric(dvIOC[i]["END_DEVICE_CODE"])==false )
                            {
                                obj = dbo.GetSingle("SELECT FLaneWay FROM ST_CELL where FCELLCODE='" + dvIOC[i]["END_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["END_WAREHOUSE_CODE"] + "'");
                                if (obj != null)
                                {
                                    FENDDEVICE = Convert.ToInt32(obj);
                                }
                                else
                                {
                                    _CObtainTaskError = "获取任务的修改路径的答复：没找到调度任务索引：" + dvIOC[i]["CONTROL_ID"].ToString() + ",修改后的终点位置！";
                                    continue;
                                }
                                FENDCELL = dvIOC[i]["END_DEVICE_CODE"].ToString();
                                //20100304
                                if (ccf.GetExceptionNOFromManageTask(Convert.ToInt32(dvIOC[i]["CONTROL_ID"]), 1) == Model.CGeneralFunction.TASKREPEATINPUT)
                                {
                                    UseOldRoute = true;
                                    
                                }
                            }
                            else
                            {
                                FENDDEVICE = Convert.ToInt32(dvIOC[i]["END_DEVICE_CODE"]);
                                //20090910
                                if (ccf.GetExceptionNOFromManageTask(Convert.ToInt32(dvIOC[i]["CONTROL_ID"]), 1) == Model.CGeneralFunction.TASKREPEATINPUT)
                                {
                                    dv  = dbo.ExceSQL("SELECT F_TASKKIND, F_DESTINATION FROM T_Base_Destination WHERE (F_TASKKIND = " + dvIOC[i]["CONTROL_TASK_TYPE"] + ") and (F_AbendStation=1) and (F_DESTINATION=" + FENDDEVICE+ ")").Tables[0].DefaultView ;
                                    if (dv.Count > 0)//是应急站台，把原来的终点改为起点改道至应急站台
                                    {
                                        dbo.ExceSQL("update T_Manage_Task set FSTARTDEVICE=FENDDEVICE,FSTARTCELL=FENDCELL where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1)");
                                    }
                                    else
                                    {
                                        UseOldRoute = true;
                                    }
                                    
                                }
                                FENDCELL = "-";

                                #region 20101028转换AGV的坐标为通道


                                obj = dbo.GetSingle("SELECT F_ChannelsIndex FROM T_Base_AGV_Gate WHERE (F_AGVGateDeviceIndex = " + Convert.ToInt32(dvIOC[i]["END_DEVICE_CODE"]) + ") ");
                                if (obj != null)
                                {
                                    FENDDEVICE = Convert.ToInt32(obj);
                                    FENDCELL = dvIOC[i]["END_DEVICE_CODE"].ToString();
                                }
                                else
                                {
                                    FENDDEVICE = Convert.ToInt32(dvIOC[i]["END_DEVICE_CODE"]);
                                    FENDCELL = "-";
                                }
                                #endregion
                            }
                            dbo.ExceSQL("update T_Manage_Task set FExceptionNO=NULL,FENDDEVICE='" + FENDDEVICE + "',FENDCELL='" + FENDCELL + "' where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1)");
                            //已经开始执行的需要更改调度任务)
                            dvmi = dbo.ExceSQL("SELECT * FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) AND (F_Status =3) order by F_MonitorIndex asc").Tables[0].DefaultView;
                            if (dvmi.Count > 0)
                            {//已经开始执行的需要更改调度任务
                                //判断申请修改路径的第一个调度任务：
                                int monitorIndex = (int)dvmi[0]["F_MonitorIndex"];
                                int associateMonitor = -1;
                                if (dvmi[0]["F_Associate"] != DBNull.Value)
                                {
                                    associateMonitor = Convert.ToInt32(dvmi[0]["F_Associate"]);
                                }
                                int devindex = Convert.ToInt32(dvmi[0]["F_DeviceIndex"]);
                                int devKind = ccf.GetDeviceKindIdx(Convert.ToInt32(dvmi[0]["F_DeviceIndex"]));
                                int devCommand = Convert.ToInt32(dvmi[0]["F_DeviceCommandIndex"]);
                                int routeID = Convert.ToInt32(dvmi[0]["F_RouteID"]);
                                int NumParam1 = Convert.ToInt32(dvmi[0]["F_NumParam1"]);
                                int NumParam4 = Convert.ToInt32(dvmi[0]["F_NumParam4"]);
                                string AheadDetect = dvmi[0]["F_AheadDetect"].ToString();



                                ////20090925 WHERE
                                DMAN = dbo.ExceSQL("select * from T_Manage_Task where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1)").Tables[0].DefaultView;
                                if (DMAN.Count > 0)
                                {


                                    //20091107
                                    int routeidNew = 0;
                                    if (UseOldRoute == false)
                                    {
                                        routeidNew = CDisassembleTask.MinRouteID(Convert.ToInt32(DMAN[0]["FSTARTDEVICE"]), Convert.ToInt32(DMAN[0]["FENDDEVICE"]), DMAN[0]["FUseAwayFork"]);
                                    }
                                    else
                                    {//970送货时货架有货，还是用原来路径
                                        routeidNew = routeID;
                                    }

                                    //20091005
                                    if (routeidNew == -1)
                                    {

                                        //考虑重新向管理申请改道
                                        if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                        {//20091107
                                            GetUsableDestination(DMAN[0]);
                                        }

                                        continue;
                                    }
                                    //20091005
                                    //删除原来的申请修改路径任务，拆分新的任务并且只保留现有设备开始的任务
                                    dbo.ExceSQL("DELETE FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) AND (F_Status =3)");
                                    //20090910
                                    if (CDisassembleTask.CreateMonitor(1, Convert.ToInt32(dvIOC[i]["CONTROL_ID"]), routeidNew, DMAN[0], 3) <= 0)
                                    {
                                        //重新生成申请修改路径的申请任务
                                        sql = "INSERT INTO T_Monitor_Task " +
                                                    "(F_ManageTaskIndex, F_ManageTASKKINDINDEX, F_MonitorIndex,F_MonitorTaskLevel," +
                                                    " F_DeviceIndex, F_DeviceCommandIndex, F_RouteID, F_Status,F_NumParam1, F_NumParam4," +
                                                    " F_AheadDetect,F_TxtParam)" +
                                                "VALUES (" + dvIOC[i]["CONTROL_ID"] + ",1," + monitorIndex + ",1," + devindex + "," + devCommand + "," + routeID + ",3," + NumParam1 + "," + NumParam4
                                                    + ",'" + AheadDetect + "','" + dvIOC[i]["STOCK_BARCODE"] + "')";
                                        dbo.ExceSQL(sql);
                                        continue;
                                    }

                                    if (devKind == 4)
                                    {
                                        if (devCommand == 7)
                                        {
                                            int RGVsn = ccf.GetSerialNumberFromRouteDevice(routeID, devindex);
                                            int Consn = ccf.GetSerialNumberFromRouteDevice(routeID, NumParam1);

                                            #region RGV运动到接货点
                                            if (RGVsn > Consn)
                                            {
                                                //删除RGV运动到接货点之前的任务
                                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                    Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                    devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                                    ") AND (F_Status = 3)  AND (F_NumParam1 = " + NumParam1 + ")").Tables[0].DefaultView;
                                                if (dvnew.Count > 0)
                                                {
                                                    dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                    Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                }
                                                

                                            }
                                            #endregion

                                            #region RGV运动到送货点
                                            if (RGVsn < Consn)
                                            {
                                                int RGVsn1 = ccf.GetSerialNumberFromRouteDevice(routeidNew, devindex);
                                                //找到接货输送机设备索引
                                                List<int> nextcon = CDisassembleTask.GetNextDevice(routeidNew, RGVsn1);
                                                int condev = nextcon[0];
                                                //删除RGV运动到送货点之前的任务
                                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                    Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                    devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                                    ") AND (F_Status = 3)  AND (F_NumParam1 = " + condev + ")").Tables[0].DefaultView;
                                                if (dvnew.Count > 0)
                                                {
                                                    dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                    Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                }
                                                
                                            }
                                            #endregion
                                        }

                                        #region RGV送货

                                        if ((devCommand == 3) || (devCommand == 5))
                                        {
                                            int RGVsn = ccf.GetSerialNumberFromRouteDevice(routeidNew, devindex);
                                            //找到接货输送机设备索引
                                            List<int> nextcon = CDisassembleTask.GetNextDevice(routeidNew, RGVsn);
                                            int condev = nextcon[0];
                                            //删除RGV运动到送货点之前的任务
                                            dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                                ") AND (F_Status = 3)  AND (F_NumParam1 = " + condev + ")").Tables[0].DefaultView;
                                            if (dvnew.Count > 0)
                                            {
                                                dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                            }
                                            

                                        }
                                        #endregion

                                        #region RGV接货
                                        if ((devCommand == 2) || (devCommand == 4))
                                        {
                                            int RGVsn = ccf.GetSerialNumberFromRouteDevice(routeidNew, devindex);
                                            //找到送货输送机设备索引
                                            List<int> priorcon = CDisassembleTask.GetPriorDevice(routeidNew, RGVsn);
                                            int condev = priorcon[0];
                                            //删除RGV运动到接货点之前的任务
                                            dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                                ") AND (F_Status = 3)  AND (F_NumParam1 = " + condev + ")").Tables[0].DefaultView;
                                            if (dvnew.Count > 0)
                                            {
                                                dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                            }
                                            

                                        }
                                        #endregion
                                    }
                                    if (devKind == 2)
                                    {
                                        #region 输送机送货
                                        if (devCommand == 3)
                                        {
                                            int consn = ccf.GetSerialNumberFromRouteDevice(routeidNew, devindex);
                                            //找到接货RGV设备索引
                                            List<int> nextrgv = CDisassembleTask.GetNextDevice(routeidNew, consn);
                                            int rgvdev = nextrgv[0];

                                            //删除RGV运动到接货点之前的任务
                                            dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                rgvdev + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                                ") AND (F_Status = 3)  AND (F_NumParam1 = " + devindex + ")").Tables[0].DefaultView;
                                            if (dvnew.Count > 0)
                                            {
                                                dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                            }

                                        }
                                        #endregion

                                        #region 输送机的接货

                                        if (devCommand == 4)
                                        {
                                            int consn = ccf.GetSerialNumberFromRouteDevice(routeID, devindex);
                                            //找到送货RGV设备索引
                                            List<int> priorrgv = CDisassembleTask.GetPriorDevice(routeID, consn);
                                            int rgvdev = priorrgv[0];
                                            int rgvsn = ccf.GetSerialNumberFromRouteDevice(routeidNew, rgvdev);
                                            List<int> nextdev = CDisassembleTask.GetNextDevice(routeidNew, rgvdev);
                                            int condev = nextdev[0];
                                            //删除RGV运动到送货点之前的任务
                                            dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                rgvdev + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                                ") AND (F_Status = 3)  AND (F_NumParam1 = " + condev + ")").Tables[0].DefaultView;
                                            if (dvnew.Count > 0)
                                            {
                                                dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                            }

                                        }

                                        #endregion


                                        #region 输送机的送出
                                        if (devCommand == 6)
                                        {
                                            dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                devindex + ") AND (F_DeviceCommandIndex = 6) AND (F_RouteID = " + routeidNew +
                                                ") AND (F_Status = 3) ").Tables[0].DefaultView;
                                            if (dvnew.Count > 0)
                                            {
                                                dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                                int CurrentLocation = 0;
                                                dvc = dbo.ExceSQL("SELECT FCurrentLocation FROM T_Manage_Task where FID=" + dvIOC[i]["CONTROL_ID"] + " and F_ManageTaskKindIndex=1").Tables[0].DefaultView;
                                                if (dvc.Count > 0)
                                                {
                                                    CurrentLocation = Convert.ToInt32(dvc[0]["FCurrentLocation"]);
                                                }
                                                if (CurrentLocation == 0) continue;
                                                dbo.ExceSQL("update T_Monitor_Task set F_DeviceIndex=" + CurrentLocation + " where F_MonitorIndex=" + dvnew[0]["F_MonitorIndex"]);
                                                //20090910已经搬运到CurrentLocation（F_NumParam4=CurrentLocation） 删除送出任务
                                                dbo.ExceSQL("delete from T_Monitor_Task where  F_DeviceIndex=" + CurrentLocation + " and F_NumParam4=" + CurrentLocation + "");
                                                //20091102
                                                dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_LockedState=" + monitorIndex);

                                                dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where  (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");


                                            }
                                        }
                                        #endregion

                                    }
                                    #region 堆垛机的送货重和其它任务
                                    if (devKind == 1)
                                    {
                                        //堆垛机的送货重，只保留堆垛机的送货任务
                                        
                                        dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                                devindex + ") AND (F_DeviceCommandIndex = " + devCommand + ") AND (F_RouteID = " + routeidNew +
                                                ") AND (F_Status = 3)").Tables[0].DefaultView;
                                        if (dvnew.Count > 0)
                                        {
                                            dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                                Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                            dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + devindex + "");
                                            dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                            Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_Status = 3)");
                                        }
                                        

                                    }
                                    #endregion

                                }//20090910


                            }
                            else//未拆分的，修改目标位置和状态(FSTATUS='40'禁用拆分的FIntoStepOK='-'改为FIntoStepOK='0'；
                            {
                                //20091128必须使用FENDCELL
                                dbo.ExceSQL("update T_Manage_Task set FENDDEVICE='" + FENDDEVICE + "',FENDCELL='" + FENDCELL + "', FIntoStepOK=0 where (FID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ") AND (F_ManageTASKKINDINDEX =1) and (FIntoStepOK='-')");
                            }
                            //修改T_Manage_Task的FLANEWAY，FSTACK
                            int flaneway = -1, stackno = -1;
                            if (Information.IsNumeric(dvIOC[i]["START_DEVICE_CODE"]) == false)
                            {//货位编码
                                obj = dbo.GetSingle("SELECT FLaneWay FROM ST_CELL where FCELLCODE='" + dvIOC[i]["START_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["START_WAREHOUSE_CODE"] + "'");
                                if (obj != null)
                                {
                                    flaneway =Convert.ToInt32( obj);
                                }
                            }
                            else
                            {
                                if (Information.IsNumeric(dvIOC[i]["END_DEVICE_CODE"]) == false)
                                {
                                    obj = dbo.GetSingle("SELECT FLaneWay FROM ST_CELL where FCELLCODE='" + dvIOC[i]["END_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["END_WAREHOUSE_CODE"] + "'");
                                    if (obj != null)
                                    {
                                        flaneway =Convert.ToInt32( obj);
                                    }
                                }
                            }
                            string sss = "SELECT F_StackIndex, F_LaneNo FROM T_Base_StackInfo " +
                                        " where (F_LaneNo='" + flaneway + "') OR (F_LaneNo like '%" + ";" + flaneway + "') OR (F_LaneNo='" + flaneway + ";" + "%') ";
                            dv = dbo.ExceSQL(sss).Tables[0].DefaultView;
                            if (dv.Count > 0)
                            {
                                stackno = Convert.ToInt32(dv[0]["F_StackIndex"]);
                            }
                            dbo.ExceSQL("update dbo.T_Manage_Task set FLANEWAY=" + flaneway + ",FSTACK=" + stackno + " where F_ManageTaskKindIndex=1 and FID=" + dvIOC[i]["CONTROL_ID"] + "");
                            //20091107
                            dboM.ExceSQL("update IO_control set CONTROL_status=" + Model.CGeneralFunction.TASKRUN + " where (CONTROL_ID = " + Convert.ToInt32(dvIOC[i]["CONTROL_ID"]) + ")");
                        }

                        #endregion

                    }
                    if (RecCount > 0)
                    {
                        //显示调度任务
                        if (CStaticClass.RealRefresh == true)
                        {
                            FrmControlMonitor.FormInstance.ManagerRefresh(
                                dbo.ExceSQL("select * from V_Manage_Task where " + CStaticClass.Manstatus).Tables[0].DefaultView);
                        }
                        
                        return RecCount;
                    }
                    else
                    {
                        //_CObtainTaskError = "没有获得任何调度任务！";
                        return 0;
                    }
                }
                else
                {
                    #region  测试自动生成任务 20120916
                  //  int havegood = CStaticClass.GetDevicePhotoelectric("12112.0");
                  // int[] status = new int[6];
                  //// status = CStaticClass.GetDeviceState(12111);
                  // status[1] = 0;
               
                  // if ((havegood ==1) && (status[1] == 0))
                  // {
                  //       int   AutoManageIdx = ccf.GetTempManageIdx();
                  //       string dtime = DateTime.Now.ToString("u");//20101028
                  //      dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                  //      string tempsql = "   insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,BOX_QUANTITY,UNPACK_QUANTITY,FStartCol,FStartLayer) values(" + AutoManageIdx + ",'343243243243243','1',2,'1','12112','-','1','12115','-',0,0,'-','" + dtime + "',0,0,0,0)";
                  //    DataView tempdv=  dbo.ExceSQL("select * from t_manage_task where FSTARTDEVICE =" + 12112).Tables[0].DefaultView;
                  //    if (tempdv.Count <=0)
                  //    {
                  //        return 0;
                  //        dbo.ExceSQL(tempsql);
                  //    }
                    
                  // }


                    //int havegood = CStaticClass.GetDevicePhotoelectric("12026.0");
                    //int[] status = new int[6];
                    //// status = CStaticClass.GetDeviceState(12111);
                    //status[1] = 0;

                    //if ((havegood == 1) && (status[1] == 0))
                    //{
                    //    int AutoManageIdx = ccf.GetTempManageIdx();
                    //    string dtime = DateTime.Now.ToString("u");//20101028
                    //    dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                    //    string tempsql = "   insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,BOX_QUANTITY,UNPACK_QUANTITY,FStartCol,FStartLayer) values(" + AutoManageIdx + ",'343243243243243','1',2,'1','12026','-','1','12526','-',0,0,'-','" + dtime + "',0,0,0,0)";
                    //    DataView tempdv = dbo.ExceSQL("select * from t_manage_task where FSTARTDEVICE =" + 12026).Tables[0].DefaultView;
                    //    if (tempdv.Count <= 0)
                    //    {

                    //        dbo.ExceSQL(tempsql);
                    //    }
                    //    else
                    //    {
                    //        DataView tempdvmon = dbo.ExceSQL("select * from t_monitor_task where f_deviceindex =12026 ").Tables[0].DefaultView;
                    //        if (tempdvmon.Count <= 0)
                    //        {
                    //            dbo.ExceSQL(tempsql);
                    //        }
                    //    }

                    //}

                    //int havegood = CStaticClass.GetDevicePhotoelectric("12026.0");
                    //int[] status = new int[6];
                    //// status = CStaticClass.GetDeviceState(12111);
                    //status[1] = 0;

                    //if ((havegood == 1) && (status[1] == 0))
                    //{
                    //    int AutoManageIdx = ccf.GetTempManageIdx();
                    //    string dtime = DateTime.Now.ToString("u");//20101028
                    //    dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                    //    string tempsql = "   insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,BOX_QUANTITY,UNPACK_QUANTITY,FStartCol,FStartLayer) values(" + AutoManageIdx + ",'343243243243243','1',2,'1','12026','-','1','12043','-',0,0,'-','" + dtime + "',0,0,0,0)";
                    //    DataView tempdv = dbo.ExceSQL("select * from t_manage_task where FSTARTDEVICE =" + 12026).Tables[0].DefaultView;
                        
                    //    if (tempdv.Count <= 0)
                    //    {

                    //        dbo.ExceSQL(tempsql);
                    //    }
                    //    else
                    //    {
                           
                    //    }

                    //}
                   


                    #endregion  测试自动生成任务
                    //_CObtainTaskError = "管理程序没有下达新的搬运任务！";
                    return 0;
                }
            }
            catch (Exception ex)
            {
                _CObtainTaskError = "获得调度任务失败:" + ex.Message;
                return 0;
            }
            finally
            {
                dsIOC=null;
                dvIOC=null;
                
                dv = null;
                dvc = null;
                dvmi = null;
                dvnew = null;
            }
        }
        /// <summary>
        /// 根据自动任务修改的获取出入库任务
        /// </summary>
        /// <param name="gdata">扫描到的托盘号</param>
        public static void GetWebManageTask(string gdata)
        {
            //任务状态已启动 托盘号是扫描到的
            DataView dsIOC = dboM.ExceSQL($"select * from TaskDetails where TaskStatus = 1 and PalletNo='{gdata}'").Tables[0].DefaultView;

            if (dsIOC.Count>0)
            {
                string Sql, _tasktype, _startposition, _startsite = "-", _endposition, _endsite = "-";

                DataSet ds;
                _tasktype = dsIOC[0]["TaskType"].ToString();//入库
                _startposition = dsIOC[0]["SourceLocation"].ToString();//起始点
                _endposition = dsIOC[0]["Aisle"].ToString();//巷道
                int flaneway = 0;
                int stackno = 0;
                int startdevicekind = ccf.GetDeviceKindIdx(Convert.ToInt32(_startposition));//20110411
                if (_tasktype == "2")//出库
                {
                    _startsite = dsIOC[0]["SourceLocation"].ToString();//起点位置
                    flaneway = Convert.ToInt32(_startposition);
                    if (dbo.Exists("SELECT FID FROM ST_CELL where FCELLSTATUS<> '-1' and FLaneWay=" + flaneway + " and FCELLCODE='" + _startsite + "'") == false)
                    {
                        MessageBox.Show("起始位置和起始货位编码在数据库中没有记录！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                if (_tasktype == "1")//入库
                {
                    _endsite = dsIOC[0]["TargetLocation"].ToString();//终点位置
                    flaneway = Convert.ToInt32(_endposition);
                    if (dbo.Exists("SELECT FID FROM ST_CELL where FCELLSTATUS<> '-1' and FLaneWay=" + flaneway + " and FCELLCODE='" + _endsite + "'") == false)
                    {
                        MessageBox.Show("终点位置和终点货位编码在数据库中没有记录！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                try
                {
                    //20100304
                    Sql = "SELECT F_RouteID FROM T_Base_Route WHERE (F_StartDevice = " + _startposition + ") AND (F_EndDevice = " + _endposition + ")";
                    ds = dbo.ExceSQL(Sql).Tables[0].DataSet;
                    if (ds.Tables[0].DefaultView.Count <= 0)
                    {
                        MessageBox.Show("起始位置和结束位置不在有效路径的范围内！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    string FSTARTCELL = _startsite, FENDCELL = _endsite, UseAwayFork = "-";
                    int FSTARTDEVICE = Convert.ToInt32(_startposition); int FENDDEVICE = Convert.ToInt32(_endposition);
                    devinfo = Model.CGetInfo.GetDeviceInfo(FSTARTDEVICE);

                    stackno = Convert.ToInt32(dbo.GetSingle("SELECT F_StackIndex FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = " + flaneway + ")"));//20101028
                    string dtime = DateTime.Now.ToString("u");//20101028
                    dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                    int AutoManageIdx = ccf.GetTempManageIdx();

                    //插入临时调度任务T_Manage_Task(监控下的调度任务)：
                    int startcol = 0, startlayer = 0;//20110411
                    if (startdevicekind == 10)//出库或是巷道内移库任务
                    {
                        startcol = Convert.ToInt32(_startsite.Substring(3, 2));
                        startlayer = Convert.ToInt32(_startsite.Substring(6, 2));
                    }

                    Sql = "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL," +
                           "FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,UNPACK_QUANTITY,BOX_QUANTITY,FStartCol,FStartLayer) " +
                           "values(" + AutoManageIdx + ",'" + dsIOC[0]["RFID"].ToString() + "','" + _tasktype + "',2,'" + ccf.GetWarehouseIndex() + "','" + _startposition + "','" + _startsite + "','" + ccf.GetWarehouseIndex() + "','"
                           + _endposition + "','" + _endsite + "'," + flaneway + "," + stackno + ",'" + UseAwayFork + "','" + dtime + "'," + 1 + "," + int.Parse(dsIOC[0]["TaskQty"].ToString()) + "," + startcol + "," + startlayer + ")";//20101028

                    ds = dbo.ExceSQL(Sql);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 本行记录是否需要软确认
        /// </summary>
        /// <param name="drv">行视图</param>
        /// <returns>ｔｒｕｅ必须软确认；ｆａｌｓｅ无需软确认</returns>
        public static bool IfSoftConfirm(string FCONTROLTASKTYPE)
        {
            try
            {
                DataSet ds = dbo.ExceSQL("SELECT FCODE, FSOFTCONFIRM FROM T_ITEMTASKTYPE where FCODE='" + FCONTROLTASKTYPE+"'");
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    if (ds.Tables[0].DefaultView[0]["FSOFTCONFIRM"].ToString() == "1")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        static void FeedBackConfirm(int FID, int FSTARTDEVICE)
        {
            //判断每个任务的第一个设备FSTARTDEVICE是否空闲？？？
            try
            {
                DataSet dsS = dbo.ExceSQL("SELECT F_DeviceIndex,F_LockedState FROM T_Base_Device Where F_DeviceIndex=" + FSTARTDEVICE + "and F_LockedState=0");
                if (dsS.Tables[0].DefaultView.Count > 0)
                {
                    DataSet ds = dboM.ExceSQL("update IO_CONTROL set CONTROL_STATUS='2' where CONTROL_ID=" + FID);
                }
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得FSTARTCELL或者FENDCELL
        /// </summary>
        /// <param name="fid">IO_CONTROL的主键FID</param>
        /// <param name="devidx">设备索引</param>
        /// <param name="kind">堆垛机001取坐标；002送坐标</param>
        /// <returns>返回FSTARTCELL或者FENDCELL</returns>
        static string GetSite(int fid, int devidx, string kind)
        {
            try
            {
                DataSet ds = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceKindIndex FROM T_Base_Device where F_DeviceKindIndex=10 and F_DeviceIndex=" + devidx);
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    DataSet dss = dboM.ExceSQL("SELECT * FROM IO_CONTROLDETAIL where FCONTROLID=" + fid + " and  FKIND=" + kind);
                    if (dss.Tables[0].DefaultView.Count > 0)
                    {
                        return dss.Tables[0].DefaultView[0]["FVALUE"].ToString();
                    }
                    else
                    {
                        _CObtainTaskError = "获取调度任务时，无法取得堆垛机坐标！！！";
                        return "";
                    }
                }
                else
                {
                    return "-";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        ///判断调度任务A是否为91码盘入库或者92码盘出库；
        ///如果A的FMANAGEID任务有9搬运木块码盘的任务，不允许插入调度任务A
        /// </summary>
        /// <param name="TaskType">调度任务类型</param>
        /// <param name="FMANAGEID"></param>
        /// <returns></returns>
        static bool GetStackPalletTask(string TaskType, int FMANAGEID)
        {
            DataSet ds = dbo.ExceSQL("SELECT FCODE, FINTERCODE FROM T_ITEMTASKTYPE Where FCODE='"+TaskType +"'");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                if ((ds.Tables[0].DefaultView[0]["FINTERCODE"].ToString() == "91")
                    || (ds.Tables[0].DefaultView[0]["FINTERCODE"].ToString() == "92"))
                {
                    DataSet dss = dbo.ExceSQL("SELECT FINTERCODE, FCONTROLTASKTYPE,FCODE FROM T_Manage_Task ,T_ITEMTASKTYPE Where FCONTROLTASKTYPE = FCODE and FMANAGEID=" + FMANAGEID + " and FINTERCODE=9 ");
                    if (dss.Tables[0].DefaultView.Count > 0)
                    {
                        return true;
                    }
                    else
                        return false;
                }
                else
                    return false;
            }
            else
                _CObtainTaskError ="管理单据传来的搬运任务类型在监控表里不存在！";
                return false;
        }
        /// <summary>
        ///判断调度任务A是否为开始位置4#站台或者5#站台码盘任务；
        ///如果A的FMANAGEID任务有9搬运木块码盘的任务，不允许插入调度任务A
        /// </summary>
        /// <param name="FSTARTDEVICE">开始位置</param>
        /// <param name="FMANAGEID"></param>
        /// <returns></returns>
        static bool GetStackPalletTask(int FSTARTDEVICE, int FMANAGEID)
        {
            
            if ((FSTARTDEVICE==4)|| (FSTARTDEVICE==5))
            {

                DataSet dss = dbo.ExceSQL("SELECT FINTERCODE, FCONTROLTASKTYPE,FCODE FROM T_Manage_Task ,T_ITEMTASKTYPE Where FCONTROLTASKTYPE = FCODE and FMANAGEID=" + FMANAGEID + " and FINTERCODE=9 ");
                if (dss.Tables[0].DefaultView.Count > 0)
                {
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
            
        }
        static bool GetStackPalletTask(DataRowView drv)
        {
            DataView dv = dbo.ExceSQL("SELECT F_StackPositionDeviceIndex FROM T_BASE_STACK_ROBOT where F_StackPositionDeviceIndex=" +Convert.ToInt32( drv["FSTARTDEVICE"])).Tables[0].DefaultView;
            //if ((drv["FSTARTDEVICE"].ToString() == "4") || (drv["FSTARTDEVICE"].ToString() == "5"))
            if(dv.Count>0)
            {

                DataSet dss = dboM.ExceSQL("SELECT MANAGE_ID, CONTROL_TASK_TYPE FROM IO_CONTROL where MANAGE_ID=" + Convert.ToInt32(drv["FMANAGEID"]) + " and CONTROL_TASK_TYPE='901'");
                if (dss.Tables[0].DefaultView.Count > 0)
                {
                    return true;
                }
                else
                    return false;
            }
            else
                return false;

        }
        static void RecordMaxManageTaskFID(int fid)
        {
            DataSet ds= dbo.ExceSQL("select F_ManageTaskIndex from T_Base_Manage_Task_Index_Auto_Task");
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (fid > Convert.ToInt32(dv[0]["F_ManageTaskIndex"]))
                {
                    dbo.ExceSQL("UPDATE T_Base_Manage_Task_Index_Auto_Task SET F_ManageTaskIndex ="+fid);
                }
            }
            else
            {
                dbo.ExceSQL("INSERT INTO T_Base_Manage_Task_Index_Auto_Task (F_ManageTaskIndex)VALUES (" + fid + ")");
            }
        }
        /// <summary>
        /// 20091005
        /// 获取可用的目标位置：入库的巷道或者出库站台
        /// </summary>
        /// <param name="dr">T_Manage_Task表的行记录</param>
        /// <returns></returns>
        public static void GetUsableDestination(DataRowView dr)
        {
            //20100610查找一个路径可用，任务数最少的终点设备
            Dictionary<int, int> advDev = new Dictionary<int, int>();
            object ob;
            //只修申请改调度任务的路径，不修改调度自动任务路径
            if (dr["F_ManageTaskKindIndex"].ToString() != "1") return;
            string sql = "";
            string adviceDev = "";
            DataTable dtd = dbo.ExceSQL("SELECT F_TASKKIND, F_DESTINATION FROM T_Base_Destination WHERE (F_TASKKIND = " + dr["FCONTROLTASKTYPE"] + ") and (F_AbendStation=1) and (F_DESTINATION=" + dr["FENDDEVICE"] + ")").Tables[0];
            if (dtd.Rows.Count > 0)//原来终点是应急站台那么还分配这个站台，不需要改变
            {
                adviceDev = dtd.Rows[0]["F_DESTINATION"].ToString();
                //20091005
                return;
            }
            else
            {
                //查找可用目标位置
                DataTable dt = dbo.ExceSQL("SELECT F_TASKKIND, F_DESTINATION FROM T_Base_Destination WHERE (F_TASKKIND = " + dr["FCONTROLTASKTYPE"] + ") and (F_DESTINATION <>" + dr["FENDDEVICE"] + ") and (F_AbendStation=0)").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (CDisassembleTask.MinRouteID(Convert.ToInt32(dr["FSTARTDEVICE"]), Convert.ToInt32(dt.Rows[i]["F_DESTINATION"]), dr["FUseAwayFork"]) != -1)
                        {
                            //20100610统计到终点设备正在执行的任务数
                            ob = dbo.GetSingle("SELECT count(FENDDEVICE) as counts FROM T_Manage_Task where FENDDEVICE='" + dt.Rows[i]["F_DESTINATION"] + "' and fstatus>0");
                            advDev.Add(Convert.ToInt32(dt.Rows[i]["F_DESTINATION"]), Convert.ToInt32(ob));

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

                        return ;


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

                            return ;

                        }
                    }
                }
                else
                {
                    return;
                }
            }

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


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


        public static bool IfDeleteOutTask(int fid, int deleteflag)
        {     //20091014      
            try
            {
                if (1 != deleteflag)
                {
                    return false;
                }

                string strsql = "select FIntoStepOK from T_Manage_Task where F_ManageTaskKindIndex=1 and FID= " + fid + " and FIntoStepOK <> '1' ";

                DataView dv = dbo.ExceSQL(strsql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    string delsql = "DELETE FROM T_Manage_Task WHERE (F_ManageTaskKindIndex = 1) AND (FID = " + fid + ")";
                    string cancelsql = "update IO_Control set CONTROL_STATUS=" + Model.CGeneralFunction.TASKCANCEL + " where CONTROL_ID=" + fid;

                    dbo.ExceSQL(delsql);
                    dboM.ExceSQL(cancelsql);
                    return true;

                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 20101028获取关联任务，同时返回主任务的应该分配的货叉：0，近货叉；1，远货叉；“-”未分配
        /// </summary>
        /// <param name="RelativeControlID">关联任务FID</param>
        /// <param name="UseAwayFork">是否使用远货叉，默认值"-"</param>
        /// <returns></returns>
        static string ObtainDoubleForkTask(object RelativeControlID,string UseAwayFork)
        {

           

            int i = 0;
            
            
            DataView dvl;
            
            object obj = null;
            string FSTARTCELL = ""; string FENDCELL = ""; char[] cc = new char[1] { '-' };
            int FSTARTDEVICE = 0; int FENDDEVICE = 0;
            string flaneway = "-1";
            int stackno = -1;
            int FStartCol = 0, FStartLayer = 0, FEndCol = 0, FEndLayer = 0;

            DataView dvIOC = dboM.ExceSQL("select * from IO_CONTROL where CONTROL_ID=" + RelativeControlID + "").Tables[0].DefaultView;
            if (dvIOC.Count == 0) return "-";
            string sql = "SELECT T_Base_Manage_Task_Kind.F_TaskKindIndex, " +
                            "T_Manage_Task.F_ManageTaskKindIndex, T_Manage_Task.FID " +
                            "FROM T_Base_Manage_Task_Kind ,  T_Manage_Task where  " +
                            "T_Base_Manage_Task_Kind.F_TaskKindIndex = T_Manage_Task.F_ManageTaskKindIndex " +
                            " and T_Base_Manage_Task_Kind.F_TaskKindIndex=1 and T_Manage_Task.FID = ";

            sql = sql + RelativeControlID;

            dvl = dbo.ExceSQL(sql).Tables[0].DefaultView;
            if (dvl.Count > 0)// 插入调度任务新记录
            {
                return "-";
            }

            if (Information.IsNumeric(dvIOC[i]["START_DEVICE_CODE"]) == false)
            {//货位编码
                //20101028
                dvl = dbo.ExceSQL("SELECT FLaneWay,FStack FROM ST_CELL where FCELLCODE='" + dvIOC[i]["START_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["START_WAREHOUSE_CODE"] + "'").Tables[0].DefaultView;
                if (dvl.Count > 0)
                {
                    flaneway = dvl[0]["FLaneWay"].ToString();
                    stackno =Convert.ToInt32( dvl[0]["FStack"]);//20101028
                    FStartCol =Convert.ToInt32( dvIOC[i]["START_DEVICE_CODE"].ToString().Substring(3, 2));
                    FStartLayer = Convert.ToInt32(dvIOC[i]["START_DEVICE_CODE"].ToString().Substring(6, 2));
                }

            }
            else
            {
                if (Information.IsNumeric(dvIOC[i]["END_DEVICE_CODE"]) == false)
                {
                    //20101028
                    dvl = dbo.ExceSQL("SELECT FLaneWay,FStack FROM ST_CELL where FCELLCODE='" + dvIOC[i]["END_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["END_WAREHOUSE_CODE"] + "'").Tables[0].DefaultView;
                    if (dvl.Count>0)
                    {
                        flaneway = dvl[0]["FLaneWay"].ToString();
                        stackno =Convert.ToInt32( dvl[0]["FStack"]);//20101028
                        FEndCol =Convert.ToInt32( dvIOC[i]["END_DEVICE_CODE"].ToString().Substring(3, 2));
                        FEndLayer =Convert.ToInt32( dvIOC[i]["END_DEVICE_CODE"].ToString().Substring(6, 2));
                    }
                }
            }
            //20101028


            //记录调度任务最大索引FID到表T_Base_Manage_Task_Index_Auto_Task
            RecordMaxManageTaskFID(Convert.ToInt32(dvIOC[i]["CONTROL_ID"]));
            
            if (Information.IsNumeric(dvIOC[i]["START_DEVICE_CODE"]) == true)
            {
                obj = dbo.GetSingle("SELECT T_Base_AGV_Gate.F_ChannelsIndex FROM T_Base_Device,T_Base_AGV_Gate where T_Base_Device.F_DeviceIndex = T_Base_AGV_Gate.F_AGVGateDeviceIndex and (T_Base_Device.F_DeviceKindIndex = 9) and (F_AGVGateDeviceIndex = " + Convert.ToInt32(dvIOC[i]["START_DEVICE_CODE"]) + ") ");
                if (obj != null)
                {//AGV站台编码
                    FSTARTDEVICE = Convert.ToInt32(obj);
                    FSTARTCELL = dvIOC[i]["START_DEVICE_CODE"].ToString();
                }
                
                else
                {//站台编码
                    FSTARTDEVICE = Convert.ToInt32(dvIOC[i]["START_DEVICE_CODE"]);
                    FSTARTCELL = "-";
                }
                
            }
            else
            {//货位编码
                obj = dbo.GetSingle("SELECT FLaneWay FROM ST_CELL where FCELLCODE='" + dvIOC[i]["START_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["START_WAREHOUSE_CODE"] + "'");
                if (obj != null)
                {
                    FSTARTDEVICE = Convert.ToInt32(obj);
                }
                else
                {
                    _CObtainTaskError = "获取任务时：没找到调度任务索引：" + dvIOC[i]["CONTROL_ID"].ToString() + ",的起点位置！";
                    return "-";
                }
                FSTARTCELL = dvIOC[i]["START_DEVICE_CODE"].ToString();
            }
            if (Information.IsNumeric(dvIOC[i]["END_DEVICE_CODE"]) == true)
            {
                obj = dbo.GetSingle("SELECT T_Base_AGV_Gate.F_ChannelsIndex FROM T_Base_Device,T_Base_AGV_Gate where T_Base_Device.F_DeviceIndex = T_Base_AGV_Gate.F_AGVGateDeviceIndex and (T_Base_Device.F_DeviceKindIndex = 9) and (F_AGVGateDeviceIndex = " + Convert.ToInt32(dvIOC[i]["END_DEVICE_CODE"]) + ") ");
                if(obj!=null)
                {//AGV站台编码
                    FENDDEVICE = Convert.ToInt32(obj);
                    FENDCELL = dvIOC[i]["END_DEVICE_CODE"].ToString();
                }
                
                else
                {//站台编码
                    FENDDEVICE = Convert.ToInt32(dvIOC[i]["END_DEVICE_CODE"]);
                    FENDCELL = "-";
                }
            }
            else
            {//货位编码
                obj = dbo.GetSingle("SELECT FLaneWay FROM ST_CELL where FCELLCODE='" + dvIOC[i]["END_DEVICE_CODE"] + "' and FWAREHOUSE='" + dvIOC[i]["END_WAREHOUSE_CODE"] + "'");
                if (obj != null)
                {
                    FENDDEVICE = Convert.ToInt32(obj);
                }
                else
                {
                    _CObtainTaskError = "获取任务时：没找到调度任务索引：" + dvIOC[i]["CONTROL_ID"].ToString() + ",的终点位置！";
                    return "-";
                }
                FENDCELL = dvIOC[i]["END_DEVICE_CODE"].ToString();
            }
            //20091014
            int FTASKLEVEL = 0;//空托盘组出库的优先级应该最大
            FTASKLEVEL = dvIOC[i]["CONTROL_TASK_LEVEL"] == DBNull.Value ? 0 : Convert.ToInt32(dvIOC[i]["CONTROL_TASK_LEVEL"]);
            if (UseAwayFork == "-")
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(FSTARTDEVICE);
                if (devinfo != null)
                {
                    if (Microsoft.VisualBasic.Information.IsNumeric(FSTARTCELL) == true)
                    {
                        obj = dbo.GetSingle("SELECT F_UseAwayFork FROM T_Base_AGV_Gate WHERE  (F_ChannelsIndex=" + FSTARTDEVICE + ") and ( F_AGVGateDeviceIndex= " + FSTARTCELL + ")").ToString();
                        if (obj != null)
                        {//AGV站台的双叉属性
                            UseAwayFork = obj.ToString();
                            
                        }
                    }
                    else
                    {
                        if (devinfo.DoubleFork == "1")
                        {
                            UseAwayFork = "0";
                        }
                        else if (devinfo.DoubleFork == "2")
                        {
                            UseAwayFork = "1";
                        }

                    }
                    if (FEndCol > 0)
                    {//结束列有数据是巷道货位判断是否为极限列，以极限列为准分配货叉
                        //obj = dbo.GetSingle("SELECT F_ForwardLimitX FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = " + flaneway + ") AND (F_ForwardLimitX = " + FEndCol + ")");
                        //if (obj != null)
                        //{
                        //    UseAwayFork = "0";
                        //}
                        //obj = dbo.GetSingle("SELECT F_BackLimitX FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = " + flaneway + ") AND (F_BackLimitX = " + FEndCol + ")");
                        //if (obj != null)
                        //{
                        //    UseAwayFork = "1";
                        //}
                    }

                }
                if (UseAwayFork == "-")
                {
                    devinfo = Model.CGetInfo.GetDeviceInfo(FENDDEVICE);
                    if (devinfo != null)
                    {
                        if (Microsoft.VisualBasic.Information.IsNumeric(FENDCELL) == true)
                        {
                            obj = dbo.GetSingle("SELECT F_UseAwayFork FROM T_Base_AGV_Gate WHERE (F_ChannelsIndex=" + FENDDEVICE + ") and ( F_AGVGateDeviceIndex= " + FENDCELL + ")").ToString();
                            if (obj != null)
                            {
                                UseAwayFork = obj.ToString();
                            }
                        }
                        else
                        {
                            if (devinfo.DoubleFork == "1")
                            {
                                UseAwayFork = "0";
                            }
                            else if (devinfo.DoubleFork == "2")
                            {
                                UseAwayFork = "1";
                            }

                        }
                        if (FStartCol > 0)
                        {//开始列有数据是巷道货位判断是否为极限列，以极限列为准分配货叉
                            //obj = dbo.GetSingle("SELECT F_ForwardLimitX FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = " + flaneway + ") AND (F_ForwardLimitX = " + FStartCol + ")");
                            //if (obj != null)
                            //{
                            //    UseAwayFork = "0";
                            //}
                            //obj = dbo.GetSingle("SELECT F_BackLimitX FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = " + flaneway + ") AND (F_BackLimitX = " + FStartCol + ")");
                            //if (obj != null)
                            //{
                            //    UseAwayFork = "1";
                            //}
                        }

                    }

                }
            }
            //if (FENDDEVICE==13001||FENDDEVICE==13002)
            //{
            //    //FENDDEVICE = 12072;
            //}
            //20110428 remark 1280，64取空 " + dvIOC[i]["CONTROL_REMARK"] + "
            string typeStatus = "-1";
            if (dvIOC[i]["MANAGE_TASK_TYPE"].ToString() == "2")
            {
                typeStatus = "0";
            }
            sql =$"INSERT INTO T_Manage_Task" +
            "(FID, F_ManageTaskKindIndex,FMANAGEID,F_RELATIVECONTORLID,FPALLETBARCODE,FMANAGETASKTYPE,FCONTROLTASKTYPE, FTASKLEVEL, FISRETURN," +
            "FSTARTWAREHOUSE, FSTARTCELL, FSTARTDEVICE,FENDWAREHOUSE,FENDCELL,FENDDEVICE, " +
            "FSTATUS, FBEGTIME, FENDTIME,FIntoStepOK,FREMARK,FLANEWAY,FSTACK,FUseAwayFork,FStartCol,FStartLayer,FEndCol,FEndLayer ,BOX_QUANTITY,UNPACK_QUANTITY)" +
            "VALUES (" + dvIOC[i]["CONTROL_ID"] + ",1," + dvIOC[i]["MANAGE_ID"] + "," +
            dvIOC[i]["RELATIVE_CONTROL_ID"] + ",'" + dvIOC[i]["STOCK_BARCODE"] +
            "','" + dvIOC[i]["MANAGE_TASK_TYPE"] + "','" + dvIOC[i]["CONTROL_TASK_TYPE"] + "'," + FTASKLEVEL + ",'"
            + 0 + "','" + dvIOC[i]["START_WAREHOUSE_CODE"] + "','" + FSTARTCELL + "','"
            + FSTARTDEVICE + "','" + dvIOC[i]["END_WAREHOUSE_CODE"] + "','" + FENDCELL + "','" + FENDDEVICE + "','"+ typeStatus + "','" + Convert.ToDateTime(dvIOC[i]["CONTROL_BEGIN_TIME"]).ToString("yyyy-MM-dd HH:mm:ss") + "','"
            + dvIOC[i]["CONTROL_END_TIME"] + "','" + 0 + "',''," + flaneway + "," +
            stackno + ",'" + UseAwayFork + "'," + FStartCol + "," + FStartLayer + "," + FEndCol + "," + FEndLayer + "," + Convert.ToInt32(dvIOC[i]["BOX_QUANTITY"]) + "," + Convert.ToInt32(dvIOC[i]["UNPACK_QUANTITY"]) + ")";//20110318
            int rc = dbo.ExecuteSql(sql);
            if (rc == 0) return "-";
            else
            {
                if (UseAwayFork == "1")
                {
                    UseAwayFork = "0";
                }
                else if (UseAwayFork == "0")
                {
                    UseAwayFork = "1";
                }
                //20101011
                dboM.ExecuteSql("update IO_CONTROL set CONTROL_STATUS=" + Model.CGeneralFunction.TASKCONTROLREADED + " where CONTROL_ID=" + dvIOC[i]["CONTROL_ID"]);
              //  CommonClassLib.CCarryConvert.WriteDarkCasket("CObtainTask", "管理CNTROL任务ID" + dvIOC[i]["CONTROL_ID"],"调度任务ID"+, (dt2 - dt1).ToString());
                                
                return UseAwayFork;
            }
        }
        /// <summary>
        /// 返回关联任务的CONTROL_ID
        /// </summary>
        /// <param name="fid"></param>
        /// <returns></returns>
        static int GetDouleForkFID(int fid)
        {//CONTORL_BATCH  LOGIC_AREA END_DEVICE_CODE START_DEVICE_CODE
            DataView dv = dboM.ExceSQL("select * from IO_CONTROL where CONTROL_ID="+fid).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                int minFid = -1; double minX = -1;
                char[] cc=new char[1]{'-'};
                DataView dv0 = dboM.ExceSQL("select * from IO_CONTROL where CONTROL_STATUS=0 and CONTORL_BATCH='" +
                    dv[0]["CONTORL_BATCH"] + "' and LOGIC_AREA='" + dv[0]["LOGIC_AREA"] + "' and END_DEVICE_CODE='" +
                    dv[0]["END_DEVICE_CODE"] + "' and START_WAREHOUSE_CODE='" + dv[0]["START_WAREHOUSE_CODE"] + "'").Tables[0].DefaultView;
                if (dv[0]["START_DEVICE_CODE"].ToString().IndexOf("-") < 0) return -1;
                string[] sp1=dv[0]["START_DEVICE_CODE"].ToString().Split(cc),sp2;

                for (int i = 0; i < dv0.Count; i++)
                {//START_DEVICE_CODE z-x-y 
                    if (dv0[0]["START_DEVICE_CODE"].ToString().IndexOf("-") < 0) continue ;
                    if (EqualCellDoubleFork(dv[0]["START_DEVICE_CODE"].ToString(), dv0[0]["START_DEVICE_CODE"].ToString(), dv[0]["START_WAREHOUSE_CODE"].ToString()) == false )
                    {//不符合双叉原则
                        continue;
                    }
                    if (InSameLaneWay(dv[0]["START_DEVICE_CODE"].ToString(), dv0[0]["START_DEVICE_CODE"].ToString(), dv[0]["START_WAREHOUSE_CODE"].ToString()) == false)
                    {//不在一个巷道
                        continue;
                    }
                    sp2=dv0[0]["START_DEVICE_CODE"].ToString().Split(cc);
                    //1、优先考虑：同一巷道的Z，临X（差值是1），同Y，符合双叉原则；
                    if ((sp1[2] == sp2[2])&&(Math.Abs(int.Parse(sp2[1])-int.Parse(sp1[1]))==1))
                    {
                        return int.Parse(dv0[i]["CONTROL_ID"].ToString());
                    }
                    //2、其次：同一巷道的Z，X差值平方+Y差值平方，符合双叉原则；
                    if (minX > (Math.Pow(Math.Abs(int.Parse(sp2[1]) - int.Parse(sp1[1])), 2) + Math.Pow(Math.Abs(int.Parse(sp2[2]) - int.Parse(sp1[2])), 2)))
                    {
                        minX = Math.Pow(Convert.ToDouble(Math.Abs(decimal.Parse(sp2[1]) - decimal.Parse(sp1[1]))), 2) + Math.Pow(Convert.ToDouble(Math.Abs(decimal.Parse(sp2[2]) - decimal.Parse(sp1[2]))), 2);
                        minFid = int.Parse(dv0[i]["CONTROL_ID"].ToString());
                    }
                    
                }
                return minFid;

            }
            else
            {
                return -1;
            }
        }
        /// <summary>
        /// 判断两个货位是否满足双叉原则
        /// </summary>
        /// <param name="Zxy">货位1</param>
        /// <param name="Zxy1">货位2</param>
        /// <param name="warehouse">库房位置</param>
        /// <returns></returns>
        static bool EqualCellDoubleFork(string Zxy,string Zxy1,string warehouse)
        {
            char[] cc = new char[1] { '-'};
            string[] sp = Zxy.Split(cc);
            string[] sp1 = Zxy1.Split(cc);
            char DoubleFork = '0', DoubleFork1 = '0';
            int z = int.Parse(sp[0]), x = int.Parse(sp[1]), y = int.Parse(sp[2]), z1 = int.Parse(sp1[0]), x1 = int.Parse(sp1[1]), y1 = int.Parse(sp1[2]);
            object ob,ob1;
            try
            {
                //考虑极限货位：如果其中一个是前极限货位，另外一个必须为非前极限货位；
                //如果其中一个是后极限货位，另外一个必须为非后极限货位
                ob = dbo.GetSingle("SELECT FLaneWay FROM  ST_CELL WHERE FCELLCODE = '"+Zxy+"'");
                #region 考虑极限货位
                ob1 = dbo.GetSingle("SELECT F_LaneDeviceIndex FROM T_Base_LaneInfo where (F_LaneDeviceIndex =" + ob + ") and (F_ForwardLimitX=" + x + ")  and (F_ForwardLimitX=" + x1 + ")");
                if (ob1 != null)
                {
                    return false;
                }
                ob1 = dbo.GetSingle("SELECT F_LaneDeviceIndex FROM T_Base_LaneInfo where (F_LaneDeviceIndex =" + ob + ") and (F_BackLimitX=" + x + ")  and (F_BackLimitX=" + x1 + ")");
                if (ob1 != null)
                {
                    return false;
                }

                #endregion
                DoubleFork =char.Parse( Model.CGeneralFunction.GetDoubleForkFromST_CELL(z,x,y,warehouse).ToString());
                
                if ((z == 0) && (x == 0) && (y == 0))
                {
                    return false;
                }
                else
                {
                    DoubleFork1 =char.Parse( Model.CGeneralFunction.GetDoubleForkFromST_CELL(z1, x1, y1, warehouse).ToString());
                    //0,1,-
                    if (x>=x1)
                    {
                        if (DoubleFork == '1')
                        {
                            if (DoubleFork1 != '1') return true;
                            else
                            {
                                return false;
                            }
                        }
                        else if (DoubleFork=='0')
                        {
                            return false;
                            
                        }
                        else //'-'
                        {
                            if (DoubleFork1 == '1') return false;
                            else
                            {
                                return true;
                            }
                        }
                       
                    }
                    else//x1>x
                    {
                        if (DoubleFork1 == '1')
                        {
                            if (DoubleFork != '1') return true;
                            else
                            {
                                return false;
                            }
                        }
                        else if (DoubleFork1 == '0')
                        {
                            return false;

                        }
                        else //'-'
                        {
                            if (DoubleFork == '1') return false;
                            else
                            {
                                return true;
                            }
                        }
                    }
                    
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ob = null;
                ob1 = null;
                cc=null;
                sp = null;
                sp1 = null;
            }

        }

        static bool InSameLaneWay(string Zxy, string Zxy1, string warehouse)
        {

            DataView dv = dbo.ExceSQL("SELECT FLaneWay FROM ST_CELL WHERE (FCELLCODE = '" + Zxy + "') and FWAREHOUSE='"+warehouse+"'").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                DataView dv1 = dbo.ExceSQL("SELECT FLaneWay FROM ST_CELL WHERE (FCELLCODE = '" + Zxy1 + "') and FWAREHOUSE='" + warehouse + "'").Tables[0].DefaultView;
                if (dv1.Count > 0)
                {
                    if (dv[0]["FLaneWay"].ToString() == dv1[0]["FLaneWay"].ToString())
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 出库任务数量控制
        /// </summary>
        /// <param name="enddevice"></param>
        /// <returns></returns>
        static int ManageCountControl(string enddevice)
        {
            int count = 0;
            int device = 0;
            if (!int.TryParse(enddevice, out device))
            {
                count = 100;
                return count;
            }
            DataView dv= dbo.ExceSQL("select * from t_base_device_taskcontrol where device_id =" + Convert.ToInt64(enddevice)).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                count = Convert.ToInt32(dv[0]["manage_max"]);
            }
            else
            {
                count = 100;
            }

            return count;
        }


    }
}
