using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ICommLayer;
using CommLayerFactory;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu and Jack.Ma
    /// 设备实时状态显示
    /// </summary>
    public partial class FrmDeviceStatus : Form
    {
        #region 变量定义
        Model.MDevice _device = null;
        int _deviceIndex;
        ISendDeviceOrder sdo;

        CCommonFunction ccf = new CCommonFunction();
        DBFactory.DBOperator dbo = CStaticClass.dbo;
        /// <summary>
        /// 设置要显示的设备索引
        /// </summary>
        public int DeviceIndex
        {
            set { _deviceIndex = value;}
        }
        #endregion

        #region 构造函数/初始化
        public FrmDeviceStatus()
        {
            InitializeComponent();
        }

        private void FrmDeviceStatus_Load(object sender, EventArgs e)
        {
            btnRefresh_Click(null, EventArgs.Empty);
        }
        #endregion

        #region 更新设备状态
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            
            //timer1.Enabled = true;
            _device = Model.CGetInfo.GetDeviceInfo(_deviceIndex);
            //20100108
            if (_device == null)
            {
                MessageBox.Show("您选择的设备在数据库没有记录！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
                
            }
            //设备索引
            this.lblDeviceIndex.Text = _device.DeviceIndex.ToString();
            //设备名称
            this.lblDeviceName.Text = _device.DeviceName;
            //设备指令索引
            this.lblTaskIndex.Text = _device.TaskNo.ToString();
            //目标位置
            this.lblArrowLocation.Text = _device.ArrowLocation;
            //设备状态
            switch (_device.RunState)
            {
                case 0:
                    lblDeviceStatus.Text = "空闲";
                    break;
                case 1:
                    lblDeviceStatus.Text = "运行";
                    break;
                case 2:
                    lblDeviceStatus.Text = "故障";
                    break;
                case 3:
                    lblDeviceStatus.Text = "离线";
                    break;
                case 4:
                    lblDeviceStatus.Text = "停用";
                    break;
                case 5://20090920
                    lblDeviceStatus.Text = "动作完成";
                    break;
            }
            //有货/无货
            this.lblHaveGoods.Text = _device.HaveGoods == true ? "有货" : "无货";
            //托盘条码号
            if(_device.DeviceKind==7)//20110418
            {
             // this.lblBarcode.Text=  dbo.GetSingle("Select F_BarCode  from  T_Base_PLC_Ask   where F_DeviceIndex="+ _device.DeviceIndex +"" ).ToString();

            }
                else
            {
            this.lblBarcode.Text = _device.Barcode;
            }
            if (_device.ErrorCode >= 30)
            {     

                    Model.MError err = Model.CGetInfo.GetErrorInfo(Convert.ToInt32(_device.DeviceKind.ToString() + _device.ErrorCode.ToString()));
                    string errmessage = "";//20110401
                    if (err == null)
                    {
                        errmessage = "故障代码未定义!";
                    }
                    else
                    {
                        errmessage = err.ErrorName;
                    }
                     this.lblErrorName.Text = string.Format("{0}:{1}",_device.ErrorCode,errmessage);

                
            }
            else
            {
                this.lblErrorName.Text = "";
            }
            if ((_device.DeviceKind == 1) || (_device.DeviceKind == 4))
            {
                this.lblNowX.Text = _device.XCoor.ToString();
                this.lblNowY.Text = _device.YCoor.ToString();
            }
            else
            {
                this.lblNowX.Text ="";
                this.lblNowY.Text = "";
            }
            //是否逻辑有物
            DataView dv = dbo.ExceSQL("select F_DeviceIndex from T_Base_Device  where F_HaveGoods = 1 and F_DeviceIndex =" + this._deviceIndex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                lblGoods.Text = "逻辑有物";
                //if((_device.DeviceKind ==9)||(_device.DeviceKind ==2&&_device.IfCorrelDoubleFork == "1"))
                //{
                    bthave.Visible=false;
                    bthaveno.Visible=true;
                //}
                //else
                //{
                //    bthave.Visible = false;
                //    bthaveno.Visible = false;
                //}
            }
            else
            {
                lblGoods.Text = "逻辑无物";
               //if((_device.DeviceKind ==9)||(_device.DeviceKind ==2&&_device.IfCorrelDoubleFork == "1"))
               // {
                    bthave.Visible=true;
                    bthaveno.Visible=false;
               // }
               //else
               //{
               //    bthave.Visible = false;
               //    bthaveno.Visible = false;
               //}

            }
            //下达任务按钮
         
            //应答按钮显示
            if (_device.Dbw1Address != -1&&_device.DeviceKind!=5)
            {
                btAnswer.Visible = true;

            }
            else
            {
                btAnswer.Visible = false;
            }
            //逻辑有物按钮显示

            if (_device.DeviceKind == 2 && _deviceIndex > 14000 && _deviceIndex < 15000)
            {

            }

        }
        #endregion

        #region 关闭窗体
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            btnRefresh_Click(sender, e);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要把设备：" + this._deviceIndex + "设成逻辑无物吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            dbo.ExceSQL("UPDATE T_Base_Device SET F_HaveGoods = 0 where  F_DeviceIndex =" + this._deviceIndex);
            btnRefresh_Click(sender, e);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("您确认要把设备：" + this._deviceIndex + "设成逻辑有物吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            dbo.ExceSQL("UPDATE T_Base_Device SET F_HaveGoods = 1 where  F_DeviceIndex =" + this._deviceIndex);
            btnRefresh_Click(sender, e);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要对设备：" + this._deviceIndex + "进行应答处理吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            int deviceKind = ccf.GetDeviceKindIdx(this._deviceIndex);
            sdo = CommModeCreate.CreateSendDeviceOrder(this._deviceIndex);
            if ((deviceKind == 1) || (deviceKind == 6))
            {
                sdo.SendDeviceOrder(2, 0, 0, this._deviceIndex, 0, 0, 0, 0, 0, 0);
            }
            else
            {
                if (deviceKind == 2 && _deviceIndex > 14000)
                {
                    StringBuilder[] wv = { new StringBuilder("2") };
                    StringBuilder[] witemnames = { new StringBuilder("") };
                    witemnames[0].Remove(0, witemnames[0].Length);
                    witemnames[0].Append(Model.CGeneralFunction.DBGet).Append(",byte").Append(Convert.ToString(_device.Dbw2Address + 0));
                    sdo.WriteDBData(witemnames, wv, _deviceIndex);
                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "手动应答"+_device.DeviceName, "", "");
                    return;
                }
                  if(_device.Dbw1Address!=-1)
                 {
                   sdo.SendDeviceOrder(2, 0, 0, this._deviceIndex, 0);
                 }
                
            }
            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "手动应答" + _device.DeviceName, "", "");
            
        }

        private void btQuitPallet_Click(object sender, EventArgs e)
        {
            int enddev = 0;
            //生成出库任务
            if ((_device.DeviceIndex == 12074) || (_device.DeviceIndex == 12080) || (_device.DeviceIndex == 12086))
            {
                enddev=_device.DeviceIndex;
            }
            else
            if(_device.DeviceIndex==22054)
            {
                enddev=22052;
            }
            else
                if(_device.DeviceIndex==32074)
            {
             enddev=32072;
            }
            else
                if (_device.DeviceIndex == 32063)
                {
                    enddev = 32082;
                }
            else
                if (_device.DeviceIndex == 12100)
                {
                    enddev = 12103;
                }
                else
            if (_device.DeviceIndex == 12043)
            {
                enddev = 12100;
            }
            DataView dvbc = dbo.ExceSQL("SELECT FID FROM T_Manage_Task WHERE (FSTARTDEVICE=" + _device.DeviceIndex + ") And (FENDDEVICE=" + enddev+ ")").Tables[0].DefaultView;
            if (dvbc.Count > 0)
            {  
                MessageBox.Show("该任务已存在,请处理后重新下达！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (MessageBox.Show("您确认要下达该任务吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                string dtime = DateTime.Now.ToString("u");
                dtime = dtime.Substring(0, dtime.Length - 1);

                int fid = ccf.GetTempManageIdx();
           string  sql = "INSERT INTO T_Manage_Task" +
          "(FID, F_ManageTaskKindIndex,FPALLETBARCODE,FMANAGETASKTYPE,FCONTROLTASKTYPE, FTASKLEVEL, FISRETURN," +
          "FSTARTWAREHOUSE, FSTARTCELL, FSTARTDEVICE, FENDDEVICE, FENDCELL, " +
          "FSTATUS, FBEGTIME, FENDTIME,FIntoStepOK,FREMARK,FLANEWAY,FSTACK,FENDWAREHOUSE,FUseAwayFork)" +
          "VALUES (" + fid + ",2,'000000000000000','0','3','1','1','','-','"
          + _device.DeviceIndex + "','" + enddev + "','-','0','"+dtime+"','-','0','',0,0,'','-')";
            dbo.ExceSQL(sql);          
            }


        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要对设备：" + this._deviceIndex + "进行故障清除吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            int deviceKind = ccf.GetDeviceKindIdx(this._deviceIndex);
            sdo = CommModeCreate.CreateSendDeviceOrder(this._deviceIndex);
            if ((deviceKind == 1) || (deviceKind == 6))
            {
                sdo.SendDeviceOrder(4, 0, 0, this._deviceIndex, 0, 0, 0, 0, 0, 0);
            }
            else
            {
                if (_device.Dbw1Address != -1)
                {
                    sdo.SendDeviceOrder(4, 0, 0, this._deviceIndex, 0);
                }
            }
            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "进行故障清除" + _device.DeviceName, "", "");
        }

        
    }
}