using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DBFactory;
using ICommLayer;
using CommLayerFactory;
using Microsoft.VisualBasic;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 
    /// 一、下位机给上位机发送现场控制触摸屏申请信号：
    /// 1-重发当前设备指令
    /// 2-申请修改当前设备所执行任务的目标位置
    /// 3-报告当前设备所执行的任务完成
    /// 4-删除当前设备所执行的任务（托盘拿走）
    /// 二、检测PLC创建自动调度任务请求
    /// </summary>
    public class CListenPLCAsk
    {
        string _listenPLCAskError="";

        public string ListenPLCAskError
        {
            get { return _listenPLCAskError; }
            set { _listenPLCAskError = value; }
        }
        DBOperator dboM =CStaticClass.dboM;
        DBOperator dbo = CStaticClass.dbo;
        CCommonFunction ccf = new CCommonFunction();
        CGetState cgs = new CGetState();
        ISendDeviceOrder sdo;
        Model.MDevice devinfo;
        public CListenPLCAsk()
        {

        }
        
        /// <summary>
        /// 检测PLC创建自动调度任务请求:1:下位机给上位机发送现场控制触摸屏申请信号;2：叠盘机上报叠盘完成；
        /// 3：PLC码盘完成；4：条码扫描器申请入库任务；5：拆盘机申请空托盘组出库
        /// </summary>
        public void DealwithPLCAsk()
        {
            //20091128
            int[] bc;
            string sql = "";
            StringBuilder[] wv = { new StringBuilder("2") };
            StringBuilder[] witemnames = { new StringBuilder("") };
            DataView dv; DataView dvbc; DataView dvm; 
            //DataView dvw; DataView dv11;
            DataView dv0; DataView dplc; DataView dvma;
            //DataView dvp; 
            DataView dvs;
            try
            {
                dv = dbo.ExceSQL("SELECT T_Base_PLC_Ask.F_DeviceIndex,T_Base_PLC_Ask.F_BindingDevice, F_Askkind,F_TaskIndex,F_BarCode,F_Remark" +
                   ",F_FirstProject,F_BoxBarcode FROM T_Base_Device,T_Base_PLC_Ask" +
                   " where  T_Base_Device.F_DeviceIndex=T_Base_PLC_Ask.F_DeviceIndex " +
                   " order by T_Base_Device.F_DeviceIndex desc").Tables[0].DefaultView;
                for (int i = 0; i < dv.Count; i++)
                {
                    int deviceindex = Convert.ToInt32(dv[i]["F_DeviceIndex"]);
                    devinfo = Model.CGetInfo.GetDeviceInfo(deviceindex);
                    witemnames[0].Remove(0, witemnames[0].Length);
                    witemnames[0].Append(Model.CGeneralFunction.DBGet).Append(",byte").Append(Convert.ToString(devinfo.Dbw2Address + 0));
                    sdo = CommModeCreate.CreateSendDeviceOrder(deviceindex);
                    #region 下位机给上位机发送现场控制触摸屏申请信号
                    if (dv[i]["F_Askkind"].ToString() == "1")//下位机给上位机发送现场控制触摸屏申请信号
                    {
                        //gds = CommModeCreate.CreateGetDeviceState(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        //bc = gds.GetDeviceState(Convert.ToInt32(dv[i]["F_DeviceIndex"]), 64777);
                        bc = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        if (bc == null) continue;
                        //bc[3];//设备索引（当前申请设备的索引）
                        //bc[4];//任务号（需要修改目标位置的任务号）

                        int bcz = 0;
                        string barcode = string.Empty;
                        for (int j = 5; j < 21; j++)
                        {
                            bcz = bcz + bc[j];
                            barcode += Convert.ToChar(bc[j]);
                        }
                        if (Information.IsDate(dv[i]["F_Remark"]))//20110513
                        {
                            if (Convert.ToDateTime(dv[i]["F_Remark"]).AddSeconds(5) > DateTime.Now)//如果5s内连续读到条码，不进行处理
                            {
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "5秒内触摸屏重复申请", dv[i]["F_DeviceIndex"].ToString(), "");

                                continue;

                            }

                        } 

                        #region 申请重发当前设备指令

                        if (bc[2] == 1)//命令字
                        {
                            //20110518 在设备空闲时响应重发申请
                            int[] state;
                            state = CStaticClass.GetDeviceState(bc[3]);
                            if (state == null)
                            {
                                continue;
                            }

                            if(state[1]!=0)
                            {
                                state = null;
                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("4");
                                sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex );
                                continue;
                            }
                            int fid = 0;
                            int mankind = 0;
                            if (bc[4] > 0)
                            {//20090928 and F_DeviceIndex=" + bc[3] + "
                                //20091128
                                dvbc = dbo.ExceSQL("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_RouteID FROM T_Monitor_Task WHERE F_MonitorIndex = '" +
                                bc[4] + "' order by F_MonitorIndex asc").Tables[0].DefaultView;
                                if (dvbc.Count > 0)
                                {//20090925
                                    fid = ccf.GetManageTaskIndexfromMonitor(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                    mankind = ccf.GetManageTaskKindIndexFromMonitor(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                    if (DeviceInRouteSub(bc[3], Convert.ToInt32(dvbc[0]["F_RouteID"])) == true)
                                    {

                                        RestoreDevice(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));

                                        //记录任务号
                                        dbo.ExceSQL("update T_Base_PLC_Ask set F_TaskIndex='" + bc[4]
                                            + "' where F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                                    }
                                    else
                                    {
                                        dbo.ExceSQL("UPDATE T_Manage_Task SET FCurrentLocation=" + bc[3] + " where FID=" + fid + " and F_ManageTaskKindIndex=" + mankind + "");
                                        //判断是否需要向管理申请改道：如果本主路径的所有子路经都不可用就需要向管理申请改道，否则：调度选择一个可用的子路经，自行改道
                                        //20091005
                                        if (GetUseableRouteIDSub(fid, mankind, bc[3]) == false)
                                        {
                                            if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                            {//20091107
                                                GetUsableDestination(fid, mankind);
                                            }
                                        }
                                    }
                                }
                            }
                            else if (bcz > 0)
                            {// 20090928 and F_DeviceIndex=" + bc[3] + "
                                //使用条码查询调度任务号，向发送bc[3]设备索引（当前申请设备的索引）重发命令
                                //20091128
                                dvbc = dbo.ExceSQL("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_RouteID FROM T_Monitor_Task WHERE F_TxtParam = '" +
                                barcode + "' order by F_MonitorIndex asc").Tables[0].DefaultView;
                                if (dvbc.Count > 0)
                                {//20090925
                                    fid = ccf.GetManageTaskIndexfromMonitor(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                    mankind = ccf.GetManageTaskKindIndexFromMonitor(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                    if (DeviceInRouteSub(bc[3], Convert.ToInt32(dvbc[0]["F_RouteID"])) == true)
                                    {
                                        if (dvbc[0]["F_NumParam4"].ToString() == bc[3].ToString())
                                        {
                                            AssociateComplete(Convert.ToInt32(dvbc[0]["F_DeviceIndex"]), Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                        }
                                        else
                                        {

                                            RestoreDevice(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));

                                            //记录新条码
                                            dbo.ExceSQL("update T_Base_PLC_Ask set F_BarCode='" + barcode
                                                + "' where F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                                        }
                                    }
                                    else
                                    {
                                        dbo.ExceSQL("UPDATE T_Manage_Task SET FCurrentLocation=" + bc[3] + " where FID=" + fid + " and F_ManageTaskKindIndex=" + mankind + "");
                                        //判断是否需要向管理申请改道：如果本主路径的所有子路经都不可用就需要向管理申请改道，否则：调度选择一个可用的子路经，自行改道
                                        //20091005
                                        if (GetUseableRouteIDSub(fid, mankind, bc[3]) == false)
                                        {
                                            if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                            {//20091107
                                                GetUsableDestination(fid, mankind);
                                            }
                                        }
                                    }
                                }
                            }
                            string dtime = DateTime.Now.ToString("u");
                            dtime = dtime.Substring(0, dtime.Length - 1);

                            dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");

                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("4");
                            sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex);
                        }

                        #endregion


                        #region 申请修改当前设备所执行任务目标位置

                        else if (bc[2] == 2)//命令字
                        {
                            //20090925
                            int fid = 0;
                            int mankind = 0;
                            if (bc[4] > 0)
                            {   //20091128
                                dvbc = dbo.ExceSQL("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_MonitorIndex = '" +
                                bc[4] + "' order by F_MonitorIndex asc").Tables[0].DefaultView;
                                if (dvbc.Count > 0)
                                {
                                    fid = ccf.GetManageTaskIndexfromMonitor(bc[4]);
                                    mankind = ccf.GetManageTaskKindIndexFromMonitor(bc[4]);
                                }
                            }
                            else if (bcz > 0)
                            {
                                //使用条码查询调度任务号，向发送bc[3]设备索引（当前申请设备的索引）重发命令
                                //20091128
                                dvbc = dbo.ExceSQL("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_TxtParam = '" +
                                barcode + "' order by F_MonitorIndex asc").Tables[0].DefaultView;
                                if (dvbc.Count > 0)
                                {

                                    fid = ccf.GetManageTaskIndexfromMonitor(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                    mankind = ccf.GetManageTaskKindIndexFromMonitor(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));

                                }
                            }
                            else
                            {
                                continue;
                            }
                            ////申请修改当前设备所执行任务目标位置的F_TaskIndex重复时不允许相应申请
                            //if (bc[4] == Convert.ToInt32(dv[i]["F_TaskIndex"]))
                            //{
                            //    continue;
                            //}
                            //记录申请的设备索引bc[3]到调度任务的FCurrentLocation;//设备索引（当前申请设备的索引）
                            //20090925


                            dbo.ExceSQL("UPDATE T_Manage_Task SET FCurrentLocation=" + bc[3] + " where FID=" + fid + " and F_ManageTaskKindIndex=" + mankind + "");
                            //判断是否需要向管理申请改道：如果本主路径的所有子路经都不可用就需要向管理申请改道，否则：调度选择一个可用的子路经，自行改道
                            //20091005
                            if (GetUseableRouteIDSub(fid, mankind, bc[3]) == false)
                            {
                                if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                                {//20091107
                                    GetUsableDestination(fid, mankind);
                                }
                            }
                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("5");
                            sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex );
                        }

                        #endregion

                        #region PLC上报完成
                        else if (bc[2] == 3)
                        {
                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            //20090915
                            if (bc[4] > 0)
                            {
                                //20090915 and F_DeviceIndex=" + bc[3] + "
                                //20091128
                                dvbc = dbo.ExceSQL("SELECT F_MonitorIndex,F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_MonitorIndex = '" +
                                bc[4] + "' order by F_MonitorIndex asc").Tables[0].DefaultView;
                                if (dvbc.Count > 0)
                                {
                                    devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dvbc[0]["F_DeviceIndex"]));
                                    bool snyc = Model.CGeneralFunction.DoubleForkIfSync(bc[4], Convert.ToInt32(dvbc[0]["F_DeviceIndex"]), devinfo.DeviceKind);
                                    string[] df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(bc[4], Convert.ToInt32(dvbc[0]["F_DeviceIndex"]));

                                    AssociateComplete(Convert.ToInt32(dvbc[0]["F_DeviceIndex"]), bc[4]);
                                    //判断关联任务20110422

                                    if (devinfo.DeviceKind == 1 && devinfo.IfCorrelDoubleFork == "1")//对于双叉堆垛机
                                    {
                                        if (snyc == true)
                                        {
                                            //string[] df = Model.CGeneralFunction.GetDoubleForkMonitorInfo(bc[4], Convert.ToInt32(dvbc[0]["F_DeviceIndex"]));
                                            if (df != null)
                                            {

                                                AssociateComplete(Convert.ToInt32(dvbc[0]["F_DeviceIndex"]), Convert.ToInt32(df[0]));

                                            }
                                        }
                                    }
                                }
                            }
                            else if (bcz > 0)
                            {
                                //使用条码查询调度任务号
                                //20091128
                                dvbc = dbo.ExceSQL("SELECT F_MonitorIndex,F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2," +
                                "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_TxtParam = '" +
                                barcode + "' order by F_MonitorIndex asc").Tables[0].DefaultView;
                                if (dvbc.Count > 0)
                                {
                                    if (dvbc[0]["F_NumParam4"].ToString() == bc[3].ToString())
                                    {
                                        AssociateComplete(Convert.ToInt32(dvbc[0]["F_DeviceIndex"]), Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                    }
                                    else
                                    {
                                        wv[0].Remove(0, wv[0].Length);
                                        wv[0].Append("37");
                                    }
                                }
                            }
                            //20090915

                            string dtime = DateTime.Now.ToString("u");
                            dtime = dtime.Substring(0, dtime.Length - 1);

                            dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");


                            sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex );

                        }
                        #endregion

                        #region 删除当前设备所执行的任务(4)（托盘拿走）
                        else if (bc[2] == 4)//命令字
                        {
                            //20090915
                            if (bc[4] > 0)
                            {
                                int fid = ccf.GetManageTaskIndexfromMonitor(bc[4]);
                                int mti = ccf.GetManageTaskKindIndexFromMonitor(bc[4]);
                                dbo.ExceSQL("update T_Manage_Task set FExceptionNO=" + Model.CGeneralFunction.TASKDELETE + " where (F_ManageTaskKindIndex = " + mti + ") AND (FID = " + fid + ")");
                                dbo.ExceSQL("update T_Monitor_Task set F_STATUS=-1 where F_ManageTaskKindIndex=" + mti + " and F_ManageTaskIndex=" + fid + " and F_STATUS=0");
                                //通知管理程序删除整个调度任务
                                //20091128
                                dvm = dbo.ExceSQL("SELECT F_ManageTaskKindIndex, F_ManageTaskIndex,F_DeviceIndex,F_MonitorIndex " +
                                " FROM T_Monitor_Task Where  F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex= " +
                                mti).Tables[0].DefaultView;
                                if (dvm.Count > 0)
                                {
                                    for (int ii = 0; ii < dvm.Count; ii++)
                                    {
                                        if (Convert.ToInt32(dv[ii]["F_Status"]) >= 1)
                                        {
                                            cgs.ActionComplete(Convert.ToInt32(dvm[ii]["F_DeviceIndex"]), Convert.ToInt32(dvm[ii]["F_MonitorIndex"]), 1);
                                        }
                                        else
                                        {
                                            cgs.ActionComplete(Convert.ToInt32(dvm[ii]["F_DeviceIndex"]), Convert.ToInt32(dvm[ii]["F_MonitorIndex"]), Model.CGeneralFunction.TASKDELETE);
                                        }
                                    }
                                }
                            }
                            else if (bcz > 0)
                            {

                                //通知管理程序删除整个调度任务
                                //20091128
                                dvm = dbo.ExceSQL("SELECT F_ManageTaskKindIndex, F_ManageTaskIndex,F_DeviceIndex,F_MonitorIndex " +
                                " FROM T_Monitor_Task Where  F_TxtParam ='" + barcode + "'").Tables[0].DefaultView;
                                if (dvm.Count > 0)
                                {
                                    int fid = Convert.ToInt32(dvm[0]["F_ManageTaskIndex"]);
                                    int mti = Convert.ToInt32(dvm[0]["F_ManageTaskKindIndex"]);
                                    dbo.ExceSQL("update T_Manage_Task set FExceptionNO=" + Model.CGeneralFunction.TASKDELETE + " where (F_ManageTaskKindIndex = " + mti + ") AND (FID = " + fid + ")");
                                    dbo.ExceSQL("update T_Monitor_Task set F_STATUS=-1 where F_ManageTaskKindIndex=" + mti + " and F_ManageTaskIndex=" + fid + " and F_STATUS=0");
                                    for (int ii = 0; ii < dvm.Count; ii++)
                                    {
                                        if (Convert.ToInt32(dv[ii]["F_Status"]) >= 1)
                                        {
                                            cgs.ActionComplete(Convert.ToInt32(dvm[ii]["F_DeviceIndex"]), Convert.ToInt32(dvm[ii]["F_MonitorIndex"]), 1);
                                        }
                                        else
                                        {
                                            cgs.ActionComplete(Convert.ToInt32(dvm[ii]["F_DeviceIndex"]), Convert.ToInt32(dvm[ii]["F_MonitorIndex"]), Model.CGeneralFunction.TASKDELETE);
                                        }
                                    }
                                }
                            }
                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("3");
                            sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex);
                        }
                        #endregion


                    }
                    #endregion

                    if (CStaticClass.DeviceErrorAutoModifyRoutePath == "1")
                    {//20091107
                        #region 上位机监测到下位机故障堵塞交通，自动变更路径：用于一个起点多个终点的复杂输送机构
                        //F_Askkind=9
                        //监听某一个调度任务在十字路口处停留超过30秒，首先检测自身没故障，然后检测进入巷道的输送机构与堆垛机是否故障，
                        //如果任意一个设备有故障，申请改道。
                        //F_FirstProject巷道输送机组；F_Remark堆垛机；F_BoxBarcode巷道；F_BindingDevice次数
                        if (dv[i]["F_Askkind"].ToString() == "9")
                        {
                            int[] state = CStaticClass.GetDeviceState(deviceindex);
                            int errCount = 0;
                            string[] sp; char[] cc = new char[1] { ';' };
                            if (state[1] >= 30)
                            {
                                //20091128
                                sp = null;
                                cc = null;
                                state = null;
                                continue;
                            }
                            if (state[2].ToString() == dv[i]["F_TaskIndex"].ToString())
                            {
                                dbo.ExceSQL("update T_Base_PLC_Ask set F_BindingDevice=F_BindingDevice+1 where F_DeviceIndex=" + deviceindex + "");

                            }
                            else
                            {
                                dbo.ExceSQL("update T_Base_PLC_Ask set F_BindingDevice=0,F_TaskIndex=" + state[2] + " where F_DeviceIndex=" + deviceindex + "");

                            }
                            //20091128
                            dplc = dbo.ExceSQL("select F_BindingDevice from T_Base_PLC_Ask  where F_DeviceIndex=" + deviceindex + " and F_BindingDevice>=100").Tables[0].DefaultView;
                            if (dplc.Count > 0)
                            {
                                //20091128
                                dvma = dbo.ExceSQL("select FID, F_ManageTaskKindIndex,FENDDEVICE fromT_Manage_Task where F_ManageTaskKindIndex=" +
                                    ccf.GetManageTaskKindIndexFromMonitor(state[2]) + " and fid=" + ccf.GetManageTaskIndexfromMonitor(state[2])
                                    + " and FENDDEVICE=" + dv[i]["F_BoxBarcode"] + "").Tables[0].DefaultView;
                                if (dvma.Count > 0)
                                {

                                    int[] state1 = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_Remark"]));
                                    if (state1[1] >= 30)
                                    {
                                        errCount = 1;
                                    }
                                    sp = dv[i]["F_FirstProject"].ToString().Split(cc);
                                    for (int jj = sp.GetLowerBound(0); jj <= sp.GetUpperBound(0); jj++)
                                    {
                                        state1 = CStaticClass.GetDeviceState(Convert.ToInt32(sp[jj]));
                                        if (state1[1] >= 30)
                                        {
                                            errCount = 1;
                                            break;
                                        }

                                    }
                                    if (errCount > 0)
                                    {
                                        //bool havegoods = true;
                                        //for (int jj = sp.GetLowerBound(0); jj <= sp.GetUpperBound(0); jj++)
                                        //{
                                        //    devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(sp[jj]));
                                        //    havegoods = (havegoods && devinfo.HaveGoods);
                                        //}
                                        //if (havegoods == true)
                                        //{
                                        //申请改道
                                        GetUsableDestination(ccf.GetManageTaskIndexfromMonitor(state[2]), ccf.GetManageTaskKindIndexFromMonitor(state[2]));
                                        //}
                                    }
                                    //20091128
                                    state1 = null;
                                }

                            }
                            //20091128
                            sp = null;
                            cc = null;
                            state = null;
                        }
                        #endregion
                    }

                    #region 叠盘完成 类型2 
                    if (dv[i]["F_Askkind"].ToString() == "2")
                    {

                        #region 与管理系统的交互
///*        
                        string recordedbarcode = string.Empty;
                        if (CStaticClass.GetOverlapStatus(Convert.ToInt32(dv[i]["F_DeviceIndex"])) == 1) // 获取叠盘机是否叠盘完成
                        {
                            deviceindex = Convert.ToInt32(dv[i]["F_BindingDevice"]);

                            if (CStaticClass.GetDevicePhotoelectric(ccf.GetSendOutDetect(Convert.ToInt32(dv[i]["F_BindingDevice"]))) != 1)// 获取叠盘机关联设备的开关的值 (有物)
                            {
                                continue;
                            }      
                            int[] state;
                            state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"])); //获取关联设备的状态数组
                            if (state == null)
                            {
                                continue;
                            }
                            if ((state[1] >= 30) || (state[1] == 1) || (state[1] == 2))//空闲时，采集数据
                            {
                                //20091128
                                state = null;
                                continue;

                            }
                            if (Information.IsDate(dv[i]["F_FirstProject"]))//20110513
                            {
                                if (Convert.ToDateTime(dv[i]["F_FirstProject"]).AddSeconds(5) > DateTime.Now)//如果5秒内上报叠盘完成，不进行处理(防止程序在电气响应前重复处理)
                                {
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "5秒内上报叠盘完成", deviceindex.ToString(), "");

                                    continue;

                                }

                            }
                           dv0 = dbo.ExceSQL("SELECT FSTARTDEVICE, FENDDEVICE FROM T_Manage_Task WHERE (FSTARTDEVICE = " + Convert.ToInt32(dv[i]["F_BindingDevice"]) + ") and FSTATUS=0").Tables[0].DefaultView;
                            if (dv0.Count > 0)
                            {
                                
                                continue;
                            }
                            dvbc = dboM.ExceSQL("SELECT DEVICE_CODE FROM IO_CONTROL_APPLY WHERE APPLY_TASK_STATUS=0 and DEVICE_CODE=" + deviceindex + "").Tables[0].DefaultView;
                            if (dvbc.Count > 0)
                            {
                                _listenPLCAskError = "输送机：" + deviceindex.ToString() + "上报叠盘离开时：有未处理的申请！";
                                continue;
                            }
                            string dtime = DateTime.Now.ToString("u");//20101028
                            dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                            recordedbarcode = GetPLCAskRecordBarCode(deviceindex);

                            if (recordedbarcode == string.Empty)
                            {
                                _listenPLCAskError = "输送机：" + deviceindex.ToString() + "上报叠盘离开时：未发现组垛信息！";
                                continue;
                            }
                   
                           // int ApplyID = 0;
                            int ControlID = 0;
                          //  ccf.GetApplyID(out ApplyID, out ControlID);
                            sql = "INSERT INTO IO_CONTROL_APPLY(control_id ,WAREHOUSE_CODE , CONTROL_APPLY_TYPE,DEVICE_CODE, STOCK_BARCODE,APPLY_TASK_STATUS, CREATE_TIME)VALUES " +
                             "("  + ControlID + ", 1,3," + deviceindex + ",'" + recordedbarcode + "', 0,'" + dtime + "')";  //应该允许叠完自动离开
                       
                            try
                            {
                                dboM.ExceSQL(sql);
                                dbo.ExceSQL("insert into t_bak_uploadmsg (barcode,time,deviceindex) values ('" + recordedbarcode + "','" + dtime + "'," + deviceindex + ")");
                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("2");
                                sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex  );// 给叠盘机状态恢复为空闲状态
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "叠盘完成申请离开", deviceindex.ToString(), recordedbarcode);
                                dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='',F_FirstProject='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");//记录叠盘完成时间
                            }
                            catch (Exception ex)
                            {
                                _listenPLCAskError = "向管理上报叠盘离开时：" + ex.Message;
                            }

                        }
                       
//*/                       
                        #endregion

                    }
                    #endregion
  
                    #region 入库条码扫描器申请入库任务 类型4
                    if (dv[i]["F_Askkind"].ToString() == "4")//条码扫描器申请入库任务
                    {

                        int[] state;

                        #region 检查电气信号
                        state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"]));
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1) || (state[1] == 2))//空闲时，采集数据
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndex(Convert.ToInt32(dv[i]["F_BindingDevice"]))) != 1)//有物
                        {
                            
                            state = null;
                            continue;
                        }
                        #region 条码上报后处理
                        string barcode = CStaticClass.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        if (barcode == null)
                        {
                            continue; //入库申请时，未上报条码不处理
                        }

                        if (barcode == string.Empty)
                            barcode = CStaticClass.BarcodeNull;  //表示PLC未读到条码
                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);
                        #endregion

                        //20091128
                        #endregion 
                       
                        #region 申请入库任务前进行校验，校验通过才向管理申请入库任务,校验失败不给PLC应答信号，只提示管理员去处理

                        dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='" + barcode + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");

                        if (Information.IsDate(dv[i]["F_Remark"]))//20110513
                        {
                            if (Convert.ToDateTime(dv[i]["F_Remark"]).AddSeconds(5) > DateTime.Now)//如果5s内连续读到条码，不进行处理
                            {
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "5秒内上报申请条码", dv[i]["F_DeviceIndex"].ToString(), barcode);

                                continue;

                            }
                        }
    
                        int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        //不申请则不清除条码扫描的值只提示管理员去处理 20131219
                        if (!barcode.Equals(CStaticClass.BarcodeNull))//扫描到条码的处理 11111111111111 表示未读到条码
                        {
                            string Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task " +
                            "where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex)  And F_DeviceCommandIndex=6 And (FCONTROLTASKTYPE=2 Or F_NumParam1 ={0})And F_TxtParam like '%{1}%'", dcode, barcode);
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {

                                string msg = DateTime.Now.ToString("u").TrimEnd('Z') + ":" + dcode .ToString ()+ "扫描的条码" + barcode + "已存在任务";
                                FrmMain.FormInstance.notifyIcon1.BalloonTipText = msg;
                                FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", msg, System.Windows.Forms.ToolTipIcon.Warning);
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                continue;
                            }
                            Sql = "SELECT FPALLETBARCODE from T_Manage_Task where   FPALLETBARCODE like '%" + barcode + "%'";
                            //20091128
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {//20091128
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                           
                                _listenPLCAskError = "输送机：" + dcode.ToString() + "的扫描器向管理申请入库任务时：本地任务有相同的托盘号：" + barcode + "正在运行！";
                                FrmMain.FormInstance.notifyIcon1.BalloonTipText = _listenPLCAskError;
                                FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", _listenPLCAskError, System.Windows.Forms.ToolTipIcon.Warning);
                                continue;
                            }
                            //查找IOCONTROL中的任务
                            Sql = "SELECT STOCK_BARCODE from IO_CONTROL where STOCK_BARCODE like '%" + barcode + "%'  and CONTROL_STATUS<100";
                            dvs = dboM.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {//20091128
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                _listenPLCAskError = "输送机：" + dcode.ToString() + "的扫描器向管理申请入库任务时：管理系统调度任务有相同的托盘号：" + barcode + "正在运行！";
                                FrmMain.FormInstance.notifyIcon1.BalloonTipText = _listenPLCAskError;
                                FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", _listenPLCAskError, System.Windows.Forms.ToolTipIcon.Warning);
                                continue;
                            }
                           
                        }

                        dvs = dbo.ExceSQL("select * from T_Monitor_Task where F_DeviceIndex  =" + dcode + " and F_Status <2").Tables[0].DefaultView;
                        if (dvs.Count > 0)
                        {//20091128
                            //wv[0].Remove(0, wv[0].Length);
                            //wv[0].Append("2");
                            //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                            _listenPLCAskError = "输送机：" + dcode.ToString() + "的扫描器向管理申请入库任务时：" + barcode + "有任务未动作！";
                            FrmMain.FormInstance.notifyIcon1.BalloonTipText = _listenPLCAskError;
                            FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", _listenPLCAskError, System.Windows.Forms.ToolTipIcon.Warning);
                            continue;
                        }
                        dvbc = dboM.ExceSQL("SELECT DEVICE_CODE,STOCK_BARCODE FROM IO_CONTROL_APPLY WHERE APPLY_TASK_STATUS=0 and DEVICE_CODE=" + dcode + " and (STOCK_BARCODE like '%" + barcode + "%')").Tables[0].DefaultView;
                        if (dvbc.Count > 0)
                        {//20091128
                            
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                           
                            _listenPLCAskError = "输送机：" + dcode.ToString() + "的扫描器向管理申请入库任务时：管理系统有相同的托盘号：" + barcode + "尚未处理！";
                            FrmMain.FormInstance.notifyIcon1.BalloonTipText = _listenPLCAskError;
                            FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", _listenPLCAskError, System.Windows.Forms.ToolTipIcon.Warning);
                            continue;
                        }
                        #endregion

                        #region 向管理申请入库任务

                        string dtime = DateTime.Now.ToString("u");
                        dtime = dtime.Substring(0, dtime.Length - 1);
                        //int ApplyID = 0;
                        int ControlID = 0;
                      //  ccf.GetApplyID(out ApplyID, out ControlID);
                        int CONTROL_APPLY_TYPE = 1;
               
                            
                        sql = "INSERT INTO IO_CONTROL_APPLY(control_id ,WAREHOUSE_CODE, CONTROL_APPLY_TYPE,DEVICE_CODE, STOCK_BARCODE, APPLY_TASK_STATUS, CREATE_TIME,CONTROL_APPLY_REMARK)VALUES " +
                           "(" + ControlID + ",'1'," + CONTROL_APPLY_TYPE + "," + dcode + ",'" + barcode + "',0,'" + dtime + "','')";
                    
                        try
                        {
                           
                            dboM.ExceSQL(sql);
                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "申请入库任务", dv[i]["F_DeviceIndex"].ToString(), barcode);
                            dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");

                            
                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("2");
                                sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                            
                        }
                        catch (Exception ex)
                        {
                            _listenPLCAskError = "向管理申请入库任务：" + ex.Message;
                        }
                        #endregion

                    }
                    #endregion
                  
                    #region  空箱数量上报 类型10
                    if (dv[i]["F_Askkind"].ToString() == "10")//空箱数量校验
                    {


                        int[] state;
                        
                        state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"]));
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1) || (state[1] == 2))//空闲时，采集数据
                        {
                            //20091128
                            state = null;
                            continue;

                        }

                        devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        int DEVEICE = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        int temp = devinfo.Dbw2Address ;
                        int flag = CStaticClass.AllReturns[temp];//组箱完成信号
                        if (flag != 1)
                        {
                            continue;
                        }
                        else
                        {
                            string dtime = DateTime.Now.ToString("u");

                            dtime = dtime.Substring(0, dtime.Length - 1);
                            int number = CStaticClass.AllReturns[temp + 1];

                            int ApplyID = 0;
                            int ControlID = 0;
                            ccf.GetApplyID(out ApplyID, out ControlID);

                            string tempsql = "INSERT INTO IO_CONTROL_APPLY(control_apply_id，control_id ， CONTROL_APPLY_TYPE,DEVICE_CODE ,WAREHOUSE_CODE, APPLY_TASK_STATUS, CREATE_TIME,BOX_QUANTITY)VALUES " +
                             "(" + ApplyID + "," + ControlID + ", 1,'" + DEVEICE.ToString() + "',1,0,'" + dtime + "'," + number + ")";
                            dboM.ExceSQL(tempsql);
                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex );//
                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "数量上报完成", deviceindex.ToString(), number.ToString ());

                        }

                    }
                    #endregion

                    #region 码垛完成/拆跺完成申请入库 类型12
                    if (dv[i]["F_Askkind"].ToString() == "12")
                    {
                        int[] state;
                        state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"]));
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1) || (state[1] == 2))//空闲时，采集数据
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndex(Convert.ToInt32(dv[i]["F_BindingDevice"]))) != 1)//有物
                        {

                            state = null;
                            continue;
                        }
                        string barcode = CStaticClass.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        if (barcode == null)
                        {
                            // 机器人拆码垛位未上报条码不处理
                            continue;
                        }
                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);
                        dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='" + barcode + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");
                        if (barcode == "1111111111111111111111")
                        {
                            string msg = DateTime.Now.ToString("u").TrimEnd('Z') + ":" + Convert.ToInt32(dv[i]["F_BindingDevice"]).ToString() + "未扫描到条码，请到电气触摸屏上补充条码";
                            FrmMain.FormInstance.notifyIcon1.BalloonTipText = msg;
                            FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", msg, System.Windows.Forms.ToolTipIcon.Warning);
                            continue;
                        }
                        if (Information.IsDate(dv[i]["F_Remark"]))//20110513
                        {
                            if (Convert.ToDateTime(dv[i]["F_Remark"]).AddSeconds(5) > DateTime.Now)//如果5s内连续读到条码，不进行处理
                            {
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "5秒内上报申请条码", dv[i]["F_DeviceIndex"].ToString(), barcode);

                                continue;

                            }

                        }
                        int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        if (!barcode.Equals("1111111111111111111111"))//扫描到条码的处理
                        {

                            string Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task " +
                            "where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex)  And F_DeviceCommandIndex=6 And (FCONTROLTASKTYPE=2 Or F_NumParam1 ={0})And F_TxtParam like '%{1}%'", dcode, barcode);
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {

                                string msg = DateTime.Now.ToString("u").TrimEnd('Z') + ":" + dcode.ToString() + "扫描的条码" + barcode + "已存在任务";
                                FrmMain.FormInstance.notifyIcon1.BalloonTipText = msg;
                                FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", msg, System.Windows.Forms.ToolTipIcon.Warning);
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                continue;
                            }

                            Sql = "SELECT FPALLETBARCODE from T_Manage_Task where   FPALLETBARCODE like '%" + barcode + "%'";
                            //20091128
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {//20091128
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                _listenPLCAskError = "输送机：" + dcode.ToString() + "的扫描器向管理申请入库任务时：本地任务有相同的托盘号：" + barcode + "正在运行！";
                                continue;
                            }
                            //查找IOCONTROL中的任务
                            Sql = "SELECT STOCK_BARCODE from IO_CONTROL where STOCK_BARCODE like '%" + barcode + "%'  and CONTROL_STATUS<100";
                            dvs = dboM.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {//20091128
                                //wv[0].Remove(0, wv[0].Length);
                                //wv[0].Append("2");
                                //sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                _listenPLCAskError = "输送机：" + dcode.ToString() + "的扫描器向管理申请入库任务时：调度任务有相同的托盘号：" + barcode + "正在运行！";
                                continue;
                            }
                        }
                        int boxsum =0;
                        string dtime = DateTime.Now.ToString("u");
                        dtime = dtime.Substring(0, dtime.Length - 1);
                        int ApplyID = 0;
                        int ControlID = 0;
                        ccf.GetApplyID(out ApplyID, out ControlID);
                        int CONTROL_APPLY_TYPE = 10;//拆垛申请类型10
                        if (CStaticClass.GetRobotUnpack(16061) == 1) //拆跺完成
                        {
                            sql = "INSERT INTO IO_CONTROL_APPLY(control_apply_id，control_id ，WAREHOUSE_CODE, CONTROL_APPLY_TYPE,DEVICE_CODE, STOCK_BARCODE, APPLY_TASK_STATUS, CREATE_TIME,CONTROL_APPLY_REMARK)VALUES " +
                               "(" + ApplyID + "," + ControlID + ",'1'," + CONTROL_APPLY_TYPE + "," + dcode + ",'" + barcode + "',0,'" + dtime + "','')";
                               dboM.ExceSQL(sql);
                                dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");
                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("2");
                                sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "拆跺完成后申请入库任务", dv[i]["F_DeviceIndex"].ToString(), barcode);
                               continue;
                        }
                        else if (CStaticClass.GetRobotStatus(16063, out boxsum) == 1) //码垛完成
                        {
                            CONTROL_APPLY_TYPE = 2; //码垛申请类型2
                            string packresult =string.Empty;
                            string control_apply_parameter = GetPLCAskRecordBarCode(boxsum, out packresult);
                            if (packresult == string.Empty)
                            {
                                dbo.ExceSQL("insert into t_bak_uploadmsg (barcode,time,deviceindex) values ('" + control_apply_parameter + "','" + dtime + "'," + dcode + ")");
                                sql = "INSERT INTO IO_CONTROL_APPLY(control_apply_id，control_id ，WAREHOUSE_CODE, CONTROL_APPLY_TYPE,DEVICE_CODE, STOCK_BARCODE, APPLY_TASK_STATUS, CREATE_TIME,CONTROL_APPLY_REMARK,control_apply_parameter)VALUES " +
                                   "(" + ApplyID + "," + ControlID + ",'1'," + CONTROL_APPLY_TYPE + "," + dcode + ",'" + barcode + "',0,'" + dtime + "','','" + control_apply_parameter + "')";
                                dboM.ExceSQL(sql);

                                dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");
                                dbo.ExecuteSql("update T_Base_PLC_Ask set  F_BarCode='' where (F_DeviceIndex=16062)");  // 清除码箱记录的条码
                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("2");
                                sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码跺完成后申请入库任务", dv[i]["F_DeviceIndex"].ToString(), barcode + "**纸箱条码" + control_apply_parameter);
                            }
                            else
                            {
                                FrmMain.FormInstance.notifyIcon1.BalloonTipText = packresult;
                                FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", packresult, System.Windows.Forms.ToolTipIcon.Warning);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "接收码垛完成失败", deviceindex.ToString(), packresult);
                            }

                            continue;
                        }

                    }
                    #endregion

                    #region  码箱完成 类型13
                    if (dv[i]["F_Askkind"].ToString() == "13")
                    {
                        string barcode = string.Empty;
                        if (CStaticClass.GetPackBoxBarcodes(Convert.ToInt32(dv[i]["F_DeviceIndex"]), out barcode) == 1)
                        {
                            int[] state;
                            state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"]));
                            if (state == null)
                            {
                                continue;
                            }
                            if ((state[1] >= 30) || (state[1] == 1) || (state[1] == 2))//空闲时，采集数据
                            {
                                //20091128
                                state = null;
                                continue;

                            }
                            if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndex(Convert.ToInt32(dv[i]["F_BindingDevice"]))) != 1)//有物
                            {

                                state = null;
                                continue;
                            }
                            if (Information.IsDate(dv[i]["F_Remark"]))//20110513
                            {
                                if (Convert.ToDateTime(dv[i]["F_Remark"]).AddSeconds(3) > DateTime.Now)//如果同3s内连续读到条码，不进行处理
                                {
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "3秒内上报码箱条码", dv[i]["F_DeviceIndex"].ToString(), barcode);

                                    continue;

                                }
                            }  
                            string dtime = DateTime.Now.ToString("u").TrimEnd('Z');
                            string sReulst = string.Empty;
                            RecordBarCodeForDiePan(barcode,out sReulst);
                            if (sReulst == string.Empty)
                            {
                                dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");
                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("2");
                                sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "接收码箱完成", deviceindex.ToString(), barcode);
                            }
                            else
                            {
                                FrmMain.FormInstance.notifyIcon1.BalloonTipText = sReulst;
                                FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", sReulst, System.Windows.Forms.ToolTipIcon.Warning);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "接收码箱完成失败", deviceindex.ToString(), barcode);
                            }

                        }
                    }
                    #endregion

                    #region  控制滑块 类型14
                    if (dv[i]["F_Askkind"].ToString() == "14")
                    {
                          DataView dvboxtype =   dbo.ExceSQL ("select FID, BOX_TYPE from T_Manage_Task where FSTARTDEVICE =16003 and FENDDEVICE  =16003").Tables [0].DefaultView ;
                           if(dvboxtype.Count >0)
                           {
                               int fid = Convert.ToInt32((dvboxtype[0]["FID"]));
                               string boxtype = (dvboxtype[0]["BOX_TYPE"]).ToString();
                               wv[0].Remove(0, wv[0].Length);
                               wv[0].Append(boxtype);
                               sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                               dbo.ExceSQL ("delete from T_Manage_Task where FSTARTDEVICE =16003 and FENDDEVICE  =16003");
                              dboM.ExceSQL("update IO_Control set  CONTROL_STATUS=" + Model.CGeneralFunction.TASKFINISH + " where CONTROL_ID=" + fid);
                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "控制滑块", deviceindex.ToString(),"表型"+boxtype  );
                           } 
                    }
                    #endregion

                    #region 模拟管理系统生成RFID输送机置叠盘机的任务
                    if (dv[i]["F_Askkind"].ToString() == "11")
                    {
                        //continue;
                        int[] state;
                        state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"]));
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1))
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndexOut(Convert.ToInt32(dv[i]["F_BindingDevice"]))) != 1)
                        {
                            //20091128
                            state = null;
                            continue;
                        }


                        //dv0 = dbo.ExceSQL("SELECT FSTARTDEVICE, FENDDEVICE FROM T_Manage_Task WHERE (FSTARTDEVICE = " + Convert.ToInt32(dv[i]["F_BindingDevice"]) + ") and FSTATUS=0").Tables[0].DefaultView;
                        //if (dv0.Count > 0)
                        //{
                        //    continue;
                        //}
                        dv0 = dbo.ExceSQL("SELECT FSTATUS, FBEGTIME FROM T_Manage_Task WHERE (FSTARTDEVICE = " + Convert.ToInt32(dv[i]["F_BindingDevice"]) + ")").Tables[0].DefaultView;
                        if (dv0.Count > 0)//存在该起点的任务
                        {
                            if (dv0.Count >= 3)
                            {
                                continue;
                            }
                            int k;
                            for (k = 0; k < dv0.Count; k++)
                            {

                                if (Convert.ToInt32(dv0[k]["FSTATUS"]) == 0 || (Convert.ToDateTime(dv0[k]["FBEGTIME"]).AddSeconds(20) > DateTime.Now))
                                {
                                    break;
                                }

                            }
                            if (k < dv0.Count)
                            {
                                continue;
                            }

                        }

                        int fid = ccf.GetTempManageIdx();
                        //ccf.RecordMaxTempManageTaskFID(fid);

                        string dtime = DateTime.Now.ToString("u");//20101028
                        dtime = dtime.Substring(0, dtime.Length - 1);//20101028


                        sql = "INSERT INTO T_Manage_Task" +
                      "(FID, F_ManageTaskKindIndex,FPALLETBARCODE,FMANAGETASKTYPE,FCONTROLTASKTYPE, FTASKLEVEL, FISRETURN," +
                      "FSTARTWAREHOUSE, FSTARTCELL, FSTARTDEVICE, FENDWAREHOUSE,FENDDEVICE, FENDCELL, " +
                      "FSTATUS, FBEGTIME, FENDTIME,FIntoStepOK,FREMARK,FLANEWAY,FSTACK)" +
                      "VALUES (" + fid + ",2,'" + ccf.GetBarCode("WF") + "','0','3','1','1','" + ccf.GetWarehouseIndex() + "','-','"
                      + dv[i]["F_BindingDevice"] + "','" + ccf.GetWarehouseIndex() + "','" + dv[i]["F_Remark"] + "','-',"
                      + "'0','" + dtime + "','-','0','',0,0)";
                        dbo.ExceSQL(sql);

                    }
                    #endregion

                    #region 三层出库提升机处条码扫描分拣5
                    if (dv[i]["F_Askkind"].ToString() == "5")//出库提升机处条码扫描分拣
                    {

                        #region 向管理申请入库任务
                        //continue;

                        int[] state;
                        int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        state = CStaticClass.GetDeviceState(dcode);//条码所在输送机
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1))//空闲时，采集数据
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndexOut(dcode)) != 1)
                        {
                            //20091128
                            state = null;
                            continue;
                        }
                        //扫到的条码（全部非零）与记录的条形码不相等就认为是新条码
                        //gds = CommModeCreate.CreateGetDeviceState(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        //string barcode = gds.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]), 64777);
                        string barcode = CStaticClass.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        //barcode = "370070000001001";
                        if ((barcode == null) || (barcode == "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")) continue;
                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);
                        //20091128
                        dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='" + barcode + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");
                        if (Information.IsDate(dv[i]["F_Remark"]))//20110513
                        {
                            if (Convert.ToDateTime(dv[i]["F_Remark"]).AddSeconds(5) > DateTime.Now)//如果5s内连续读到条码，不进行处理
                            {
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "5秒内上报条码", dv[i]["F_DeviceIndex"].ToString(), barcode);

                                continue;

                            }

                        }

                        if (barcode == "111111111111111")//未扫描到条码的处理
                        {
                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                            _listenPLCAskError = "三层出库提升前分拣输送机：" + dcode.ToString() + "条码扫描器未扫描到表箱条码！";
                            continue;
                        }

                        //未扫到条码如何处理，是否需要人工输入
                        string Sql = string.Format("SELECT F_ManageTaskIndex,F_ManageTASKKINDINDEX,F_MonitorIndex from T_Monitor_Task where F_Status>=1 And F_DeviceCommandIndex=6 And F_NumParam4 ={0} And F_TxtParam like '%{1}%'", dcode, barcode);
                        //20091128
                        dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                        if (dvs.Count > 0)
                        {//20091128
                            string dtime = DateTime.Now.ToString("u");
                            dtime = dtime.Substring(0, dtime.Length - 1);

                            cgs.ActionComplete(dcode, Convert.ToInt32(dvs[0]["F_MonitorIndex"]), 1);
                            dbo.ExecuteSql("update T_Base_PLC_Ask set  F_Remark='" + dtime + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");

                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "提升出库分拣成功", dv[i]["F_DeviceIndex"].ToString(), barcode);

                        }
                        else
                        {
                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);

                            _listenPLCAskError = "输送机：" + dcode.ToString() + "条码扫描器上报的表箱码为：" + barcode + ",不存在对应的出库任务！";
                            continue;
                        }



                        #endregion
                    }
                    #endregion

                    #region 一层叠盘分拣条码的处理6
                    if (dv[i]["F_Askkind"].ToString() == "6")//拆盘机申请进盘
                    {

                        int[] state;
                        int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        state = CStaticClass.GetDeviceState(dcode);//条码所在输送机
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1))//空闲时，采集数据
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndexOut(dcode)) != 1)
                        {
                            //20091128
                            state = null;
                            continue;
                        }

                        string barcode = CStaticClass.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        //barcode = "370070000001001";
                        if ((barcode == null) || (barcode == "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")) continue;
                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);

                        dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='" + barcode + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");

                        #region 任务号丢失的处理

                        if ((state[1] == 2) && (state[2] == 0))//完成且任务号为0，且为管理系统下达的任务
                        {
                            //未扫到条码：生成到12100的任务
                            if (barcode == "111111111111111")
                            {
                                sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                //发送指令
                                sdo.SendDeviceOrder(1, 0, 6, dcode, Convert.ToInt32(dv[i]["F_Remark"]));//任务号为0
                                //生成任务...........

                                wv[0].Remove(0, wv[0].Length);
                                wv[0].Append("2");
                                sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "任务号丢失且未扫到条码则输送至12100", dv[i]["F_DeviceIndex"].ToString(), barcode);

                                continue;

                            }
                            //扫到条码：判断是出库任务还是入库任务()

                            //首先在管理系统下达的任务中查找,设备指令的终点设备(到12043任务丢失)或是起点设备（到叠盘机任务丢失）是该设备
                            string Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex) And F_Status>=1 And F_DeviceCommandIndex=6  And T_Manage_Task.F_ManageTaskKindIndex=1 And (F_NumParam4 ={0} Or F_NumParam1 ={1})And F_TxtParam like '%{2}%'", dcode, dcode, barcode);
                            //20091128
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {//20091128
                                //出库任务在输送置12043途中任务丢失,则直接完成该任务...........
                                if (Convert.ToInt32(dvs[0]["F_NumParam4"]) == dcode)
                                {
                                    cgs.ActionComplete(dcode, Convert.ToInt32(dvs[0]["F_MonitorIndex"]), 1);
                                    CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "根据条码完成任务", dvs[0]["F_MonitorIndex"].ToString(), barcode);

                                }
                                //出库任务在输送至配送叠盘机途中任务丢失,则重发改指令.............
                                if (Convert.ToInt32(dvs[0]["F_NumParam1"]) == dcode)
                                {
                                    sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                    //发送指令
                                    sdo.SendDeviceOrder(2, 0, 0, dcode, 0);
                                    dbo.ExceSQL("update T_Monitor_Task set F_SendCount=0,F_Status=0 where F_MonitorIndex=" + Convert.ToInt32(dvs[0]["F_MonitorIndex"]));
                                    CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "根据条码重发任务", dvs[0]["F_MonitorIndex"].ToString(), barcode);

                                }



                            }
                            else//不存在与该条码对应的设备指令或是入库任务，则生成至异常口任务
                            {
                                //生成任务...........
                                sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                //发送指令
                                sdo.SendDeviceOrder(1, 0, 6, dcode, Convert.ToInt32(dv[i]["F_Remark"]));

                                _listenPLCAskError = "输送机：" + dcode.ToString() + "条码扫描器上报的表箱码为：" + barcode + ",不存在对应的出库任务,则输送至12100！";
                                CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "不存在对应的出库任务", "则输送至12100", barcode);

                            }

                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                        }
                        #endregion

                    }
                    #endregion

                    #region 一层入库口12100条码的处理7
                    //20100406
                    if (dv[i]["F_Askkind"].ToString() == "7")//生成双叉入库任务条码申请
                    {

                        int[] state;
                        int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        int sortingdev = Convert.ToInt32(dv[i]["F_TaskIndex"]);
                        state = CStaticClass.GetDeviceState(dcode);//条码所在输送机
                        if (state == null)
                        {
                            continue;
                        }
                        //如果任务号丢失，则只有在任务号为0的情况下处理
                        if (!((state[1] == 2) && (state[2] == 0)))//完成且任务号为0时才进行处理
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndexOut(dcode)) != 1)
                        {
                            //20091128
                            state = null;
                            continue;
                        }

                        string barcode = CStaticClass.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        //barcode = "370070000001462";
                        if ((barcode == null) || (barcode == "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")) continue;
                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);

                        dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='" + barcode + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");

                        //int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);

                        if (barcode != "111111111111111")//扫描到条码的处理
                        {
                            //查找是否有222的任务，该任务为自动出库任务，不需要申请条码

                            #region 判断是否存在起点或是终点为12100的任务

                            //判断是否是已经存在的任务，起点为该设备的任务重新发送，终点为该设备的任务完成
                            //string Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task"+
                            //"where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex) And F_Status>=1 And F_DeviceCommandIndex=6 And T_Manage_Task.F_ManageTaskKindIndex=1 And (FCONTROLTASKTYPEF=2 Or _NumParam1 ={0})And F_TxtParam like '%{1}%'", dcode, barcode);
                            string Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task " +
                            "where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex) And F_Status>=1 And F_DeviceCommandIndex=6 And (F_NumParam4 ={0} Or F_NumParam1 ={1})And F_TxtParam like '%{2}%'", dcode, dcode, barcode);

                            //20091128
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {
                                //不管任务号是否丢失
                                //任务在输送置12100途中任务丢失,则直接完成该任务...........
                                if (Convert.ToInt32(dvs[0]["F_NumParam4"]) == dcode)
                                {
                                    cgs.ActionComplete(dcode, Convert.ToInt32(dvs[0]["F_MonitorIndex"]), 1);
                                    CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "根据条码完成任务", dvs[0]["F_MonitorIndex"].ToString(), barcode);

                                }
                                //入库任务在输送至配送叠盘机途中任务丢失,则重发改指令.............
                                if (Convert.ToInt32(dvs[0]["F_NumParam1"]) == dcode)
                                {
                                    sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                    //发送指令
                                    sdo.SendDeviceOrder(2, 0, 0, dcode, 0);
                                    dbo.ExceSQL("update T_Monitor_Task set F_SendCount=0,F_Status=0 where F_MonitorIndex=" + Convert.ToInt32(dvs[0]["F_MonitorIndex"]));
                                    CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "根据条码重发任务", dvs[0]["F_MonitorIndex"].ToString(), barcode);

                                }

                                //wv[0] = "2";
                                //sdo.WriteDBData(witemnames, wv);
                                continue;
                            }
                            #endregion
                            #region 判断是否存在起点或是终点为12043的任务

                            //判断是否有起点或是终点为12043的任务。。。。。。。
                            Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task " +
                            "where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex) And F_Status>=1 And F_DeviceCommandIndex=6 And (F_NumParam4 ={0} Or F_NumParam1 ={1})And F_TxtParam like '%{2}%'", sortingdev, sortingdev, barcode);

                            //20091128
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {
                                //不管任务号是否丢失
                                //如果终点是12043则更改原指令的发送设备指令，重新发送该指令
                                if (Convert.ToInt32(dvs[0]["F_NumParam4"]) == sortingdev)
                                {
                                    string checkstring = string.Empty;
                                    checkstring = ccf.GetBeDetectedDevices(dcode);
                                    int routeIDsub = ccf.GetRouteIDsub(dcode);
                                    dbo.ExceSQL("update T_Monitor_Task set F_RouteID= " + routeIDsub + ",F_SendCount=0,F_Status=0,F_DeviceIndex=" + dcode + ",F_AheadDetect='" + checkstring + "' where F_MonitorIndex=" + Convert.ToInt32(dvs[0]["F_MonitorIndex"]));
                                    CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "根据条码更改起始设备为12100重发任务", dvs[0]["F_MonitorIndex"].ToString(), barcode);

                                }
                                //如果起点为12043则生成至12043的任务
                                if (Convert.ToInt32(dvs[0]["F_NumParam1"]) == sortingdev)
                                {
                                    sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                    //发送指令
                                    sdo.SendDeviceOrder(2, 0, 0, dcode, 0);
                                    sdo.SendDeviceOrder(1, 0, 6, dcode, sortingdev);//任务号为0
                                    CommonClassLib.CCarryConvert.WriteDarkCasket(dv[i]["F_DeviceIndex"].ToString(), "根据条码下达至12043的任务", barcode, "");

                                }

                                //wv[0] = "2";
                                //sdo.WriteDBData(witemnames, wv);
                                continue;
                            }
                            #endregion

                        }
                        else//未扫到条码的处理
                        {
                            if (state[1] == 2)//如果任务号丢失，则给应答
                            {
                                sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                //发送指令
                                sdo.SendDeviceOrder(2, 0, 0, dcode, 0);
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "任务号丢失且未扫到条码", dv[i]["F_DeviceIndex"].ToString(), barcode);

                            }

                        }



                    }
                    #endregion

                    #region 获取一号工程码信息F_Askkind=8
                    if (dv[i]["F_Askkind"].ToString() == "8")
                    {
                        ////20091128
                        //dvp = dbo.ExceSQL("SELECT F_DeviceIndex, F_FirstProject,F_BoxBarcode,F_HaveFirstProject, F_Askkind, F_BindingDevice FROM T_Base_PLC_Ask WHERE (F_Askkind = 8) AND (F_BindingDevice = " + dv[i]["F_BindingDevice"] + ")").Tables[0].DefaultView;
                        //if (dvp.Count > 0)
                        //{
                        //    //gds = CommModeCreate.CreateGetDeviceState(Convert.ToInt32(dvp[0]["F_DeviceIndex"]));
                        //    //string bcp = gds.GetStringData(Convert.ToInt32(dvp[0]["F_DeviceIndex"]), 64775);
                        //    string bcp = CStaticClass.GetStringData(Convert.ToInt32(dvp[0]["F_DeviceIndex"]));
                        //    if (bcp == null)
                        //    {
                        //        continue;
                        //    }
                        //    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", deviceindex.ToString(), bcp);
                        //    string bar1 = "", bar2 = "";
                        //    string ExceptionCode = "0";

                        //    bar1 = bcp.Substring(0, 16);
                        //    bar2 = bcp.Substring(16, 16);

                        //    if ((bar1 == "0000000000000000") || (bar1 == "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"))
                        //    {

                        //        if (dvp[0]["F_HaveFirstProject"].ToString() == "1")
                        //        {
                        //            ExceptionCode = "800";
                        //        }
                        //        else
                        //        {
                        //            ExceptionCode = "0";
                        //        }
                        //        bcp = "";
                        //    }
                        //    else
                        //    {
                        //        if (dvp[0]["F_HaveFirstProject"].ToString() == "1")
                        //        {
                        //            ExceptionCode = "0";

                        //        }
                        //        else
                        //        {
                        //            ExceptionCode = "800";
                        //        }
                        //        bcp = bar1;
                        //    }
                        //    if ((bar2 != "0000000000000000") && (bar2 != "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"))
                        //    {
                        //        if (dvp[0]["F_HaveFirstProject"].ToString() != "1")
                        //        {
                        //            ExceptionCode = "800";
                        //        }
                        //        else
                        //        {
                        //            ExceptionCode = "0";
                        //        }
                        //        bcp = bcp + ";" + bar2;
                        //    }
                        //    if (bcp.Length >= 1)
                        //    {
                        //        if (bcp.Substring(0, 1) == ";")
                        //        {
                        //            if (bcp.Length > 1)
                        //            {
                        //                bcp = bcp.Substring(1);
                        //            }
                        //            else
                        //            {
                        //                bcp = "";
                        //            }
                        //        }
                        //    }
                        //    if (ExceptionCode == "800")
                        //    {
                        //        //判断是否为无码烟，是无码烟不报告异常码，否则报告异常码

                        //        dbo.ExceSQL("UPDATE T_Base_PLC_Ask SET F_Remark='" + ExceptionCode + "' WHERE (F_Askkind = 8) AND (F_BindingDevice = " + dvp[0]["F_BindingDevice"] + ")");
                        //    }
                        //    //把一号工程码暂存在临时字段
                        //    dbo.ExceSQL("UPDATE T_Base_PLC_Ask SET F_TempFirstProject = '" + bcp + "' WHERE (F_Askkind = 8) AND (F_BindingDevice = " + dvp[0]["F_BindingDevice"] + ")");
                        //    if (CStaticClass.TestTemp == true)
                        //    {
                        //        //临时增加没用
                        //        dbo.ExceSQL("UPDATE T_Base_PLC_Ask SET F_FirstProject =F_FirstProject+';'+ F_TempFirstProject  WHERE (F_Askkind = 8) AND (F_BindingDevice = " + dv[i]["F_BindingDevice"] + ")");
                        //        dbo.ExceSQL("UPDATE T_Base_PLC_Ask SET F_TempFirstProject='' WHERE (F_Askkind = 8) AND (F_BindingDevice = " + dv[i]["F_BindingDevice"] + ")");
                        //    }
                        //    wv[0] = "2";
                        //    sdo.WriteDBData(witemnames, wv);
                        //}

                    }
                    #endregion

                    #region 一层配送出库分拣条码扫描3

                    if (dv[i]["F_Askkind"].ToString() == "3")// 一层配送出库分拣条码
                    {
                        int[] state;
                        int dcode = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                        continue;
                        state = CStaticClass.GetDeviceState(dcode);//条码所在输送机
                        if (state == null)
                        {
                            continue;
                        }
                        if ((state[1] >= 30) || (state[1] == 1))//空闲时，采集数据
                        {
                            //20091128
                            state = null;
                            continue;

                        }
                        if (CStaticClass.GetDevicePhotoelectric(ccf.GetBindingDeviceIndexOut(dcode)) != 1)
                        {
                            //20091128
                            state = null;
                            continue;
                        }

                        string barcode = CStaticClass.GetStringData(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                        //barcode = "370070000001001";
                        if ((barcode == null) || (barcode == "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")) continue;
                        //   CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);


                        //int bcz = 0;
                        //for (int j = 0; j < 15; j++)
                        //{
                        //    if (barcode.Substring(j, 1) != "0")
                        //    {
                        //        bcz = 1;
                        //        break;
                        //    }
                        //}
                        //if (bcz == 0)
                        //{//20091128
                        //    wv[0] = "2";
                        //    sdo.WriteDBData(witemnames, wv);
                        //    continue;
                        //}
                        #region 任务号丢失的处理

                        if ((state[1] == 2) && (state[2] == 0))//完成且任务号为0，且为管理系统下达的任务
                        {
                            //未扫到条码：生成到12100的任务
                            if (barcode == "111111111111111")
                            {

                                continue;

                            }
                            //扫到条码：判断是出库任务还是入库任务()

                            //首先在管理系统下达的任务中查找,设备指令的终点设备(到12043任务丢失)或是起点设备（到叠盘机任务丢失）是该设备
                            string Sql = string.Format("SELECT T_Manage_Task.F_ManageTaskKindIndex,FCONTROLTASKTYPE,F_ManageTaskIndex,F_MonitorIndex,F_NumParam1,F_NumParam4 from T_Manage_Task,T_Monitor_Task where (T_Manage_Task.FID = T_Monitor_Task.F_ManageTaskIndex And T_Manage_Task.F_ManageTaskKindIndex=T_Monitor_Task.F_ManageTaskKindIndex) And F_Status>=1 And F_DeviceCommandIndex=6  And T_Manage_Task.F_ManageTaskKindIndex＝1 And (F_NumParam4 ={0})And F_TxtParam like '%{1}%'", dcode, barcode);
                            //20091128
                            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                            if (dvs.Count > 0)
                            {//20091128
                                //出库任务在输送置12043途中任务丢失,则直接完成该任务...........
                                if (Convert.ToInt32(dvs[0]["F_NumParam4"]) == dcode)
                                {
                                    cgs.ActionComplete(dcode, Convert.ToInt32(dvs[0]["F_MonitorIndex"]), 1);
                                }


                            }
                            else//不存在与该条码对应的设备指令或是入库任务，则生成至异常口任务
                            {
                                ////生成任务...........
                                //sdo = CommModeCreate.CreateSendDeviceOrder(dcode);
                                ////发送指令
                                //sdo.SendDeviceOrder(1, 111, 6, dcode, Convert.ToInt32(dv[i]["F_Remark"]));

                                //_listenPLCAskError = "输送机：" + dcode.ToString() + "条码扫描器上报的表箱码为：" + barcode + ",不存在对应的出库任务！";

                            }
                            // 自动12307-12310


                            wv[0].Remove(0, wv[0].Length);
                            wv[0].Append("2");
                            sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);
                        }
                        DataView dvss = dbo.ExceSQL("select * from T_Manage_Task where FPALLETBARCODE   like '%" + barcode + "%' and FENDDEVICE =12307 ").Tables[0].DefaultView;
                        if (dvss.Count > 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_TYPE,BOX_QUANTITY,FStartCol,FStartLayer) " +
                            //"values(" + AutoManageIdx + ",'" + barcode + "','" + 4 + "',2,'" + ccf.GetWarehouseIndex() + "','" + 12307 + "','-','" + ccf.GetWarehouseIndex() + "','"
                            //+ 12310 + "','-'," + (-1) + "," + (-1) + ",'-','" + dtime + "',0,0,0,0)";//20101028
                            //                            dbo.ExceSQL(tempsql);
                            //                            wv[0] = "2";
                            //                            sdo.WriteDBData(witemnames, wv);

                        }
                        //


                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", dv[i]["F_DeviceIndex"].ToString(), barcode);



                        dbo.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='" + barcode + "' ,F_Remark ='" + DateTime.Now.ToString("u").Substring(0, DateTime.Now.ToString("u").Length - 1) + "' where (F_DeviceIndex=" + Convert.ToInt32(dv[i]["F_DeviceIndex"]) + ")");
                        #endregion
                    }
                    #endregion

                    //20101220


                }

            }
            catch (Exception ex)
            {
                _listenPLCAskError = "监听PLC请求时：" + ex.Message;
            }
            finally
            {
                bc=null;
                sql = null;
                wv =null;
                witemnames =null;
                dv=null;
                dvbc=null;
                dvm=null;
                //dvw=null;dv11=null;
                dv0=null;dplc=null;dvma=null;
                //dvp=null; 
                dvs=null;
            }
        }


        void RestoreDevice(int mindex)
        {
            int DeviceIdx, devKind;
            DataView dv = dbo.ExceSQL("select F_MonitorIndex,F_DeviceIndex from T_Monitor_Task where F_MonitorIndex=" + mindex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                //检查关联命令一起复位
                //如果mindex是主动任务（f_associatemonitor有数据），先复位被动的任务；如果mindex是被动任务，先复位自己，再复位主动任务；
                DataView dv1 = dbo.ExceSQL("select F_DeviceIndex,F_Associate from T_Monitor_Task where F_Associate IS NOT NULL and F_MonitorIndex=" + mindex).Tables[0].DefaultView;
                if (dv1.Count > 0)
                {
                    DataView dv2 = dbo.ExceSQL("select F_DeviceIndex,F_MonitorIndex from T_Monitor_Task where F_MonitorIndex=" + Convert.ToInt32(dv1[0]["F_Associate"])).Tables[0].DefaultView;
                    if (dv2.Count > 0)//有关联命令，先复位关联命令
                    {

                        DeviceIdx = Convert.ToInt32(dv2[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        if ((devKind == 2) || (devKind == 4))
                        {//输送机清零
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                        }
                        if ((devKind == 1)) //堆垛机、RGV
                        {

                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                        }
                        dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + Convert.ToInt32(dv2[0]["F_DeviceIndex"]));
                        dbo.ExceSQL("update T_Monitor_Task set F_Status=0 where F_MonitorIndex=" + Convert.ToInt32(dv2[0]["F_MonitorIndex"]));
                    }
                    //20091128
                    dv2 = null;
                    //再复位自己
                    DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                    devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                    if ((devKind == 2) || (devKind == 4))
                    {//输送机、RGV清零
                        sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                        sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                    }
                    if ((devKind == 1)) //堆垛机
                    {

                        sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                        sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                    }
                    dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                    dbo.ExceSQL("update T_Monitor_Task set F_Status=0 where F_MonitorIndex=" + Convert.ToInt32(dv[0]["F_MonitorIndex"]));

                }
                else
                {
                    //自己是否被关联,先复位自己，再复位主任务
                    DataView dv3 = dbo.ExceSQL("select F_DeviceIndex,F_MonitorIndex from T_Monitor_Task where F_Associate ='" + mindex + "'").Tables[0].DefaultView;
                    if (dv3.Count > 0)
                    {   //先复位自己
                        DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        if ((devKind == 2) || (devKind == 4))
                        {//输送机、RGV清零
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                        }
                        if ((devKind == 1)) //堆垛机
                        {

                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                        }
                        dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                        dbo.ExceSQL("update T_Monitor_Task set F_Status=0 where F_MonitorIndex=" + mindex);
                        //再复位主任务
                        DeviceIdx = Convert.ToInt32(dv3[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        if ((devKind == 2) || (devKind == 4))
                        {//输送机、RGV清零
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                        }
                        if ((devKind == 1)) //堆垛机
                        {

                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                        }
                        dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + Convert.ToInt32(dv3[0]["F_DeviceIndex"]));
                        dbo.ExceSQL("update T_Monitor_Task set F_Status=0 where F_MonitorIndex=" + Convert.ToInt32(dv3[0]["F_MonitorIndex"]));
                    }
                    else
                    {
                        //无关联任务，只复位自己
                        DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        if ((devKind == 2) || (devKind == 4))
                        {//输送机、RGV清零
                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0);
                        }
                        if ((devKind == 1)) //堆垛机
                        {

                            sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                            sdo.SendDeviceOrder(2, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                        }
                        dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                        dbo.ExceSQL("update T_Monitor_Task set F_Status=0 where F_MonitorIndex=" + mindex);
                    }
                    //20091128
                    dv3 = null;
                }
                //20091128
                dv1 = null;
            }
            //20091128
            dv = null;
        }
        void AssociateComplete(int deviceIdx, int mindex)
        {
            int DeviceIdx = deviceIdx;
            int devKind;
            DataView dv = dbo.ExceSQL("select F_MonitorIndex,F_DeviceIndex from T_Monitor_Task where F_MonitorIndex=" + mindex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                //检查关联命令一起复位
                //如果mindex是主动任务（f_associatemonitor有数据），先复位被动的任务；如果mindex是被动任务，先复位自己，再复位主动任务；
                DataView dv1 = dbo.ExceSQL("select F_DeviceIndex,F_Associate from T_Monitor_Task where F_Associate IS NOT NULL and F_MonitorIndex=" + mindex).Tables[0].DefaultView;
                if (dv1.Count > 0)
                {
                    DataView dv2 = dbo.ExceSQL("select F_DeviceIndex,F_MonitorIndex from T_Monitor_Task where F_MonitorIndex=" + Convert.ToInt32(dv1[0]["F_Associate"])).Tables[0].DefaultView;
                    if (dv2.Count > 0)//有关联命令，先复位关联命令
                    {

                        DeviceIdx = Convert.ToInt32(dv2[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        cgs.ActionComplete(DeviceIdx,Convert.ToInt32( dv2[0]["F_MonitorIndex"]),1);
                    }
                    //20091128
                    dv2 = null;
                    //再复位自己
                    DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                    devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                    cgs.ActionComplete(DeviceIdx,mindex,1);
                }
                else
                {
                    //自己是否被关联,先复位自己，再复位主任务
                    DataView dv3 = dbo.ExceSQL("select F_DeviceIndex,F_MonitorIndex from T_Monitor_Task where F_Associate ='" + mindex + "'").Tables[0].DefaultView;
                    if (dv3.Count > 0)
                    {   //先复位自己
                        DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        cgs.ActionComplete(DeviceIdx,mindex,1);
                        //再复位主任务
                        DeviceIdx = Convert.ToInt32(dv3[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        cgs.ActionComplete(DeviceIdx,Convert.ToInt32( dv3[0]["F_MonitorIndex"]),1);
                    }
                    else
                    {
                        //无关联任务，只复位自己
                        DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        cgs.ActionComplete(DeviceIdx, mindex,1);
                    }
                    //20091128
                    dv3 = null;
                }
                //20091128
                dv1 = null;
            }
            //20091128
            dv = null;
        }
        /// <summary>
        /// 获取可用的目标位置：入库的巷道或者出库站台
        /// </summary>
        /// <param name="manageTaskIdx">调度任务索引</param>
        /// <param name="manageKindIdx">调度任务类别</param>
        /// <returns></returns>
        bool GetUsableDestination(int manageTaskIdx, int manageKindIdx)
        {
            //20091128
            //DataView DV;
            DataView dv;
            DataRowView dr;
            string sql = "";
            string adviceDev = "";
            char[] cc = new char[1] { ';' };
            string[] sp;
            DataView dvIO;


            try
            {
                dv = dbo.ExceSQL("SELECT * FROM T_Manage_Task WHERE (FID = " + manageTaskIdx + ") AND (F_ManageTaskKindIndex = " + manageKindIdx + ")").Tables[0].DefaultView;
                if (dv.Count <= 0)
                {
                    return false;
                }
                dr = dv[0];
                //只修申请改调度任务的路径，不修改调度自动任务路径
                if (dr["F_ManageTaskKindIndex"].ToString() != "1") return false;
                //20091128
                dvIO = dboM.ExceSQL("select CONTROL_ID, CONTROL_STATUS from IO_Control where (CONTROL_ID = " + Convert.ToInt32(dr["FID"]) + ") AND ((CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEAPPLY + ") or (CONTROL_STATUS=" + Model.CGeneralFunction.TASKCANCEL + ") or(CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEREPLY + "))").Tables[0].DefaultView;
                if (dvIO.Count <= 0)
                {

                    #region 根据T_Base_Device表的F_UsableEndDevice查找可用终点设备
                    DataView dvu = dbo.ExceSQL("select F_UsableEndDevice from T_Base_Device where F_UsableEndDevice is not null and F_DeviceIndex=" + dr["FCurrentLocation"] + "").Tables[0].DefaultView;
                    if (dvu.Count > 0)
                    {
                        sp = dvu[0]["F_UsableEndDevice"].ToString().Split(cc);
                        for (int i = sp.GetLowerBound(0); i <= sp.GetUpperBound(0); i++)
                        {
                            if (CDisassembleTask.MinRouteID(Convert.ToInt32(dr["FSTARTDEVICE"]), Convert.ToInt32(sp[i])) != -1)
                            {
                                adviceDev = sp[i];
                                break;
                            }
                        }
                    }
                    //20091128
                    dvu = null;
                    if (adviceDev == "")
                    {
                        return false;
                    }
                    #endregion

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

                    dboM.TransBegin();
                    try
                    {
                        #region 入库任务运到出库站台需要上报IO_CONTROL表FSTATUS=960
                        //3241;3249;3256;3257;3258
                        string[] outstation = new string[5] { "3241", "3249", "3256", "3257", "3258" };
                        if (ccf.GetFCONTROLTASKTYPEFromManageTask(manageKindIdx, manageTaskIdx) == 1)//入库任务
                        {
                            if (Array.IndexOf(outstation, dr["FCurrentLocation"].ToString()) >= 0)
                            {
                                dboM.ExceSQL("update IO_Control set CONTROL_STATUS=" + Model.CGeneralFunction.TASKCANCEL + ",ERROR_TEXT='入库任务被误搬运到出库站台！' where CONTROL_ID=" + manageTaskIdx);

                            }
                        }
                        //20091128
                        outstation = null;
                        #endregion

                        //20090918
                        dboM.ExceSQL(" update IO_CONTROL set CONTROL_STATUS=" + Model.CGeneralFunction.TASKALTERROUTEAPPLY + " where CONTROL_ID=" + dr["FID"] + " and CONTROL_STATUS<>" + Model.CGeneralFunction.TASKCANCEL + "");
                        //向管理申请修改任务//20101108CONTROL_APPLY_ID," + fid + ",
                        sql = "INSERT INTO IO_CONTROL_APPLY ( CONTROL_ID, WAREHOUSE_CODE, STOCK_BARCODE, DEVICE_CODE, APPLY_TASK_STATUS, CREATE_TIME,CONTROL_APPLY_REMARK)" +
                        "VALUES (" + dr["FID"] + ",'" + dr["FENDWAREHOUSE"] + "','" + dr["FPALLETBARCODE"] + "','" + adviceDev + "',0,'" + dtime + "',null)";
                        dboM.ExceSQL(sql);
                        dboM.TransCommit();
                        //把ManageTaskIdx，ManageKindIdx 的调度任务全部申请改道
                        dbo.ExceSQL("UPDATE T_Monitor_Task SET  F_Status = 3 WHERE (F_ManageTaskIndex = " + manageTaskIdx + ") AND (F_ManageTASKKINDINDEX =" + manageKindIdx + ")");
                        //20090910

                        return true;
                    }
                    catch (Exception ex)
                    {
                        dboM.TransRollback();
                        _listenPLCAskError = "监听PLC请求改道时：" + ex.Message;
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                _listenPLCAskError = "监听PLC请求改道时：" + ex.Message;
                return false;
            }
            finally
            {
                //DV=null;
                dv=null;
                dr=null;
                cc =null;
                sp=null;
                dvIO=null;
            }
        }
        /// <summary>
        /// 20091005判断是否可以获得可用的路径子路经
        /// </summary>
        /// <param name="manageTaskIdx">调度任务索引</param>
        /// <param name="manageKindIdx">任务类型索引</param>
        /// <param name="curLocation">当前设备索引</param>
        /// <returns></returns>
        bool GetUseableRouteIDSub(int manageTaskIdx, int manageKindIdx,int curLocation)
        {
            DataView dvmi;
            DataView DMAN;
            DataView dvnew;
            try
            {
                string sql;
                //20091005
                
                #region 调度任务存在
                //20091128
                dvmi = dbo.ExceSQL("SELECT * FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + manageTaskIdx + ") AND (F_ManageTASKKINDINDEX =1) 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();

                    //20091128
                    DMAN = dbo.ExceSQL("select * from T_Manage_Task WHERE (FID = " + manageTaskIdx + ") AND (F_ManageTASKKINDINDEX =1)").Tables[0].DefaultView;
                    if (DMAN.Count > 0)
                    {


                        //20091005
                        int routeidNew = CDisassembleTask.MinRouteID(Convert.ToInt32(DMAN[0]["FSTARTDEVICE"]), Convert.ToInt32(DMAN[0]["FENDDEVICE"]),curLocation);

                        if (routeidNew == -1)
                        {
                            //20091005
                            return false;
                        }
                        //20091005
                        //删除原来的申请修改路径任务，拆分新的任务并且只保留现有设备开始的任务
                        dbo.ExceSQL("DELETE FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + manageTaskIdx + ") AND (F_ManageTASKKINDINDEX =1)");
                        //20090910
                        if (CDisassembleTask.CreateMonitor(1, manageTaskIdx, 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 (" + manageTaskIdx + ",1," + monitorIndex + ",1," + devindex + "," + devCommand + "," + routeID + ",3," + NumParam1 + "," + NumParam4
                                        + ",'" + AheadDetect + "','" + DMAN[0]["FPALLETBARCODE"] + "')";
                            dbo.ExceSQL(sql);
                            return false;
                        }

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

                                #region RGV运动到接货点
                                if (RGVsn > Consn)
                                {
                                    //删除RGV运动到接货点之前的任务
                                    //20091128
                                    dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                        manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                        devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                        ")  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 = " +
                                        manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) ");
                                        dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) ");
                                    }

                                }
                                #endregion

                                #region RGV运动到送货点
                                if (RGVsn < Consn)
                                {
                                    //删除RGV运动到送货点之前的任务
                                    //DataView dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    //    manageTaskIdx + ") 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;
                                    int RGVsn1 = ccf.GetSerialNumberFromRouteDevice(routeidNew, devindex);
                                    //找到接货输送机设备索引
                                    List<int> nextcon = CDisassembleTask.GetNextDevice(routeidNew, RGVsn1);
                                    int condev = nextcon[0];
                                    //删除RGV运动到送货点之前的任务
                                    //20091128
                                    dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                        manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                        devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                        ")  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 = " +
                                        manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                        dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                    }
                                }
                                #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运动到送货点之前的任务
                                //20091128
                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                    devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                    ")  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 = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) ");
                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                }

                            }
                            #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运动到接货点之前的任务
                                //20091128
                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                    devindex + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                    ")  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 = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                }

                            }
                            #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运动到接货点之前的任务
                                //20091128
                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                    rgvdev + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                    ")  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 = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                }

                            }
                            #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运动到送货点之前的任务
                                //20091128
                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                    rgvdev + ") AND (F_DeviceCommandIndex = 7) AND (F_RouteID = " + routeidNew +
                                    ") 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 = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                }

                            }

                            #endregion


                            #region 输送机的送出
                            if (devCommand == 6)
                            {
                                //20091128
                                dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                    devindex + ") AND (F_DeviceCommandIndex = 6) AND (F_RouteID = " + routeidNew +
                                    ")").Tables[0].DefaultView;
                                if (dvnew.Count > 0)
                                {
                                    dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) ");
                                    int CurrentLocation = 0;
                                    DataView dvc = dbo.ExceSQL("SELECT FCurrentLocation FROM T_Manage_Task where FID=" + manageTaskIdx + " and F_ManageTaskKindIndex=1").Tables[0].DefaultView;
                                    if (dvc.Count > 0)
                                    {
                                        CurrentLocation = Convert.ToInt32(dvc[0]["FCurrentLocation"]);
                                    }
                                    //20091128
                                    dvc = null;
                                    if (CurrentLocation == 0) return false;
                                    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 + "");


                                    dbo.ExceSQL("update  T_Monitor_Task set F_Status =0 where  (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");


                                }
                            }
                            #endregion

                        }
                        #region 堆垛机的送货重
                        if (devKind == 1)
                        {//堆垛机的送货重，只保留堆垛机的送货任务

                            //20091128
                            dvnew = dbo.ExceSQL("SELECT F_MonitorIndex FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) AND (F_DeviceIndex = " +
                                    devindex + ") AND (F_DeviceCommandIndex = 5) AND (F_RouteID = " + routeidNew +
                                    ")").Tables[0].DefaultView;
                            if (dvnew.Count > 0)
                            {
                                dbo.ExceSQL("delete from T_Monitor_Task where F_MonitorIndex<" + dvnew[0]["F_MonitorIndex"] + " and (F_ManageTaskIndex = " +
                                    manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1)");
                                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 = " +
                                manageTaskIdx + ") AND (F_ManageTASKKINDINDEX = 1) ");
                            }

                        }
                        #endregion

                    }//20090910

                    return true;
                }//20091005
                #endregion
                else
                {//调度任务不存在
                    return false;
                }
                
            }
            catch (Exception ex)
            {
                _listenPLCAskError = "CListenPLCAsk.GetUseableRouteIDSub:" + ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 判断设备是否被包含在子路径中
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <param name="routeSub">子路经</param>
        /// <returns></returns>
        bool DeviceInRouteSub(int deviceIdx,int routeSub)
        {
            DataView dv = dbo.ExceSQL("SELECT F_RouteIDSub, F_DeviceIndex FROM T_Base_Route_Device Where F_RouteIDSub=" + routeSub + " and F_DeviceIndex="+deviceIdx +"").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        void CreateTempTask(int tw, string FPALLETBARCODE)
        {
            DataView dvs;
            string Sql, _tasktype, _startposition = "0", _startsite = "-", _endposition = "0", _endsite = "-";
            _tasktype = "1";
            _startposition = tw.ToString();
            _startsite = "-";
            int flaneway = 0;
            int stackno = 0;
            int FISRETURN = 0;
            Sql = "SELECT FPALLETBARCODE from T_Manage_Task where FPALLETBARCODE='" + FPALLETBARCODE + "'";
            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
            if (dvs.Count > 0) return;

            //Sql = "SELECT FID,FCELLCODE FROM ST_CELL WHERE (FCELLSTATUS > '0') AND (FWAREHOUSE = '12') AND (FLaneWay = '2802')";
            //dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
            //if (dvs.Count >= 2)
            //{
            //    Sql = "SELECT FID,FCELLCODE FROM ST_CELL WHERE (FCELLSTATUS = '0') AND (FRUNSTATUS = '0') AND (FWAREHOUSE = '12') AND (FLaneWay = '2803')";
            //    dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
            //    if (dvs.Count > 0)
            //    {
            //        _endposition = "2803";
            //        _endsite = dvs[0]["FCELLCODE"].ToString();
            //        flaneway = 2803;
            //        stackno = 2103;
            //        FISRETURN = 2210;
            //    }
            //}
            //else
            //{
                Sql = "SELECT FID,FCELLCODE FROM ST_CELL WHERE (FCELLSTATUS = '0') AND (FRUNSTATUS = '0') AND (FWAREHOUSE = '12') AND (FLaneWay = '2801')";
                dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
                if (dvs.Count > 0)
                {
                    _endposition = "2801";
                    _endsite = dvs[0]["FCELLCODE"].ToString();
                    flaneway = 2801;
                    stackno = 2101;
                    FISRETURN = 2201;
                }

            //}


           
            int AutoManageIdx = ccf.GetTempManageIdx();
            //插入临时调度任务T_Manage_Task(监控下的调度任务)：
            //ccf.RecordMaxTempManageTaskFID(AutoManageIdx);
            Sql = "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTDEVICE,FSTARTCELL," +
            "FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FISRETURN) " +
            "values(" + AutoManageIdx + ",'" + FPALLETBARCODE + "','" + _tasktype + "',2,'" + _startposition + "','" + _startsite + "','"
            + _endposition + "','" + _endsite + "'," + flaneway + "," + stackno + "," + FISRETURN + ")";
          //  dbo.ExceSQL(Sql);
            ccf.SetRunStatus("12", flaneway, _endsite, "1");
        }
        void CreateTempTask(int tw, string FPALLETBARCODE, int flaneway, int stackno, int FISRETURN)
        {
            DataView dvs;
            string Sql, _tasktype, _startposition = "0", _startsite = "-", _endposition = "0", _endsite = "-";
            _tasktype = "1";
            _startposition = tw.ToString();
            _startsite = "-";
            Sql = "SELECT FPALLETBARCODE from T_Manage_Task where FPALLETBARCODE='"+ FPALLETBARCODE +"'";
            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView ;
            if (dvs.Count > 0) return;
            Sql = "SELECT FID,FCELLCODE FROM ST_CELL WHERE (FCELLSTATUS = '0') AND (FRUNSTATUS = '0') AND (FWAREHOUSE = '12') AND (FLaneWay = "+flaneway+")";
            dvs = dbo.ExceSQL(Sql).Tables[0].DefaultView;
            if (dvs.Count > 0)
            {
                _endposition = flaneway.ToString();
                _endsite = dvs[0]["FCELLCODE"].ToString();
                
            }
        



            int AutoManageIdx = ccf.GetTempManageIdx();
            //插入临时调度任务T_Manage_Task(监控下的调度任务)：
            //ccf.RecordMaxTempManageTaskFID(AutoManageIdx);
            Sql = "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTDEVICE,FSTARTCELL," +
            "FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FISRETURN) " +
            "values(" + AutoManageIdx + ",'" + FPALLETBARCODE + "','" + _tasktype + "',2,'" + _startposition + "','" + _startsite + "','"
            + _endposition + "','" + _endsite + "'," + flaneway + "," + stackno + "," + FISRETURN + ")";
            dbo.ExceSQL(Sql);
            ccf.SetRunStatus("12", flaneway, _endsite, "1");
        }

        /// <summary>
        /// 获取记录的条码
        /// </summary>
        /// <returns></returns>
        string  GetPLCAskRecordBarCode(int boxsum ,out string sResult)
        {
            string RecordedBarCode = string.Empty;
            sResult = string.Empty;
            DataView dv = dbo.ExceSQL("select * from T_Base_PLC_Ask where F_DeviceIndex =16062").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0]["F_BarCode"] != DBNull.Value)
                {
                    RecordedBarCode = dv[0]["F_BarCode"].ToString();
                }
            }
            if (RecordedBarCode != string.Empty)
            {
                RecordedBarCode = RecordedBarCode.TrimEnd('|');
            }
            string[] strtemp = RecordedBarCode.Split('|');
            if (strtemp.Length != boxsum)
            {
                sResult = "码垛完成上报完成纸箱数量为 " + boxsum + ";系统记录纸箱数量为 " + strtemp.Length+",两者数量不一致，请到码垛管理页面进行处理！";
            }
            return RecordedBarCode;
        }

        /// <summary>
        /// 记录送入码箱条码
        /// </summary>
        /// <param name="fid"></param>
        void RecordBarCodeForDiePan(string STOCK_BARCODE ,out string sRueslt)
        {

            StringBuilder sb = new StringBuilder();
            sRueslt  =string.Empty ;
            
            DataView dvAsk = dbo.ExceSQL("select * from  T_Base_PLC_Ask t where t.F_DeviceIndex =16062 ").Tables[0].DefaultView;
            if (dvAsk.Count > 0)
            {
                if (dvAsk[0]["F_BarCode"] != DBNull.Value || dvAsk[0]["F_BarCode"].ToString() != string.Empty)
                {
                    sb.Append(dvAsk[0]["F_BarCode"].ToString());
                }
            }
            if (sb.ToString().Contains(STOCK_BARCODE))
            {
                sRueslt = "本次码箱上报条码" + STOCK_BARCODE+"已存在托盘上";
                return;
            }
            sb.Append(STOCK_BARCODE).Append("|");
            dbo.ExceSQL("update T_Base_PLC_Ask set F_BarCode ='" + sb.ToString() + "' where F_DeviceIndex =16062");
        }

        /// <summary>
        /// 获取记录的条码
        /// </summary>
        /// <returns></returns>
        string GetPLCAskRecordBarCode(int BindingDevice)
        {
            string RecordedBarCode = string.Empty;
            DataView dv = dbo.ExceSQL("select * from T_Base_PLC_Ask where F_BindingDevice =" + BindingDevice).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0]["F_BarCode"] != DBNull.Value)
                {
                    RecordedBarCode = dv[0]["F_BarCode"].ToString();
                }
            }
            if (RecordedBarCode != string.Empty)
            {
                RecordedBarCode = RecordedBarCode.TrimEnd('|');
            }
            return RecordedBarCode;
        }
        
    }
}
