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 Microsoft.VisualBasic;
using System.Resources;
using System.Collections;

namespace SystemConfig
{
    public partial class FrmDeviceEdit : Form
    {
        bool IfUpdate = false;
        string CommonSql = "SELECT  T_Base_Device.F_DeviceIndex AS 设备索引, " +
                  " T_Base_Device.F_DeviceName AS 设备名称, " +
                  " T_Base_Device.F_DeviceKindIndex AS 设备类型索引, " +
                  " T_Base_Device_Kind.F_DeviceKindName AS 设备类型名称, " +
                  " T_Base_Device.F_CommType AS 通讯接口方式, " +
                  " T_Base_Device.F_DBWAddress AS DBW1区开始地址, " +
                  " T_Base_Device.F_DBWSendLength AS 发送字数," +
                  " T_Base_Device.F_DBWGetLength AS 接收字数, " +
                  " T_Base_Device.F_SerialPort AS 串口编号, " +
                  " T_Base_Device.F_CommSettings AS 通讯参数设置," +
                  " T_Base_Device.F_LocalIP AS 本地IP地址, " +
                  " T_Base_Device.F_LocalPort AS 本地端口," +
                  " T_Base_Device.F_RemoteIP AS 远程IP地址, " +
                  " T_Base_Device.F_RemotePort AS 远程端口,F_LockedState AS 设备状态," +
                  " F_EndNode AS 是终端节点,F_WaitPallet AS 可以停盘, F_DeviceVisual AS 动画显示," +
                  " F_Picture AS 图片源名称,F_ControlName AS 监控界面上的图形控件名称, " +
                  " T_Base_Device.F_BindingDevice AS 捆绑设备索引,F_NeedOptimize AS 需要优化调度," +
                  " F_CollectPut AS 需要积放,f_createlock as 禁用自动回收JIT空桶,T_Base_Device.F_DBW2Address AS DBW2区开始地址 " +
                  " FROM  T_Base_Device,T_Base_Device_Kind ";
        private bool _laneIndex = false;

        public bool LaneIndex
        {
            get { return _laneIndex; }
            set { _laneIndex = value; }
        }
        private bool _laneGateDeviceIndex = false;

        public bool LaneGateDeviceIndex
        {
            get { return _laneGateDeviceIndex; }
            set { _laneGateDeviceIndex = value; }
        }
        private bool _isSelected = false;

        public bool IsSelected
        {
            get { return _isSelected; }
            set { _isSelected = value; }
        }
        private static FrmDeviceEdit _formInstance;

        public static FrmDeviceEdit FormInstance
        {
            get 
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmDeviceEdit();
                    
                }
                return _formInstance;
            }
            set { FrmDeviceEdit._formInstance = value; }
        }
        DBOperator dbo = CStaticClass.dbo;
        
        public FrmDeviceEdit()
        {
            InitializeComponent();
            _formInstance = this;
            dbo.Open();
        }

        private void FrmDeviceEdit_Load(object sender, EventArgs e)
        {
            this.tabControl1.SelectTab("tabPage2");
            if (_isSelected == true)
            {
                btSelectOK.Visible = true;
            }
            else
                btSelectOK.Visible = false;

            DataSet ds= dbo.ExceSQL("select * from T_BASE_CommType");
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                
                this.cbCommType.DataSource = ds.Tables[0].DefaultView;
                this.cbCommType.ValueMember = "F_CommType";
                this.cbCommType.DisplayMember = "F_CommType";
            }
            this.cbCommType.Text = "";
            cbPicture.Items.Clear();
            ResourceManager rm = new ResourceManager("SystemConfig.Properties.Resources", this.GetType().Assembly);
            ResourceSet rs=rm.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture,true,true);

            IDictionaryEnumerator en = rs.GetEnumerator();
            

            // Goes through the enumerator, printing out the key and value pairs.
            while (en.MoveNext())
            {
                if ((en.Key.ToString().IndexOf("Err") < 0) && (en.Key.ToString().IndexOf("Goods") < 0))
                {
                    cbPicture.Items.Add(en.Key);
                }
              
            }
            rs.Close();

            
            ///////////////////绑定探物光电
            DataView dv4 = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceName, F_DeviceKindIndex FROM T_Base_Device Where F_DeviceKindIndex=18 order by F_DeviceName").Tables[0].DefaultView;
            //按钮盒
            DataView dv3 = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceName, F_DeviceKindIndex FROM T_Base_Device Where F_DeviceKindIndex=14 order by F_DeviceName").Tables[0].DefaultView;
            DataView dv2 = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceName, F_DeviceKindIndex FROM T_Base_Device Where F_DeviceKindIndex=14 order by F_DeviceName").Tables[0].DefaultView;
            //容器类型检测
            DataView dv1 = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceName, F_DeviceKindIndex FROM T_Base_Device Where F_DeviceKindIndex=18 order by F_DeviceName").Tables[0].DefaultView;
            if (dv4.Count > 0)
            {
                this.cbBindingDeviceIndex.ValueMember = "F_DeviceIndex";
                this.cbBindingDeviceIndex.DisplayMember = "F_DeviceName";
                this.cbBindingDeviceIndex.DataSource = dv4;
                this.cbPauseWeighButton.ValueMember = "F_DeviceIndex";
                this.cbPauseWeighButton.DisplayMember = "F_DeviceName";
                this.cbPauseWeighButton.DataSource = dv3;
                this.cbLoopButton.ValueMember = "F_DeviceIndex";
                this.cbLoopButton.DisplayMember = "F_DeviceName";
                this.cbLoopButton.DataSource = dv2;
                this.cbContainerType.ValueMember = "F_DeviceIndex";
                this.cbContainerType.DisplayMember = "F_DeviceName";
                this.cbContainerType.DataSource = dv1;

            }
            this.cbBindingDeviceIndex.SelectedValue = 0;
            this.cbPauseWeighButton.SelectedValue = 0;
            this.cbLoopButton.SelectedValue = 0;
            this.cbContainerType.SelectedValue = 0;
            
        }

        private void cbCommType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.cbCommType.SelectedValue.ToString())
            {
                case "SimensSerialPort":
                    this.gbSerialPort.Visible =true;
                    this.gbCp5611.Visible = false;
                    this.gbSockects.Visible = false;
                    break;
                case "SimensCP5611":
                    this.gbSerialPort.Visible = false;
                    this.gbSockects.Visible = false;
                    this.gbCp5611.Visible = true;
                    break;
                case "Symbol3204":
                    this.gbSerialPort.Visible = true;
                    this.gbCp5611.Visible = false;
                    this.gbSockects.Visible = false;
                    break;
                case "SocketsUDP":
                    this.gbSerialPort.Visible = false;
                    this.gbCp5611.Visible = false;
                    this.gbSockects.Visible = true;
                    break;
                case "SocketsTCPIP":
                    this.gbSerialPort.Visible = false;
                    this.gbCp5611.Visible = false;
                    this.gbSockects.Visible = true;
                    break;
                case "SocketsTCPIPServer":
                    this.gbSerialPort.Visible = false;
                    this.gbCp5611.Visible = false;
                    this.gbSockects.Visible = true;
                    break;
                default:
                    break;
            }
           
        }

        private void btQuery_Click(object sender, EventArgs e)
        {
            if (tbContent.Text.Trim() == "") return;
            try
            {
                string df = "";

                switch (this.cbField.Text)
                {
                    case "设备索引":
                        df = "F_DeviceIndex";
                        break;
                    case "设备名称":
                        df = "F_DeviceName";
                        break;
                    case "设备类型索引":
                        df = "T_Base_Device.F_DeviceKindIndex";
                        break;
                    case "设备类型名称":
                        df = "F_DeviceKindName";
                        break;
                    case "通讯接口类型":
                        df = "F_CommType";
                        break;
                    default:
                        return;
                }
                string sql = CommonSql + "  WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex " +
                   " and  " + df + "= '" + this.tbContent.Text + "' order by T_Base_Device.F_DeviceIndex";
                DataSet ds = dbo.ExceSQL(sql);
                //if (ds.Tables[0].DefaultView.Count > 0)
                //{
                    this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void btNullQuery_Click(object sender, EventArgs e)
        {
            this.cbField.Text = "";
            this.tbContent.Text = "";

        }

        private void btNull_Click(object sender, EventArgs e)
        {
            this.tbDeviceIndex.Text = "";
            this.tbDeviceKindIndex.Text = "";
            this.tbDeviceName.Text = "";
            this.cbCommType.Text = "";
            this.tbAddress.Text = "";
            this.tbCommSettings.Text = "";
            this.tbGetLength.Text = "";
            this.tbPort.Text = "";
            this.tbSendLength.Text = "";
            this.tblocalIP.Text = "";
            this.tblocalport.Text = "";
            this.tbremoteIP.Text = "";
            this.tbremoteport.Text = "";
        }

        private void btBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btSave_Click(object sender , EventArgs e)
        {
            try
            {
                #region 条件检查
                
                if (MessageBox.Show("您确认要保存设备信息吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }
                string sql = "";
                string sqlUpdate = "";
                int LockedState, devvisual;
                string endnode, waitp, pic, ctrolname, NeedOptimize, CollectPut,CreateLock;
                this.tbCommSettings.Text.Replace(',', '，');
                
                if (Information.IsNumeric(this.tbDeviceIndex.Text) == false)
                {
                    MessageBox.Show("设备索引只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    tbDeviceIndex.Focus();
                    return;
                }
                if (Information.IsNumeric(this.tbDeviceKindIndex.Text) == false)
                {
                    MessageBox.Show("设备类型索引只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    tbDeviceKindIndex.Focus();
                    return;
                }
                if (this.tbDeviceName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("设备名称不允许是空值！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    tbDeviceName.Focus();
                    return;
                }
                if (this.cbCommType.Text.Trim().Length == 0)
                {
                    MessageBox.Show("通讯接口类型不允许是空值！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cbCommType.Focus();
                    return;
                }
                
                if (cbLockedState.Text == "0:空闲")
                {
                    LockedState = 0;
                }
                else if (cbLockedState.Text == "-1:停用")
                {
                    LockedState = -1;
                }
                else
                {
                    if (Information.IsNumeric(cbLockedState.Text) != true)
                    {
                        MessageBox.Show("只能是＂0:空闲＂，＂-1:停用＂或者是整型的设备指令索引！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        cbLockedState.Focus();
                        return;
                    }
                    else
                    {
                        LockedState = Convert.ToInt32(cbLockedState.Text.Trim());
                    }
                    
                }
                if (chbDeviceVisual.Checked == true)
                {
                    devvisual = 1;
                }
                else
                {
                    devvisual = 0;
                }
                if (this.chbEndNode.Checked == true)
                {
                    endnode  = "1";
                }
                else
                {
                    endnode  = "0";
                }
                if (chbWaitPallet.Checked == true)
                {
                    waitp  = "1";
                }
                else
                {
                    waitp  = "0";
                }
                if (chbNeedOptimize.Checked == true)
                {
                    NeedOptimize = "1";
                }
                else
                {
                    NeedOptimize = "0";
                }
                if (chbCollectPut.Checked == true)
                {
                    CollectPut = "1";
                }
                else
                {
                    CollectPut = "0";
                }
                if (cbPicture.Text.Trim() == "")
                {
                    pic = null;
                }
                else
                {
                    pic = cbPicture.Text.Trim();
                }
                if (tbControlName.Text.Trim() == "")
                {
                    ctrolname= null;
                }
                else
                {
                    ctrolname = tbControlName.Text.Trim();
                }
                if (chbCreateLock.Checked == true)
                {
                    CreateLock = "1";
                }
                else
                {
                    CreateLock = "0";
                }
                #endregion

                #region 以太网模式
                
                
                if ((this.cbCommType.SelectedValue.ToString() == "SocketsUDP") || (this.cbCommType.SelectedValue.ToString() == "SocketsTCPIP") || (this.cbCommType.SelectedValue.ToString() == "SocketsTCPIPServer"))
                {
                    if (Information.IsNumeric(this.tblocalport.Text) == false)
                    {
                        MessageBox.Show("本地通讯端口只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        tblocalport.Focus();
                        return;
                    }
                    char[] cc = new char[1] { '.' };
                    string [] split=this.tblocalIP.Text.Split(cc);
                    for (int i=0;i<=3;i++)
                    {
                        if (Information.IsNumeric(split[i]) == false)
                        {
                            MessageBox.Show("本地Ip地址只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            tblocalIP.Focus();
                            return;
                        }
                    }
                    if (Information.IsNumeric(this.tbremoteport.Text) == false)
                    {
                        MessageBox.Show("远程通讯端口只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        tbremoteport.Focus();
                        return;
                    }
                    split = this.tbremoteIP.Text.Split(cc);
                    for (int i = 0; i <= 3; i++)
                    {
                        if (Information.IsNumeric(split[i]) == false)
                        {
                            MessageBox.Show("远程Ip地址只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            tbremoteIP.Focus();
                            return;
                        }
                    }

                    sql = "insert into T_Base_Device(F_DeviceIndex,F_DeviceKindIndex,F_DeviceName," +
                    "F_CommType,F_LocalIP,F_LocalPort,F_RemoteIP,F_RemotePort,F_LockedState,F_EndNode,F_WaitPallet,F_DeviceVisual,F_Picture,F_ControlName,F_NeedOptimize,F_CollectPut,f_createlock ) " +
                    "values(" + Convert.ToInt32(tbDeviceIndex.Text) + "," + Convert.ToInt32(tbDeviceKindIndex.Text) +
                    ",'" + tbDeviceName.Text + "','" + cbCommType.SelectedValue.ToString() + "','" + this.tblocalIP.Text +
                    "'," + Convert.ToInt32(this.tblocalport.Text) + ",'" + (this.tbremoteIP.Text) + "'," + Convert.ToInt32(this.tbremoteport.Text) + ","+
                    LockedState + ",'" + endnode + "','" + waitp + "'," + devvisual + ",'" + pic + "','" + ctrolname + "','" + NeedOptimize + "','" + CollectPut + "','"+ CreateLock  +"')";
                }
                #endregion

                #region 自由口
                
                
                else if ((this.cbCommType.SelectedValue.ToString() == "SimensSerialPort") || (this.cbCommType.SelectedValue.ToString() == "Symbol3204"))
                {
                    if (Information.IsNumeric(this.tbPort.Text) == false)
                    {
                        MessageBox.Show("串口编号只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        tbPort.Focus();
                        return;
                    }
                    if (this.tbCommSettings.Text.Trim().Length == 0)
                    {
                        MessageBox.Show("通讯参数设置不允许是空值！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        tbCommSettings.Focus();
                        return;
                    }

                    
                    sql = "insert into T_Base_Device(F_DeviceIndex,F_DeviceKindIndex,F_DeviceName," +
                    "F_CommType,F_SerialPort,F_CommSettings,F_LockedState,F_EndNode,F_WaitPallet,F_DeviceVisual,F_Picture,F_ControlName,F_NeedOptimize,F_CollectPut,f_createlock ) " +
                    "values(" + Convert.ToInt32(tbDeviceIndex.Text) + "," + Convert.ToInt32(tbDeviceKindIndex.Text) +
                    ",'" + tbDeviceName.Text + "','" + cbCommType.SelectedValue.ToString() + "'," + Convert.ToInt32(this.tbPort.Text) +
                    ",'" + this.tbCommSettings.Text + "'," +
                    LockedState + ",'" + endnode + "','" + waitp + "'," + devvisual + ",'" + pic + "','" + ctrolname + "','" + NeedOptimize + "','" + CollectPut + "','"+CreateLock  +"')"; ;
                }
                #endregion

                #region SimensCP5611
                
                
                else if (this.cbCommType.SelectedValue.ToString() == "SimensCP5611")
                {
                    if (Information.IsNumeric(this.tbAddress.Text) == false)
                    {
                        MessageBox.Show("DBW1区起始地址只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (Information.IsNumeric(this.tbAddress2.Text) == false)
                    {
                        MessageBox.Show("DBW2区起始地址只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (Information.IsNumeric(this.tbGetLength.Text) == false)
                    {
                        double a, b, c;
                        char[] cc = new char[1] { '/' };
                        string[] sp;
                        if (this.tbGetLength.Text.IndexOf('/') > 0)
                        {
                            sp = this.tbGetLength.Text.Split(cc);
                            a = Convert.ToDouble(sp[0]);
                            b = Convert.ToDouble(sp[1]);
                            c = a / b;
                            this.tbGetLength.Text = c.ToString();
                        }
                        else
                        {
                            MessageBox.Show("接收字数只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    if (Information.IsNumeric(this.tbSendLength.Text) == false)
                    {
                        double a, b, c;
                        char[] cc = new char[1] { '/' };
                        string[] sp;
                        if (this.tbSendLength.Text.IndexOf('/') > 0)
                        {
                            sp = this.tbSendLength.Text.Split(cc);
                            a = Convert.ToDouble(sp[0]);
                            b = Convert.ToDouble(sp[1]);
                            c = a / b;
                            this.tbSendLength.Text = c.ToString();
                        }
                        else
                        {
                            MessageBox.Show("发送字数只能是数字类型！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                    }
                        
                    }
                    sql = "insert into T_Base_Device(F_DeviceIndex,F_DeviceKindIndex,F_DeviceName," +
                    "F_CommType,F_DBWAddress,F_DBWSendLength,F_DBW2Address,F_DBWGetLength,F_LockedState,F_EndNode,F_WaitPallet,F_DeviceVisual,F_Picture,F_ControlName,F_NeedOptimize,F_CollectPut,f_createlock ) " +
                    "values(" + Convert.ToInt32(tbDeviceIndex.Text) + "," + Convert.ToInt32(tbDeviceKindIndex.Text) +
                    ",'" + tbDeviceName.Text + "','" + cbCommType.SelectedValue + "'," + Convert.ToInt32(this.tbAddress.Text) +
                    "," + Convert.ToDouble(this.tbSendLength.Text) + "," + Convert.ToInt32(this.tbAddress2.Text) +"," + Convert.ToDouble(this.tbGetLength.Text) + "," +
                    LockedState + ",'" + endnode + "','" + waitp + "'," + devvisual + ",'" + pic + "','" + ctrolname + "','" + NeedOptimize + "','" + CollectPut + "','"+ CreateLock  +"')";
                }
                #endregion

                #region 虚拟类接口


                else //if ((this.cbCommType.SelectedValue.ToString() == "-"))
                {
                    sql = "insert into T_Base_Device(F_DeviceIndex,F_DeviceKindIndex,F_DeviceName," +
                    " F_CommType,F_LockedState,F_EndNode,F_WaitPallet,F_DeviceVisual,F_Picture,F_ControlName,F_NeedOptimize,F_CollectPut,f_createlock) " +
                    "values(" + Convert.ToInt32(tbDeviceIndex.Text) + "," + Convert.ToInt32(tbDeviceKindIndex.Text) +
                    ",'" + tbDeviceName.Text + "','" + cbCommType.SelectedValue + "'," + LockedState + ",'" + endnode + "','" + waitp + "'," +
                    devvisual + ",'" + pic + "','" + ctrolname + "','" + NeedOptimize + "','" + CollectPut + "','" + CreateLock + "')"; ;
                }
                #endregion

                #region 数据显示
                
                
                DataSet ds = dbo.ExceSQL("SELECT F_DeviceKindIndex, F_GoodsMoveKindIndex," +
                    " F_DeviceKindName FROM T_Base_Device_Kind where F_DeviceKindIndex=" + Convert.ToInt32(this.tbDeviceKindIndex.Text));
                if (ds.Tables[0].DefaultView.Count <= 0)
                {
                    MessageBox.Show("设备类型索引在数据库中不存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                ds.Clear();
                
                string strsql = CommonSql + " WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex " +
                   " and  F_DeviceIndex =  " + Convert.ToInt32(this.tbDeviceIndex.Text);
                #endregion

                #region 修改设备信息


                if (IfUpdate == true)
                {
                    int addr = 0, addr2 = 0, sport = 0, lport = 0, rport = 0;
                    double slen=0, glen=0;
                    string lip = null, rip = null;
                    if (tbAddress.Text.Length > 0)
                        addr =Convert.ToInt32(tbAddress.Text);
                    if (tbPort.Text.Length > 0)
                        sport = Convert.ToInt32(tbPort.Text);
                    if (tbSendLength.Text.Length > 0)
                        slen = Convert.ToDouble(tbSendLength.Text );
                    if (tbAddress2.Text.Length > 0)
                        addr2 = Convert.ToInt32(tbAddress2.Text);
                    if (tbGetLength.Text.Length > 0)
                        glen = Convert.ToDouble(tbGetLength.Text);
                    if (tblocalIP.Text.Length > 0)
                        lip = tblocalIP.Text ;
                    if (tblocalport.Text.Length > 0)
                        lport = Convert.ToInt32(tblocalport.Text);
                    if (tbremoteIP.Text.Length > 0)
                        rip = tbremoteIP.Text;
                    if (tbremoteport.Text.Length > 0)
                        rport = Convert.ToInt32(tbremoteport.Text);
                    sqlUpdate = "update T_Base_Device set F_DeviceKindIndex="+ tbDeviceKindIndex.Text
                        + ", F_DeviceName='" + tbDeviceName.Text + "',F_CommType='"+ cbCommType.Text
                        + "',F_DBWAddress=" + addr + ",F_DBWSendLength="+ slen
                        + ",F_DBW2Address=" + addr2 + ",F_DBWGetLength=" + glen + ",F_SerialPort=" + sport
                        + ",F_LocalIP='" + lip + "',F_LocalPort=" + lport
                        + ",F_RemoteIP='" + rip + "',F_RemotePort=" + rport
                        + ", F_CommSettings='" + tbCommSettings.Text
                        + "',F_LockedState ="+LockedState +", F_EndNode ='"+endnode 
                        +"', F_WaitPallet ='"+waitp +"', F_DeviceVisual ="+devvisual 
                        +", F_Picture ='"+pic +"', F_ControlName ='"+ ctrolname
                        + "',F_NeedOptimize='" + NeedOptimize + "',F_CollectPut='" + CollectPut + "',f_createlock ='"+ CreateLock 
                        + "' where F_DeviceIndex=" + Convert.ToInt32(tbDeviceIndex.Text);
                    ds = dbo.ExceSQL(sqlUpdate);
                    MessageBox.Show("设备信息修改成功！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     
                    IfUpdate = false;
                }
                #endregion

                else
                {
                    //判断是否存在
                    ds = dbo.ExceSQL(strsql);
                    if (ds.Tables[0].DefaultView.Count > 0)
                    {
                        MessageBox.Show("设备索引在数据库中已经存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    ds.Clear();
                    ds = dbo.ExceSQL(sql);
                    MessageBox.Show("设备信息录入成功！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                

                ds.Clear();
                ds = dbo.ExceSQL(strsql);
                this.dataGridView1.DataSource = ds.Tables[0].DefaultView;


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount <= 0)
            {
                return;
            }

            this.tabControl1.SelectTab("tabPage1");
            this.tbDeviceIndex.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString()+ "";
            this.tbDeviceName.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString() + "";
            this.tbDeviceKindIndex.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString() + "";
            //this.cbCommType.SelectedValue = this.dataGridView1.CurrentRow.Cells[4].Value.ToString() + "";
            this.cbCommType.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString() + "";
            cbCommType_SelectedIndexChanged(sender, e);
            if (this.dataGridView1.CurrentRow.Cells[4].Value.ToString() + "" == "")
            {
                this.cbCommType.Text = "-";
            }
            this.tbAddress.Text = this.dataGridView1.CurrentRow.Cells[5].Value.ToString() + "";
            this.tbSendLength.Text = this.dataGridView1.CurrentRow.Cells[6].Value.ToString() + "";
            this.tbGetLength.Text = this.dataGridView1.CurrentRow.Cells[7].Value.ToString() + "";
            this.tbPort.Text = this.dataGridView1.CurrentRow.Cells[8].Value.ToString() + "";
            this.tbCommSettings.Text = this.dataGridView1.CurrentRow.Cells[9].Value.ToString() + "";
            this.tblocalIP.Text = this.dataGridView1.CurrentRow.Cells[10].Value.ToString() + "";
            this.tblocalport.Text = this.dataGridView1.CurrentRow.Cells[11].Value.ToString() + "";
            this.tbremoteIP.Text = this.dataGridView1.CurrentRow.Cells[12].Value.ToString() + "";
            this.tbremoteport.Text = this.dataGridView1.CurrentRow.Cells[13].Value.ToString() + "";
            if(this.dataGridView1.CurrentRow.Cells[14].Value.ToString() + ""=="0")
            {
                this.cbLockedState.Text = "0:空闲";
            }
            else if (this.dataGridView1.CurrentRow.Cells[14].Value.ToString() + "" == "-1")
            {
                this.cbLockedState.Text  = "-1:停用";
            }
            else
            {
                this.cbLockedState.Text = this.dataGridView1.CurrentRow.Cells[14].Value.ToString() + "";
            }
            if (this.dataGridView1.CurrentRow.Cells[15].Value.ToString() + "" == "1")
            {
                this.chbEndNode.Checked = true;
            }
            else
            {
                this.chbEndNode.Checked = false;
            }
            if (this.dataGridView1.CurrentRow.Cells[16].Value.ToString() + "" == "1")
            {
                this.chbWaitPallet.Checked = true;
            }
            else
            {
                this.chbWaitPallet.Checked = false;
            }
            if (this.dataGridView1.CurrentRow.Cells[17].Value.ToString() + "" == "1")
            {
                this.chbDeviceVisual.Checked = true;
            }
            else
            {
                this.chbDeviceVisual.Checked = false;
            }
            this.tbControlName.Text = this.dataGridView1.CurrentRow.Cells[19].Value.ToString() + "";
            this.cbPicture.Text = this.dataGridView1.CurrentRow.Cells[18].Value.ToString() + "";
            if (this.dataGridView1.CurrentRow.Cells[21].Value.ToString() + "" == "1")
            {
                this.chbNeedOptimize.Checked = true;
            }
            else
            {
                this.chbNeedOptimize.Checked = false;
            }
            if (this.dataGridView1.CurrentRow.Cells[22].Value.ToString() + "" == "1")
            {
                this.chbCollectPut.Checked = true;
            }
            else
            {
                this.chbCollectPut.Checked = false;
            }
            if (this.dataGridView1.CurrentRow.Cells[23].Value.ToString() + "" == "1")
            {
                this.chbCreateLock.Checked = true;
            }
            else
            {
                this.chbCreateLock.Checked = false;
            }
            this.tbAddress2.Text = this.dataGridView1.CurrentRow.Cells[24].Value.ToString() + "";
            IfUpdate = true;
        }

        private void tsmDel_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount <= 0)
            {
                return;
            }
            if (MessageBox.Show("您确认要删除选中行的“设备索引：" + this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "”信息吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            dbo.ExceSQL("delete from T_Base_Device  where F_DeviceIndex =" + Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value));
            button2_Click(sender, e);
        }

        private void btDeviceKind_Click(object sender, EventArgs e)
        {
            FrmDeviceKindEdit.FormInstance.IsSelected = true; 
            FrmDeviceKindEdit.FormInstance.ShowDialog();
        }

        private void btSelectOK_Click(object sender, EventArgs e)
        {
            if (_laneGateDeviceIndex==true)
                FrmLaneGateEdit.FormInstance.tbLaneGateDeviceIndex.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            else if (_laneIndex==true)
                FrmLaneGateEdit.FormInstance.tbLaneIndex.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IfUpdate = false;
        }

        private void cbLockedState_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void chbDeviceVisual_CheckedChanged(object sender, EventArgs e)
        {
            if (chbDeviceVisual.Checked == true)
            {
                lblctrolname.Visible = true;
                lblpic.Visible = true;
                cbPicture.Visible = true;
                tbControlName.Visible = true;
                pbPicture.Visible = true;
            }
            else
            {
                lblctrolname.Visible = false;
                lblpic.Visible = false;
                cbPicture.Visible = false;
                tbControlName.Visible = false;
                pbPicture.Visible = false;
                tbControlName.Text = "";
                cbPicture.Text = "";
            }
        }

        private void cbPicture_SelectedIndexChanged(object sender, EventArgs e)
        {
            ResourceManager rm = new ResourceManager("SystemConfig.Properties.Resources", this.GetType().Assembly);
            
            pbPicture.BackgroundImage= (System.Drawing.Image)rm.GetObject(cbPicture.Text.Trim());
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string sql = CommonSql + "  WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex  order by T_Base_Device.F_DeviceIndex";
            DataSet ds = dbo.ExceSQL(sql);
           this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
           
        }

        private void button20_Click(object sender, EventArgs e)
        {
            if (cbBindingDeviceIndex.SelectedValue.ToString() == "")
            {
                return;
            }
            else
            {
                string litem;
                litem = cbBindingDeviceIndex.Text.Trim() + "=" + cbBindingDeviceIndex.SelectedValue.ToString();
                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    if (litem == listBox1.Items[i].ToString())
                    {
                        return;
                    }
                }
                this.listBox1.Items.Add(litem);
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex < 0)
            {
                return;
            }
            this.listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        }

        private void button28_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex < 0)
            {
                return;
            }
            else
            {
                string item = listBox1.SelectedItem.ToString();
                int idx = listBox1.SelectedIndex - 1;
                if (idx < 0)
                {
                    return;
                }
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                listBox1.Items.Insert(idx, item);
                listBox1.SelectedIndex = idx;
            }
        }

        private void button27_Click(object sender, EventArgs e)
        {
            if ((listBox1.SelectedIndex >= listBox1.Items.Count) || (listBox1.SelectedIndex < 0))
            {
                return;
            }
            else
            {
                string item = listBox1.SelectedItem.ToString();
                int idx = listBox1.SelectedIndex + 1;
                if ((idx >= listBox1.Items.Count) || (idx < 0))
                {
                    return;
                }
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                listBox1.Items.Insert(idx, item);
                listBox1.SelectedIndex = idx;
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            this.tbDeviceIndex1.Text = "";
            this.cbBindingDeviceIndex.Text = "";
            this.listBox1.Text = "";

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount <= 0)
            {
                return;
            }
            this.tabControl1.SelectTab("tabPage3");
            this.tbDeviceIndex1.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "";
            char[] cc = new char[1] { ';' };

            string[] split;

            string sql;

            if (this.dataGridView1.CurrentRow.Cells[20].Value.ToString() + "" == "")
            {
                listBox1.Items.Clear();
                return;
            }
            DataSet ds = dbo.ExceSQL("SELECT * FROM  T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex1.Text.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0]["F_BindingDevice"] == DBNull.Value)
                {
                    listBox1.Items.Clear();
                    return;
                }
                //listBox1
                listBox1.Items.Clear();
                split = dv[0]["F_BindingDevice"].ToString().Split(cc);
                for (int i = split.GetLowerBound(0); i <= split.GetUpperBound(0); i++)
                {
                    sql = "SELECT F_DeviceIndex,F_DeviceName FROM T_Base_Device Where  F_DeviceIndex=" + Convert.ToInt32(split[i]);
                    DataSet ds2 = dbo.ExceSQL(sql);
                    DataView dv2 = ds2.Tables[0].DefaultView;
                    if (dv2.Count <= 0)
                    {
                        MessageBox.Show("捆绑设备索引在设备表不存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        listBox1.Items.Add(dv2[0]["F_DeviceName"].ToString() + "=" + dv2[0]["F_DeviceIndex"].ToString());
                    }
                }
            }
            else
            {
                this.listBox1.Items.Clear();

            }

            IfUpdate = true;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要保存捆绑设备信息吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            if (Information.IsNumeric(this.tbDeviceIndex1.Text) == false)
            {
                MessageBox.Show("主设备索引只允许输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex1.Focus();
                return;
            }
            DataSet ds = dbo.ExceSQL("SELECT * FROM  T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex1.Text.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count <= 0)
            {
                MessageBox.Show("主设备索引在数据库中不存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex1.Focus();
                return;
            }
            ds.Clear();
            dv.Dispose();
            string bindingdevice="";
            char[] dh = new char[1] { '='};
            string[] sp;
            if (listBox1.Items.Count > 0)
            {
                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    sp = listBox1.Items[i].ToString().Split(dh);
                    bindingdevice = bindingdevice + ";" + sp[1];
                }
                bindingdevice = bindingdevice.Substring(1);
            }
            else
            {
                bindingdevice = null;
            }
            dbo.ExceSQL("update t_base_device set f_bindingdevice='"+ bindingdevice +"' where F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex1.Text.Trim()));
            string sql = CommonSql + "  WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex and F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex1.Text.Trim());
            ds = dbo.ExceSQL(sql);
            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
            MessageBox.Show("捆绑设备信息保存成功！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {//WIA的请求暂停称料按钮信息维护
            if (dataGridView1.RowCount <= 0)
            {
                return;
            }
            this.tabControl1.SelectTab("tabPage5");
            this.tbDeviceIndex3.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "";
           
            DataView dv= dbo.ExceSQL("SELECT f_pause FROM  T_Base_Device where f_pause is not NULL and F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex3.Text.Trim())).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                this.cbPauseWeighButton.SelectedValue = dv[0]["f_pause"];

            }
            else
            {
                this.cbPauseWeighButton.SelectedValue = 0;
            }
            

            IfUpdate = true;
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {//JIT的开车到空位的请求按钮信息维护
            if (dataGridView1.RowCount <= 0)
            {
                return;
            }
            this.tabControl1.SelectTab("tabPage4");
            this.tbDeviceIndex2.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "";

            DataSet ds = dbo.ExceSQL("SELECT f_loop  FROM  T_Base_Device where f_loop  is not NULL and F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex2.Text.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                this.cbLoopButton.SelectedValue = Convert.ToInt32(dv[0]["f_loop"]);
            }
            else
            {
                this.cbLoopButton.SelectedValue = 0;
            }
            IfUpdate = true;
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {//JIT/WIA容器类型检测光电信息维护
            if (dataGridView1.RowCount <= 0)
            {
                return;
            }
            this.tabControl1.SelectTab("tabPage6");
            this.tbDeviceIndex4.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "";

            DataSet ds = dbo.ExceSQL("SELECT f_containertype FROM  T_Base_Device where f_containertype is not NULL and F_DeviceIndex=" + Convert.ToInt32(this.tbDeviceIndex4.Text.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                this.cbContainerType.SelectedValue = dv[0]["f_containertype"];
            }
            else
            {
                this.cbContainerType.SelectedValue = 0;
            }
            IfUpdate = true;
        }

        private void btSaveJITLoop_Click(object sender, EventArgs e)
        {
            string devIndex = this.tbDeviceIndex2.Text ;
            if (MessageBox.Show("您确认要保存JIT的开车到空位的请求按钮信息吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            if (Information.IsNumeric(devIndex) == false)
            {
                MessageBox.Show("主设备索引只允许输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex2.Focus();
                return;
            }
            DataSet ds = dbo.ExceSQL("SELECT F_DeviceIndex FROM  T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count <= 0)
            {
                MessageBox.Show("主设备索引在数据库中不存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex2.Focus();
                return;
            }
            ds.Clear();
            dv.Dispose();
            string bindingdevice = this.cbLoopButton.SelectedValue.ToString();
            dbo.ExceSQL("update t_base_device set f_loop ='" + bindingdevice + "' where F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim()));
            string sql = CommonSql + "  WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex and F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim());
            ds = dbo.ExceSQL(sql);
            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
            MessageBox.Show("JIT的开车到空位的请求按钮信息保存成功！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btSaveWIAPause_Click(object sender, EventArgs e)
        {
            string devIndex = this.tbDeviceIndex3.Text ;
            if (MessageBox.Show("您确认要保存WIA暂停称料的请求按钮信息吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            if (Information.IsNumeric(devIndex) == false)
            {
                MessageBox.Show("主设备索引只允许输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex3.Focus();
                return;
            }
            DataSet ds = dbo.ExceSQL("SELECT F_DeviceIndex FROM  T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count <= 0)
            {
                MessageBox.Show("主设备索引在数据库中不存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex3.Focus();
                return;
            }
            ds.Clear();
            dv.Dispose();
            string bindingdevice = this.cbPauseWeighButton.SelectedValue.ToString();
            dbo.ExceSQL("update t_base_device set f_pause  ='" + bindingdevice + "' where F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim()));
            string sql = CommonSql + "  WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex and F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim());
            ds = dbo.ExceSQL(sql);
            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
            MessageBox.Show("WIA暂停称料的请求按钮信息保存成功！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
        
        }

        private void btSaveContainer_Click(object sender, EventArgs e)
        {
            string devIndex = this.tbDeviceIndex4.Text;
            if (MessageBox.Show("您确认要保存JIT/WIA容器类型检测光电信息吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            if (Information.IsNumeric(devIndex) == false)
            {
                MessageBox.Show("主设备索引只允许输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex4.Focus();
                return;
            }
            DataSet ds = dbo.ExceSQL("SELECT F_DeviceIndex FROM  T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim()));
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count <= 0)
            {
                MessageBox.Show("主设备索引在数据库中不存在！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbDeviceIndex4.Focus();
                return;
            }
            ds.Clear();
            dv.Dispose();
            string bindingdevice = this.cbContainerType.SelectedValue.ToString();
            dbo.ExceSQL("update t_base_device set f_containertype  ='" + bindingdevice + "' where F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim()));
            string sql = CommonSql + "  WHERE " +
                   " T_Base_Device.F_DeviceKindIndex =  T_Base_Device_Kind.F_DeviceKindIndex and F_DeviceIndex=" + Convert.ToInt32(devIndex.Trim());
            ds = dbo.ExceSQL(sql);
            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
            MessageBox.Show("JIT/WIA容器类型检测光电信息保存成功！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
        
        }

        private void cbLoopButton_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cbPauseWeighButton_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        

    }
}