using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DBFactory;
using System.Net.Sockets;
using System.Threading;
using ICommLayer;
using CommLayerFactory;
using Microsoft.VisualBasic;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 设备指令队列管理
    /// </summary>
    public partial class FrmModifyMonitor : Form
    {
        string _monstatus = " F_Status<>-1 ";
        private static FrmModifyMonitor _formInstance;

        public static FrmModifyMonitor FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmModifyMonitor();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        CGetState gs = new CGetState();
        DBOperator dbo = CStaticClass.dbo;
        DBOperator dboM = CStaticClass.dboM;
        CCommonFunction ccf = new CCommonFunction();
        Model.MDevice devinfo;
        public FrmModifyMonitor()
        {
            InitializeComponent();
            _formInstance = this;
        }

        private void cmMonitor_Opening(object sender, CancelEventArgs e)
        {
            if (this.dgvMonitor.CurrentRow == null)
            {
                TSMonitor.Visible = false;
                TSMManager.Visible = false;
                TSMSimulateRun.Visible = false;
                TSMmonitorOK.Visible = false;
                TSMRestore.Visible = false;
                TSMmonitorDel.Visible = false;
                toolStripSeparator2.Visible = false;
                tsmAGV.Visible = false;
                tsmAGVGet.Visible = false;
                tsmAGVSend.Visible = false;
                tsmAGVBank.Visible = false;
                tsmAGVGoods.Visible = false;
                return;
            }
            if (Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[0].Value) > 0)
            {
                TSMonitor.Visible = true;
                TSMManager.Visible = true;
                //TSMSimulateRun.Visible = true;
                TSMmonitorOK.Visible = true;
                TSMmonitorDel.Visible = true;
                TSMRestore.Visible = true;
                toolStripSeparator2.Visible = true;

                TSMManager.Text = "任务类型：" + this.dgvMonitor.CurrentRow.Cells[1].Value.ToString() +
                    "；调度任务索引：" + this.dgvMonitor.CurrentRow.Cells[0].Value.ToString();
                TSMonitor.Text = "设备指令索引：" + this.dgvMonitor.CurrentRow.Cells[2].Value.ToString();
                //if (this.dgvMonitor.CurrentRow.Cells[3].Value.ToString() == "1001")
                //{
                //    TSMSimulateRun.Visible = false;
                //    TSMmonitorOK.Visible = false;

                //    TSMRestore.Visible = true;

                //    toolStripSeparator2.Visible = false;
                //    tsmAGV.Visible = true;
                //    tsmAGVGet.Visible = true;
                //    tsmAGVSend.Visible = true;
                //    if (this.dgvMonitor.CurrentRow.Cells[5].Value.ToString() == "2")//1219空托盘回收
                //    {
                //        tsmAGVGoods.Visible = false;
                //        tsmAGVBank.Visible = true;
                //        tsmAGVSend.Visible = false;
                //        return;
                //    }
                //    else
                //    {
                //        tsmAGVSend.Visible = true;
                //        tsmAGVBank.Visible = false;
                //    }
                //    if (this.dgvMonitor.CurrentRow.Cells[5].Value.ToString() == "3")//1220残托盘回收
                //    {
                //        tsmAGVBank.Visible = false;
                //        tsmAGVGoods.Visible = true;
                //        tsmAGVSend.Visible = false;
                //        return;
                //    }
                //    else
                //    {
                //        tsmAGVSend.Visible = true;
                //        tsmAGVGoods.Visible = false;
                //    }
                //}
                //else
                //{
                    tsmAGV.Visible = false;
                    tsmAGVGet.Visible = false;
                    tsmAGVSend.Visible = false;
                    tsmAGVBank.Visible = false;
                    tsmAGVGoods.Visible = false;
                //}
            }
        }

        private void TSMmonitorOK_Click(object sender, EventArgs e)
        {
            char[] cc = new char[1] { '：' };
            string[] split = TSMonitor.Text.Split(cc);
            if (split[1] == "") return;


            DataView dv = dbo.ExceSQL("SELECT * FROM T_Monitor_Task Where F_MonitorIndex=" +
                Convert.ToInt32(split[1])).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                //20100108中间指令被报告完成时给与提示和警告

                DataView dv0 = dbo.ExceSQL("SELECT MIN(F_MonitorIndex) AS mmi FROM dbo.T_Monitor_Task WHERE (F_ManageTaskIndex = " + dv[0]["F_ManageTaskIndex"] + ") AND (F_ManageTASKKINDINDEX = " + dv[0]["F_ManageTASKKINDINDEX"] + ")").Tables[0].DefaultView;
                if (dv0.Count > 0)
                {
                    if ((dv0[0]["mmi"] != DBNull.Value) && (dv0[0]["mmi"].ToString() != split[1]))
                    {
                        if (MessageBox.Show("表箱条码：" + dv[0]["F_TxtParam"].ToString() + "，设备名称:“" + this.dgvMonitor.CurrentRow.Cells["设备名称"].Value.ToString() + ";设备命令:" + this.dgvMonitor.CurrentRow.Cells["设备命令名称"].Value.ToString() + "”之前还有没执行完成的调度任务，提前【动作完成】会造成调度任务混乱，您确认要继续操作吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                        {
                            return;
                        }
                    }
                }
                dv0 = null;
                //20100108操作黑匣子增加托盘条码
                if (MessageBox.Show("您确认表箱条码：" + dv[0]["F_TxtParam"].ToString() + "，设备名称:“" + this.dgvMonitor.CurrentRow.Cells["设备名称"].Value.ToString() + ";设备命令:" + this.dgvMonitor.CurrentRow.Cells["设备命令名称"].Value.ToString() + "”已经操作完成了吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }
                if ((Convert.ToInt32(dv[0]["F_DeviceIndex"]) == 12043) && (Convert.ToInt32(dv[0]["F_NumParam4"]) ==18007||Convert.ToInt32(dv[0]["F_NumParam4"]) == 12049 || Convert.ToInt32(dv[0]["F_NumParam4"]) == 12054))//判断是否是AGV放货到机器人站台的任务
                {
                    int station = 12049;
                    if (MessageBox.Show("如果您确认条码为: " + dv[0]["F_TxtParam"].ToString() + " 的表箱组\r\n已经进入叠盘输送机12049,请点击按钮'是',\r\n进入叠盘输送机12054,请点击按钮'否'!", "叠盘任务手动完成时提示：", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                    {
                        station = 12054;
                    }
                    dbo.ExceSQL("update T_Monitor_Task set F_NumParam4= " + station + " where F_MonitorIndex= " + Convert.ToInt32(dv[0]["F_MonitorIndex"]));


                }
                string sss = "设备索引:" + dv[0]["F_DeviceIndex"].ToString() + ";设备指令索引:" + dv[0]["F_MonitorIndex"].ToString();
                //20100108操作黑匣子增加托盘条码
                CommonClassLib.CCarryConvert.WriteDarkCasket("设备指令管理", "手工报告完成", "表箱条码：" + dv[0]["F_TxtParam"].ToString(), sss);

                AssociateComplete(Convert.ToInt32(dv[0]["F_DeviceIndex"]), Convert.ToInt32(dv[0]["F_MonitorIndex"]), Convert.ToInt32(dv[0]["F_Status"]));

                this.dgvMonitor.DataSource = dbo.ExceSQL("select * from V_Monitor_Task where " + _monstatus + " order by 设备指令索引 asc ").Tables[0].DefaultView;
            }
        }

        private void TSMRestore_Click(object sender, EventArgs e)
        {

            char[] cc = new char[1] { '：' };
            string[] split = TSMonitor.Text.Split(cc);
            if (split[1] == "") return;


            ISendDeviceOrder sdo;
            int DeviceIdx;
            int devKind;
            int mindex = Convert.ToInt32(split[1]);
            int fid = ccf.GetManageTaskIndexfromMonitor(mindex);
            int mankind = ccf.GetManageTaskKindIndexFromMonitor(mindex);


            //20100108改为select * 
            DataView dv = dbo.ExceSQL("select * from T_Monitor_Task where F_MonitorIndex=" + mindex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                //20100108中间指令被复位时给与提示和警告
                DataView dv0 = dbo.ExceSQL("SELECT MIN(F_MonitorIndex) AS mmi FROM dbo.T_Monitor_Task WHERE (F_ManageTaskIndex = " + fid + ") AND (F_ManageTASKKINDINDEX = " + mankind + ")").Tables[0].DefaultView;
                if (dv0.Count > 0)
                {
                    if ((dv0[0]["mmi"] != DBNull.Value) && (dv0[0]["mmi"].ToString() != mindex.ToString()))
                    {
                        if (MessageBox.Show("表箱条码：" + dv[0]["F_TxtParam"].ToString() + "，设备名称:“" + this.dgvMonitor.CurrentRow.Cells["设备名称"].Value.ToString() + ";设备命令:" + this.dgvMonitor.CurrentRow.Cells["设备命令名称"].Value.ToString() + "”之前还有没执行完成的调度任务，提前【复位】会造成调度任务混乱，您确认要继续操作吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                        {
                            return;
                        }
                    }
                }
                dv0 = null;

                //20100108操作黑匣子增加托盘条码
                if (MessageBox.Show("您确认表箱条码：" + dv[0]["F_TxtParam"].ToString() + "，设备名称:“" + this.dgvMonitor.CurrentRow.Cells["设备名称"].Value.ToString() + ";设备命令:" + this.dgvMonitor.CurrentRow.Cells["设备命令名称"].Value.ToString() + "”需要被重新发送和设备清零吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }

                //20091107
                devKind = ccf.GetDeviceKindIdx(Convert.ToInt32(dv[0]["F_DeviceIndex"]));
                if ((devKind == 6) && (dv[0]["F_AgvNo"] != DBNull.Value))
                {
                    if (MessageBox.Show("您要复位的AGV任务已经分配AGV车号：" + dv[0]["F_AgvNo"].ToString() + "，确认要继续重新下达AGV命令吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                    {
                        return;
                    }
                }

                string sss = "设备索引:" + dv[0]["F_DeviceIndex"].ToString() + ";设备指令索引:" + dv[0]["F_MonitorIndex"].ToString();
                //20100108操作黑匣子增加托盘条码
                CommonClassLib.CCarryConvert.WriteDarkCasket("设备指令管理", "手工复位", "表箱条码:" + dv[0]["F_TxtParam"].ToString(), sss);
                //检查关联命令一起复位
                //如果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))
                        {//输送机、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(dv2[0]["F_DeviceIndex"]));
                        dbo.ExceSQL("update T_Monitor_Task set F_SendCount=0,F_Status=0 where F_MonitorIndex=" + Convert.ToInt32(dv2[0]["F_MonitorIndex"]));
                    }
                    //再复位自己
                    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);
                    }
                    //if ((devKind == 6)) //AGV
                    //{
                    //    int agvtask = ccf.GetAGVTask(mindex);
                    //    if (agvtask != -1)
                    //    {
                    //        sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                    //        sdo.SendDeviceOrder(1, agvtask, 65, 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_SendCount=0,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);
                        }
                        //if ((devKind == 6)) //AGV
                        //{
                        //    int agvtask = ccf.GetAGVTask(mindex);
                        //    if (agvtask != -1)
                        //    {
                        //        sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                        //        sdo.SendDeviceOrder(1, agvtask, 65, 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_SendCount=0,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_SendCount=0,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);
                        }
                        //if ((devKind == 6)) //AGV
                        //{
                        //    int agvtask = ccf.GetAGVTask(mindex);
                        //    if (agvtask != -1)
                        //    {
                        //        sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                        //        sdo.SendDeviceOrder(1, agvtask, 65, 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_SendCount=0,F_Status=0 where F_MonitorIndex=" + mindex);
                    }
                }
                //给管理FERRORCODE清空
                if (mankind == 1)
                {
                    dboM.ExceSQL("UPDATE IO_CONTROL  SET  ERROR_TEXT =''  WHERE CONTROL_ID=" + fid + "");
                }
                dbo.ExceSQL("UPDATE T_Manage_Task  SET  FERRORCODE =''  WHERE FID=" + fid + " and F_ManageTaskKindIndex=" + mankind + "");

            }



            this.dgvMonitor.DataSource = dbo.ExceSQL("select * from V_Monitor_Task where " + _monstatus + " order by 设备指令索引 asc ").Tables[0].DefaultView;
        }

        private void TSMSimulateRun_Click(object sender, EventArgs e)
        {
            char[] cc1 = new char[1] { '：' };
            string[] split = TSMonitor.Text.Split(cc1);
            if (split[1] == "") return;

            CCommonFunction ccf = new CCommonFunction();
            DataSet ds = dbo.ExceSQL("SELECT F_ManageTaskIndex, F_ManageTaskKindIndex," +
                " F_MonitorIndex, F_DeviceIndex,F_NumParam2,F_NumParam3 FROM T_Monitor_Task Where F_MonitorIndex=" +
                Convert.ToInt32(split[1]));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                ccf.SendOrderSuccess(Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]),
                Convert.ToInt32(dv[0]["F_ManageTaskIndex"]), Convert.ToInt32(dv[0]["F_MonitorIndex"]),
                Convert.ToInt32(dv[0]["F_DeviceIndex"]), 0);
                CGetState cg = new CGetState();
                cg._States = new int[14];
                cg._States[1] = 2;//报坐标
                cg._States[2] = Convert.ToInt32(dv[0]["F_MonitorIndex"]);//任务号
                cg._States[3] = Convert.ToInt32(dv[0]["F_NumParam2"]);//X坐标（水平）
                cg._States[4] = Convert.ToInt32(dv[0]["F_NumParam3"]);//Y坐标（垂直）
                cg._States[5] = Convert.ToInt32(dv[0]["F_DeviceIndex"]);//设备号
                cg.RefreshControlMonitor(Convert.ToInt32(dv[0]["F_DeviceIndex"]));

            }
        }

        private void rbmonAll_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked == true)
            {
                _monstatus = " F_Status<>-1 ";
            }
            TSMMonitorRefresh_Click(sender, e);
        }
        private void TSMMonitorRefresh_Click(object sender, EventArgs e)
        {
            CStaticClass.RealRefresh = true;
            this.dgvMonitor.DataSource = dbo.ExceSQL("select * from V_Monitor_Task where " + _monstatus + " order by 设备指令索引 asc ").Tables[0].DefaultView;
        }

        private void rbmonRun_CheckedChanged(object sender, EventArgs e)
        {

            if (rbmonRun.Checked == true)
            {
                _monstatus = " (F_Status>=1) ";
            }
            TSMMonitorRefresh_Click(sender, e);
        }

        private void rbmonWait_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked == true)
            {
                _monstatus = " F_Status=0 ";
            }
            TSMMonitorRefresh_Click(sender, e);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text.Trim().Length == 0) return;
            int index = 0;
            bool isint = int.TryParse(this.textBox1.Text.Trim(), out index);
            if (this.comboBox1.Text == "表箱条码")
            {
                _monstatus = " 表箱条码 like'%" + this.textBox1.Text.Trim() + "%' ";
            }
            if (this.comboBox1.Text == "设备指令索引")
            {
                if (isint == false)
                {
                    //MessageBox.Show("请输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    textBox1.Text = string.Empty;
                    return;
                }
                _monstatus = " 设备指令索引='" + this.textBox1.Text.Trim() + "' ";
            }
            if (this.comboBox1.Text == "调度任务索引")
            {
                if (isint == false)
                {
                    //MessageBox.Show("请输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    textBox1.Text = string.Empty;
                    return;
                }
                _monstatus = " 调度任务索引='" + this.textBox1.Text.Trim() + "' ";
            }
            TSMMonitorRefresh_Click(sender, e);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            _monstatus = " F_Status<>-1 ";

            TSMMonitorRefresh_Click(sender, e);
        }

        private void dgvMonitor_DataSourceChanged(object sender, EventArgs e)
        {
            dgvMonitor.Columns["F_Status"].Visible = false;
        }

        private void FrmModifyMonitor_Load(object sender, EventArgs e)
        {
            rbmonRun_CheckedChanged(sender, e);
        }

        private void tsmAGVGet_Click(object sender, EventArgs e)
        {
            string sql = "";
            //由T_Monitor_Task表中获得F_NumParam2字段值 条件：消息返回的小车任务号
            DataTable tableMonitorTask = dbo.ExceSQL("SELECT F_NumParam2,F_AgvTask,F_AgvNo FROM T_MONITOR_TASK WHERE F_DeviceIndex=1001 and F_MonitorIndex=" + this.dgvMonitor.CurrentRow.Cells[2].Value + "").Tables[0];
            if (tableMonitorTask.Rows.Count > 0)
            {
                if (MessageBox.Show("您确认手工报告AGV叉货完成吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }

                sql = "UPDATE T_Monitor_Task SET F_Status = 2 WHERE (F_MonitorIndex =" + this.dgvMonitor.CurrentRow.Cells[2].Value + ")";
                dbo.ExceSQL(sql);

                //由T_Base_AGV_Gate表中获得F_AGVGateDeviceIndex字段值 条件：T_Base_AGV_Gate.F_Address = T_Monitor_Task.F_NumParam2
                DataTable tableAGVGate = dbo.ExceSQL("SELECT F_AGVGateDeviceIndex FROM T_BASE_AGV_GATE WHERE F_ADDRESS = " + Convert.ToInt32(tableMonitorTask.Rows[0]["F_NumParam2"]) + "").Tables[0];
                if (tableAGVGate.Rows.Count > 0)
                {
                    if (MessageBox.Show("您确定要把设备:" + tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"] + "置成【无托盘】状态吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                    {
                        return;
                    }
                    //更改T_Base_Device表中的F_HaveGoods字段值为0。条件：T_Base_Device.F_DeviceIndex = T_Base_AGV_Gate.F_AGVGateDeviceIndex
                    dbo.ExecuteSql("UPDATE T_BASE_DEVICE SET F_PALLETBARCODE='-',F_HAVEGOODS = 0 WHERE F_DEVICEINDEX = " + Convert.ToInt32(tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"]) + "");
                    if (ccf.GetManageTaskKindIndexFromMonitor(Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value)) == 1)
                    {
                        //20090817给管理置无托盘信息
                        dboM.ExecuteSql("UPDATE T_ITEMDEVICE SET devicestatus  ='0' WHERE devicecode = '" + tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"] + "'");
                    }
                }
                string sss = "AGV车号:" + tableMonitorTask.Rows[0]["F_AgvNo"].ToString() + ";设备指令索引:" + this.dgvMonitor.CurrentRow.Cells[2].Value.ToString();
                CommonClassLib.CCarryConvert.WriteDarkCasket("设备指令管理", "手工报告AGV叉货完成", tableMonitorTask.Rows[0]["F_AgvNo"].ToString() + "号车", sss);
            }
            else
            {
                MessageBox.Show("只有AGV任务才可以手工报告AGV叉货完成！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void tsmAGVSend_Click(object sender, EventArgs e)
        {
            //由T_Monitor_Task表中获得F_NumParam5字段值 条件：消息返回的小车任务号
            DataTable tableMonitorTask = dbo.ExceSQL("SELECT F_TxtParam,F_NumParam5,F_AgvTask,F_AgvNo FROM T_MONITOR_TASK WHERE F_DeviceIndex=1001 and F_MonitorIndex=" + this.dgvMonitor.CurrentRow.Cells[2].Value + "").Tables[0];
            if (tableMonitorTask.Rows.Count > 0)
            {

                if (MessageBox.Show("您确认手工报告AGV卸货完成吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }

                //由T_Base_AGV_Gate表中获得F_AGVGateDeviceIndex字段值 条件：T_Base_AGV_Gate.F_Address = T_Monitor_Task.F_NumParam2
                DataTable tableAGVGate = dbo.ExceSQL("SELECT F_AGVGateDeviceIndex FROM T_BASE_AGV_GATE WHERE F_ADDRESS = " + Convert.ToInt32(tableMonitorTask.Rows[0]["F_NumParam5"]) + "").Tables[0];
                if (tableAGVGate.Rows.Count > 0)
                {
                    if (MessageBox.Show("您确定要把设备:" + tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"] + "置成【有托盘】状态吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                    {
                        return;
                    }
                    //更改T_Base_Device表中的F_HaveGoods字段值为0。条件：T_Base_Device.F_DeviceIndex = T_Base_AGV_Gate.F_AGVGateDeviceIndex
                    dbo.ExecuteSql("UPDATE T_BASE_DEVICE SET F_PALLETBARCODE='" + tableMonitorTask.Rows[0]["F_TxtParam"] + "',F_HAVEGOODS = 1 WHERE F_DEVICEINDEX = " + Convert.ToInt32(tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"]) + "");

                }
                string sss = "AGV车号:" + tableMonitorTask.Rows[0]["F_AgvNo"].ToString() + ";设备指令索引:" + this.dgvMonitor.CurrentRow.Cells[2].Value.ToString();
                CommonClassLib.CCarryConvert.WriteDarkCasket("设备指令管理", "手工报告AGV卸货完成", tableMonitorTask.Rows[0]["F_AgvNo"].ToString() + "号车", sss);
                gs.ActionComplete(1001, Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value), Model.CGeneralFunction.TASKFINISH);
            }
            else
            {
                MessageBox.Show("只有AGV任务才可以手工报告AGV放货完成！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void tsmAGVBank_Click(object sender, EventArgs e)
        {
            //20091016dbo.ExecuteSql("DELETE FROM T_Monitor_Task WHERE F_DeviceIndex=1001 and F_MonitorIndex=" + this.dgvMonitor.CurrentRow.Cells[2].Value + "");
            gs.ActionComplete(1001, Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value), Model.CGeneralFunction.TASKFINISH);
        }

        private void tsmAGVGoods_Click(object sender, EventArgs e)
        {
            gs.ActionComplete(1001, Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value), Model.CGeneralFunction.TASKFINISH);
            //20091016dbo.ExecuteSql("DELETE FROM T_Monitor_Task WHERE F_DeviceIndex=1001 and F_MonitorIndex=" + this.dgvMonitor.CurrentRow.Cells[2].Value + "");
        }

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    if (this.dgvMonitor.CurrentRow == null)
        //    {

        //        return;
        //    }
        //    if (Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[0].Value) > 0)
        //    {

        //        if (this.dgvMonitor.CurrentRow.Cells[3].Value.ToString() == "1001")
        //        {
        //            if (MessageBox.Show("您确认手工强制分配选中队列的AGV任务号吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
        //            {
        //                return;
        //            }
        //            dbo.ExceSQL("UPDATE T_Monitor_Task SET F_AgvNo = " + this.nudAGVtask.Value + " WHERE (F_MonitorIndex =" + this.dgvMonitor.CurrentRow.Cells[2].Value + ")");
        //            DataView dv = dbo.ExceSQL("SELECT * FROM T_Monitor_Task (F_MonitorIndex =" + this.dgvMonitor.CurrentRow.Cells[2].Value + ") and (F_AGVNextTask IS NOT NULL)").Tables[0].DefaultView;
        //            if (dv.Count > 0)
        //            {
        //                dbo.ExceSQL("UPDATE T_Monitor_Task SET F_AgvNo = " + this.nudAGVtask.Value + " WHERE (F_MonitorIndex =" + dv[0]["F_AGVNextTask"] + ")");

        //            }
        //            dv = dbo.ExceSQL("SELECT * FROM T_Monitor_Task (F_AGVNextTask =" + this.dgvMonitor.CurrentRow.Cells[2].Value + ")").Tables[0].DefaultView;
        //            if (dv.Count > 0)
        //            {
        //                dbo.ExceSQL("UPDATE T_Monitor_Task SET F_AgvNo = " + this.nudAGVtask.Value + " WHERE (F_MonitorIndex =" + dv[0]["F_MonitorIndex"] + ")");

        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("只有AGV任务才可以手工强制分配选中队列的AGV任务号！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //            return;
        //        }

        //    }
        //}

        int GetDeviceKindIdx(int devIdx)
        {
            try
            {
                devinfo = Model.CGetInfo.GetDeviceInfo(devIdx);
                return devinfo.DeviceKind;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        int GetManageTaskIndexfromMonitor(int monitorIdx)
        {
            DataView dv = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIdx + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_ManageTaskIndex"]);
            }
            else
            {
                return -1;
            }
        }
        int GetManageTaskKindIndexFromMonitor(int monitorIdx)
        {
            DataView dv = dbo.ExceSQL("SELECT F_ManageTaskKindIndex FROM T_Monitor_Task WHERE (F_MonitorIndex = " + monitorIdx + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_ManageTaskKindIndex"]);
            }
            else
            {
                return -1;
            }
        }
        int GetDeviceOrderFromMonitor(int MonitorIndex)
        {
            try
            {
                string sql = "select F_DeviceCommandIndex from T_Monitor_Task where (F_DeviceCommandIndex IS NOT NULL) and F_MonitorIndex=" + MonitorIndex;
                DataView dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_DeviceCommandIndex"]);
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void AssociateComplete(int deviceIdx, int mindex, int status)
        {
            int ClearZero = 0;
            if (status >= 1)
            {
                ClearZero = 1;
            }
            else
            {
                ClearZero = Model.CGeneralFunction.TASKFINISH;
            }
            int DeviceIdx = deviceIdx;
            int devKind;
            //20091107
            DataView dv = dbo.ExceSQL("select F_MonitorIndex,F_DeviceIndex,F_DeviceCommandIndex,F_NumParam4 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);

                        gs.ActionComplete(DeviceIdx, Convert.ToInt32(dv2[0]["F_MonitorIndex"]), ClearZero);
                    }
                    //再报告完成自己
                    DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                    devKind = ccf.GetDeviceKindIdx(DeviceIdx);

                    gs.ActionComplete(DeviceIdx, mindex, ClearZero);
                }
                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);

                        gs.ActionComplete(DeviceIdx, mindex, ClearZero);
                        //再报告完成主任务
                        DeviceIdx = Convert.ToInt32(dv3[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        gs.ActionComplete(DeviceIdx, Convert.ToInt32(dv3[0]["F_MonitorIndex"]), ClearZero);
                    }
                    else
                    {
                        //无关联任务，只报告完成自己
                        DeviceIdx = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                        devKind = ccf.GetDeviceKindIdx(DeviceIdx);
                        //20091107长输送机链需要给最后一个报告完成的清零
                        if ((devKind == 2) && (Convert.ToInt32(dv[0]["F_NumParam4"]) > 0) && (dv[0]["F_DeviceCommandIndex"].ToString() == "6"))
                        {
                            DeviceIdx = Convert.ToInt32(dv[0]["F_NumParam4"]);
                        }
                        gs.ActionComplete(DeviceIdx, mindex, ClearZero);
                    }
                }

            }
        }

        private void dgvMonitor_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow DGVRow in this.dgvMonitor.Rows)
            {
                if (DGVRow != null)
                {
                    if (Convert.ToInt32(DGVRow.Cells["f_status"].Value) >= 30)
                    {
                        DGVRow.DefaultCellStyle.BackColor = Color.Red;
                    }

                }
            }
        }

        private void TSMmonitorDel_Click(object sender, EventArgs e)
        {
            char[] cc = new char[1] { '：' };
            string[] split = TSMonitor.Text.Split(cc);
            if (split[1] == "") return;


            DataView dv = dbo.ExceSQL("SELECT * FROM T_Monitor_Task Where F_MonitorIndex=" +
                Convert.ToInt32(split[1])).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                //20100108中间指令被报告完成时给与提示和警告

                DataView dv0 = dbo.ExceSQL("SELECT MIN(F_MonitorIndex) AS mmi FROM dbo.T_Monitor_Task WHERE (F_ManageTaskIndex = " + dv[0]["F_ManageTaskIndex"] + ") AND (F_ManageTASKKINDINDEX = " + dv[0]["F_ManageTASKKINDINDEX"] + ")").Tables[0].DefaultView;
                if (dv0.Count > 0)
                {
                    if ((dv0[0]["mmi"] != DBNull.Value) && (dv0[0]["mmi"].ToString() != split[1]))
                    {
                        if (MessageBox.Show("表箱条码：" + dv[0]["F_TxtParam"].ToString() + "，设备名称:“" + this.dgvMonitor.CurrentRow.Cells["设备名称"].Value.ToString() + ";设备命令:" + this.dgvMonitor.CurrentRow.Cells["设备命令名称"].Value.ToString() + "”之前还有没执行完成的调度任务，提前【删除设备指令】会造成调度任务混乱，您确认要继续操作吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                        {
                            return;
                        }
                    }
                }
                dv0 = null;
                //20100108操作黑匣子增加托盘条码
                if (MessageBox.Show("您确认表箱条码：" + dv[0]["F_TxtParam"].ToString() + "，设备名称:“" + this.dgvMonitor.CurrentRow.Cells["设备名称"].Value.ToString() + ";设备命令:" + this.dgvMonitor.CurrentRow.Cells["设备命令名称"].Value.ToString() + "”已经不需要设备执行了吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }

                string sss = "设备索引:" + dv[0]["F_DeviceIndex"].ToString() + ";设备指令索引:" + dv[0]["F_MonitorIndex"].ToString();
                //20100108操作黑匣子增加托盘条码
                CommonClassLib.CCarryConvert.WriteDarkCasket("设备指令管理", "手工删除设备指令", "表箱条码：" + dv[0]["F_TxtParam"].ToString(), sss);
                gs.ActionComplete(Convert.ToInt32(dv[0]["F_DeviceIndex"]), Convert.ToInt32(dv[0]["F_MonitorIndex"]), Model.CGeneralFunction.TASKDELETE);//20100905
                

                this.dgvMonitor.DataSource = dbo.ExceSQL("select * from V_Monitor_Task where " + _monstatus + " order by 设备指令索引 asc ").Tables[0].DefaultView;
            }
        }

        //private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        string df = "";

        //        switch (this.comboBox1.Text)
        //        {
        //            case "托盘条码":
        //                df = "附加信息";
        //                break;
        //            case "调度任务索引":
        //                df = "调度任务索引";
        //                break;
        //            case "设备指令索引":
        //                df = "设备指令索引";
        //                break;


        //            default:
        //                return;
        //        }
        //        //20100208
        //        string sql = "select distinct " + df + " from V_Monitor_Task ";
        //        DataView dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
        //        if (dv.Count > 0)
        //        {
        //            this.textBox1.DataSource = null;
        //            this.textBox1.DisplayMember = df;
        //            this.textBox1.ValueMember = df;
        //            this.textBox1.DataSource = dv;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}




        //private void dgvMonitor_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        //{
        //    if ((e.RowIndex >= 0))//&&(e.Button == MouseButtons.Right)
        //    {
        //        dgvMonitor.ClearSelection();
        //        dgvMonitor.Rows[e.RowIndex].Selected = true;
        //        dgvMonitor.CurrentCell = dgvMonitor.Rows[e.RowIndex].Cells[0];

        //    }
        //    if (e.RowIndex >= 0)
        //    {
        //        if (this.dgvMonitor.CurrentRow.Cells[3].Value.ToString() == "1001")
        //        {
        //            this.groupBox1.Visible = true;
        //            int fid = ccf.GetManageTaskIndexfromMonitor(Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value));
        //            int mti = ccf.GetManageTaskKindIndexFromMonitor(Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value));
        //            DataView dv = dbo.ExceSQL("SELECT FSTARTDEVICE FROM T_Manage_Task WHERE (F_ManageTaskKindIndex = " +
        //                mti + ") AND (FID = " + fid + ") and ((FSTARTDEVICE = '3801') or (FENDDEVICE = '3801'))").Tables[0].DefaultView;
        //            if (dv.Count > 0)
        //            {
        //                cobAGVno.Items.Clear();
        //                cobAGVno.Items.Add(3);
        //                cobAGVno.Items.Add(4);
        //                cobAGVno.Text = "3";
        //            }
        //            dv = dbo.ExceSQL("SELECT FSTARTDEVICE FROM T_Manage_Task WHERE (F_ManageTaskKindIndex = " +
        //                mti + ") AND (FID = " + fid + ") and ((FSTARTDEVICE = '2801') or (FENDDEVICE = '2801'))").Tables[0].DefaultView;
        //            if (dv.Count > 0)
        //            {
        //                cobAGVno.Items.Clear();
        //                cobAGVno.Items.Add(1);
        //                cobAGVno.Items.Add(2);
        //                cobAGVno.Text = "1";
        //            }
        //        }
        //        else
        //        {
        //            this.groupBox1.Visible = false;
        //        }
        //    }
        //}

        //private void btAGVNO_Click(object sender, EventArgs e)
        //{
            
        //    if (dgvMonitor.CurrentCell == null) return;
        //    int agvno=0;
        //    if (int.TryParse(cobAGVno.Text, out agvno) == true)
        //    {
        //        int fid =ccf.GetManageTaskIndexfromMonitor( Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value));
        //        int mti =ccf.GetManageTaskKindIndexFromMonitor( Convert.ToInt32(this.dgvMonitor.CurrentRow.Cells[2].Value));
        //        if (MessageBox.Show("您确认要修改【" + this.dgvMonitor.CurrentRow.Cells[1].Value.ToString() + ",调度任务索引：" + fid.ToString() + "】的AGV车号吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
        //        {
        //            return;
        //        }
        //        object ob = dbo.GetSingle("SELECT FID FROM T_Manage_Task WHERE (F_ManageTaskKindIndex = "+mti+") AND (F_RELATIVECONTORLID = "+fid+")");
        //        int rfid = 0;
        //        if (ob == null) rfid = 0;
        //        else
        //        {
        //            int.TryParse(ob.ToString(), out rfid);
        //        }
        //        dbo.ExecuteSql("update T_Monitor_Task set F_AgvNo=" + agvno + " where (F_DeviceIndex=1001) and (F_ManageTASKKINDINDEX=" + mti + ") and (F_ManageTaskIndex=" + fid + " or F_ManageTaskIndex=" + rfid + ") ");

        //    }
        //    else
        //    {
        //        MessageBox.Show("AGV车号只能是数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        return;
                
        //    }
        //}


    }
}