using RGD.DataService;
using RGD.DBUtility;
using RGD.OPCClient;
using System;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace RGD.WCS
{
    public partial class FrmControlMonitor : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        private FrmDeviceStatus _deviceStatus = new FrmDeviceStatus();

        #region 方法

        public void FlashPanit(string obj, string text, bool append)
        {
            if (append == true)
            {
                this.Controls[obj].Text += text;
            }
            else
            {
                this.Controls[obj].Text = text;
            }
        }

        public string GetObjectText(string obj)
        {
            //return "";
            return this.Controls[obj].Text;
        }

        public void MonitorRefresh(object dataSource)
        {
            FrmTaskList.FormInstance.MonitorRefresh(dataSource);
        }

        public void ManagerRefresh(object dataSource)
        {
            FrmTaskList.FormInstance.ManagerRefresh(dataSource);
        }

        #endregion 方法

        private static FrmControlMonitor _formInstance;

        public static FrmControlMonitor FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmControlMonitor();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }

        public FrmControlMonitor()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void FrmControlMonitor_Load(object sender, EventArgs e)
        {
            //textBox46.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            #region 添加输送机、穿梭车和堆垛机的单击事件

            foreach (Control ctrl in this.plAccessorial1.Controls)
            {
                if (ctrl.GetType().ToString() == "System.Windows.Forms.Button")
                {
                    ctrl.Click += new EventHandler(ctrl_Click);
                    ctrl.MouseEnter += new EventHandler(Btn_MouseEnter);
                }
                if ((ctrl.GetType().ToString() == "System.Windows.Forms.Label") && (ctrl.Tag != null))
                {
                    ctrl.Click += new EventHandler(ctrl_ClickLabel);
                    ctrl.MouseEnter += new EventHandler(Btn_MouseEnter);
                }
            }

            #endregion 添加输送机、穿梭车和堆垛机的单击事件
        }
        /// <summary>
        /// 添加debug信息 0默认黑色，1，红色
        /// </summary>  
        public void AddDebugMessage(string str, int level = 0)
        {
            Action act = delegate ()
            {
                string strLine = System.DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + "\r\n" + str + "\r\n";
                textBox46.AppendText(strLine);

                textBox46.SelectionStart = textBox46.Text.Length;
                textBox46.ScrollToCaret();
            };
            this.Invoke(act);
        }

        private void ctrl_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            _deviceStatus.DeviceIndex = Convert.ToInt32(btn.Tag);
            _deviceStatus.ShowDialog();
        }

        private void ctrl_ClickLabel(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            _deviceStatus.DeviceIndex = Convert.ToInt32(label.Tag);
            _deviceStatus.ShowDialog();
        }

        private void Btn_MouseEnter(object sender, EventArgs e)
        {
            toolTip_DeviceIndex.SetToolTip(sender as Control, Convert.ToString((sender as Control).Tag));
        }

        private void tsStatus_TextChanged(object sender, EventArgs e)
        {
            FrmErrorMessage.FormInstance.NewMessage((sender as TextBox).Text);
        }

        #region 时间事件

        private CGetState gs = new CGetState();
        private CControl cc = new CControl();
        private CListenPLCAsk cplc = new CListenPLCAsk();
        private CCommonFunction ccf = new CCommonFunction();
        private Object thisLock = new Object(); //锁定timer的一次执行
        private DataView color;

        /// <summary>
        /// 分类查找设备状态 主要执行设备完成处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerGetState_Tick(object sender, EventArgs e)
        {
            //Thread t = new Thread(new ThreadStart(TGetState));
            //t.Start();
            //-----------------------------------------------
            TGetState();
        }

        private void TGetState()
        {
            DateTime dt = DateTime.Now;
            if (CStaticClass.Order == true)
            {
                //DateTime dt = DateTime.Now;
                gs.GetDeviceState();
                //label82.Text = "nGetState300:" + (DateTime.Now - dt).TotalMilliseconds + "|" + Thread.CurrentThread.ManagedThreadId.ToString();
            }
            label82.Text = "nGetState300:" + (DateTime.Now - dt).TotalMilliseconds + "|" + Thread.CurrentThread.ManagedThreadId.ToString();
        }

        /// <summary>
        /// 发送设备指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerControl_Tick(object sender, EventArgs e)
        {
            //Thread t = new Thread(new ThreadStart(TControl));
            //t.Start();
            //-----------------------------------------------
            TControl();
        }

        private void TControl()
        {
            DateTime dt = DateTime.Now;
            if (CStaticClass.Order == true) // 自动监听plc
            {
                string ss1 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();

                lock (thisLock)
                {
                    cc.StartOrder(); //发送命令
                }

                if (cc.CControlError != "")
                {
                    if (tsStatus.Text.IndexOf(cc.CControlError) < 0)
                    {
                        tsStatus.ForeColor = Color.Red;
                        tsStatus.Text += cc.CControlError;
                    }
                }
                cc.CControlError = "";

                lock (thisLock)
                {
                    cplc.DealwithPLCAsk();//处理主动上报状态的设备 叠盘/扫码/贴标等
                }

                if (cplc.ListenPLCAskError != "")
                {
                    if (tsStatus.Text.IndexOf(cplc.ListenPLCAskError) < 0)
                    {
                        tsStatus.ForeColor = Color.Red;
                        tsStatus.Text += cplc.ListenPLCAskError;
                    }
                }
                cplc.ListenPLCAskError = "";
                if (ccf.DisassembleTaskError != "")
                {
                    if (tsStatus.Text.IndexOf(ccf.DisassembleTaskError) < 0)
                    {
                        tsStatus.ForeColor = Color.Red;
                        tsStatus.Text += ccf.DisassembleTaskError;
                    }
                }
                ccf.DisassembleTaskError = "";
            }

            label63.Text = "Control300:" + (DateTime.Now - dt).TotalMilliseconds + "|" + Thread.CurrentThread.ManagedThreadId.ToString();
        }

        /// <summary>
        /// 拆分调度任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerDisassemble_Tick(object sender, EventArgs e)
        {
            //Thread t = new Thread(new ThreadStart(TDisassemble));
            //t.Start();
            //-----------------------------------------------
            TDisassemble();
        }

        private void TDisassemble()
        {
            DateTime dt = DateTime.Now;
            if ((CStaticClass.Order == true))
            {
                //启动拆分进程MyTaskIntoSteps();
                int nSubCount = 0;
                lock (thisLock)
                {
                    nSubCount = CDisassembleTask.MyTaskIntoSteps();
                }
                //有拆分完的任务直接执行 触发发送命令
                if (nSubCount > 0)
                {
                    object sendert = new object();
                    EventArgs et = new EventArgs();
                    timerControl_Tick(sendert, et);
                }

                if (CDisassembleTask.DisassembleTaskError != "")
                {
                    if (tsStatus.Text.IndexOf(CDisassembleTask.DisassembleTaskError) < 0)
                    {
                        tsStatus.ForeColor = Color.Red;
                        tsStatus.Text += CDisassembleTask.DisassembleTaskError;
                    }
                    CDisassembleTask.DisassembleTaskError = "";
                }
            }
            label79.Text = "Disassemble900:" + (DateTime.Now - dt).TotalMilliseconds + "|" + Thread.CurrentThread.ManagedThreadId.ToString();
        }

        #endregion 时间事件

        #region 界面刷新

        private Panel pp;
        private Button stack1;//堆垛机
        private TextBox twj1;//光电开关
        private Button stack2;//堆垛机
        private TextBox twj2;//光电开关

        /// <summary>
        /// 监控界面更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerFlashMonitor_Tick(object sender, EventArgs e)
        {
            TFlashMonitor();
        }

        private void TFlashMonitor()
        {
            DateTime dt = DateTime.Now;
            Model.MDevice device = null;
            string s = "";
            try
            {
                if (CStaticClass.Order == true)
                {
                    //所有控件容器
                    pp = plAccessorial1;
                    stack1 = bt1_11001;

                    #region 每层楼监视画面

                    foreach (Control ctrl in pp.Controls)
                    {
                        //tag标签不为空
                        if (ctrl.Tag != null && ctrl.Tag.ToString().Trim() != "" && ctrl.Tag.ToString() != "11001")
                        {
                            if (((ctrl.GetType().ToString() == "System.Windows.Forms.Button") || (ctrl.GetType().ToString() == "System.Windows.Forms.PictureBox")) && (ctrl.Enabled == true))
                            {
                                s = ctrl.Name + ctrl.Tag;
                                device = BaseDeviceService.GetDeviceInfo(Convert.ToInt32(ctrl.Tag));
                                if (device == null)
                                {
                                    if (tsStatus.Text.IndexOf("设备索引：" + ctrl.Tag + "在数据库没有记录!") < 0)
                                    {
                                        tsStatus.ForeColor = Color.Red;
                                        this.tsStatus.Text += "设备索引：" + ctrl.Tag + "在数据库没有记录!";
                                    }
                                    continue;
                                }

                                #region 设置设备状态

                                switch (device.RunState)
                                {
                                    //空闲
                                    case 0:
                                        if (device.DeviceKind == 1 || device.DeviceKind == 3 || device.DeviceKind == 4)
                                        {
                                            ctrl.BackColor = Color.DarkOrange;
                                        }
                                        else if (device.DeviceKind != 18)
                                        {
                                            ctrl.BackColor = SystemColors.ScrollBar;
                                        }
                                        break;
                                    //运行
                                    case 1:
                                        ctrl.BackColor = Color.Lime;
                                        break;
                                    //故障
                                    case 2:
                                        ctrl.BackColor = Color.Red;
                                        break;
                                    //离线
                                    case 3:
                                        ctrl.BackColor = Color.LightYellow;
                                        break;
                                    //停用
                                    case 4:
                                        ctrl.BackColor = Color.Maroon;
                                        break;
                                    //动作完成
                                    case 5:
                                        if (device.DeviceKind == 1 || device.DeviceKind == 4)
                                        {
                                            ctrl.BackColor = Color.MediumSlateBlue;//MediumOrchid;
                                        }
                                        else if (device.DeviceKind != 18)
                                        {
                                            ctrl.BackColor = Color.Gray;
                                        }
                                        break;
                                }

                                #region 设置设备管理状态

                                if (ctrl.GetType().ToString() == "System.Windows.Forms.Button")
                                {
                                    color = DbHelperSQL.Query("select f_errorcount from t_base_device where f_deviceindex=" + device.DeviceIndex).Tables[0].DefaultView;
                                    Button b = (Button)ctrl;
                                    if (color[0]["f_errorcount"].ToString() == "2")
                                    {
                                        b.FlatStyle = FlatStyle.Flat;
                                        b.FlatAppearance.BorderSize = 2;
                                        b.FlatAppearance.BorderColor = Color.Red;
                                    }
                                    else
                                    {
                                        b.FlatAppearance.BorderColor = SystemColors.ControlDark;
                                    }
                                }
                                if (device.DeviceIndex == 12002 && device.SplitByte_6 == 1)
                                {
                                    button3.BackColor = Color.Lime;
                                }
                                else
                                {
                                    button3.BackColor = SystemColors.ScrollBar;
                                }

                                #endregion 设置设备管理状态

                                if (device.DeviceKind == 1)
                                {
                                    #region 移动设备坐标更新

                                    //堆垛机,调用获取机器人状态接口
                                    //try
                                    //{
                                    //    robot bot = SendDataToAgv.getRobotStatue(ctrl.Tag.ToString());

                                    //    double TempX = bot.PositionX;
                                    //    double TempY = bot.PositionY;
                                    //    switch ((int)ctrl.Tag)
                                    //    {
                                    //        case 11001:
                                    //            stack1.Location = new Point(pictureBox1.Location.X - stack1.Width + (int)(pictureBox1.Width / 26 * (TempX - 1)), (int)(87));

                                    //            twj1.Location = new Point(stack1.Location.X + 38, stack1.Location.Y + 9);
                                    //            textBox20.Location = new Point(stack1.Location.X + 33, stack1.Location.Y - 7);
                                    //            textBox19.Location = new Point(stack1.Location.X + 33, stack1.Location.Y + 31);
                                    //            break;

                                    //    }
                                    //    switch (bot.State)
                                    //    {
                                    //        case "ROBOT_IDLE": stack1.BackColor = Color.DarkOrange; break;
                                    //        case "ROBOT_RUNNING": stack1.BackColor = Color.Lime; break;
                                    //        case "ROBOT_ABNORMAL": stack1.BackColor = Color.Red; break;

                                    //    }
                                    //}
                                    //catch(Exception e)
                                    //{
                                    //}

                                    #endregion 移动设备坐标更新
                                }

                                #endregion 设置设备状态
                            }
                            else if ((ctrl.GetType().ToString() == "System.Windows.Forms.TextBox") && ctrl.Tag != null && ctrl.Tag != "")
                            {
                                #region 货物探测

                                ctrl.Visible = CStaticClass.GetDevicePhotoelectric(ctrl.Tag.ToString()) == 1 ? true : false;

                                #endregion 货物探测
                            }
                        }
                    }

                    #endregion 每层楼监视画面
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("刷新界面动画时：" + ex.Message) < 0)
                {
                    tsStatus.ForeColor = Color.Red;
                    this.tsStatus.Text += "刷新界面动画时：" + s + "----" + ex.Message;
                }
            }
            finally
            {
                device = null;
            }

            label80.Text = "FlashMonitor500:" + (DateTime.Now - dt).TotalMilliseconds + "|" + Thread.CurrentThread.ManagedThreadId.ToString();
        }

        /// <summary>
        /// 刷新任务与调度任务列表指令列表 独立线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerFlashTask_Tick(object sender, EventArgs e)
        {
            TflashTask();
        }

        private void TflashTask()
        {
            DateTime dt = DateTime.Now;
            try
            {
                if ((CStaticClass.RealRefresh == true) || (CStaticClass.Order == true))
                {
                    bool ifflash = false;
                    if (FrmMain.FormInstance.dockPanel1.ActiveAutoHideContent != null)
                    {
                        if (FrmMain.FormInstance.dockPanel1.ActiveAutoHideContent.ToString().IndexOf("FrmTaskList") < 0)
                        {
                            ifflash = false;
                        }
                        else
                        {
                            ifflash = true;
                        }
                    }
                    else
                    {
                        if (FrmTaskList.FormInstance.DockState == WeifenLuo.WinFormsUI.Docking.DockState.DockBottom)
                        {
                            ifflash = true;
                        }
                        else
                        {
                            ifflash = false;
                        }
                    }
                    //显示设备指令
                    if (ifflash == true)
                    {
                        FormInstance.MonitorRefresh(DbHelperSQL.Query("select * from V_Monitor_Task where " + CStaticClass.Monstatus + " order by 设备指令索引 asc ").Tables[0].DefaultView);
                        //显示调度任务
                        FormInstance.ManagerRefresh(DbHelperSQL.Query("select * from V_Manage_Task where " + CStaticClass.Manstatus).Tables[0].DefaultView);

                        DataView dv_task = DbHelperSQL.Query("select * from t_warehouse").Tables[0].DefaultView;
                        label92.Text = "当前任务：" + dv_task[0]["F_TASK_NO"].ToString();
                        label91.Text = "任务类型：" + dv_task[0]["F_TASK_TYPE"].ToString();
                        label4.Text = "任务状态：" + dv_task[0]["F_TASK_STATUS"].ToString();
                        label3.Text = "设备类型：" + dv_task[0]["F_EQUIP_TYPE"].ToString();
                        label1.Text = "出库原因：" + dv_task[0]["F_IO_WH_SORT_CODE"].ToString();
                        label23.Text = "尾箱标志：" + dv_task[0]["F_LASTBOX_REACH_FLAG"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("获取调度任务时：" + ex.Message) < 0)
                {
                    tsStatus.Text += "获取调度任务时：" + ex.Message;
                }
            }
            finally
            {
                label81.Text = "FlashTask500:" + (DateTime.Now - dt).TotalMilliseconds + "|" + Thread.CurrentThread.ManagedThreadId.ToString();
            }
        }

        #endregion 界面刷新

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked)
            {
                CConfig.StartAll();
                timerControl.Enabled = false;
                timerGetState.Enabled = false;
                timerDisassemble.Enabled = false;
            }
            else
            {
                CConfig.StopAll();
                timerControl.Enabled = true;
                timerGetState.Enabled = true;
                timerDisassemble.Enabled = true;
            }
        }

        public static void clearallstatues()
        {
            DialogResult dr = MessageBox.Show("是否进行初始化？", "警告", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                DbHelperSQL.ExecuteSql("update t_warehouse set f_task_no='',f_task_type='',f_task_status='FREE',f_equip_type='',F_IO_WH_SORT_CODE='',F_LASTBOX_REACH_FLAG=0");
                DbHelperSQL.ExecuteSql("update io_rfid set read_flag=0");
                DbHelperSQL.ExecuteSql("update T_Base_PLC_Ask set F_BarCode =''  where F_askkind=2");
                DbHelperSQL.ExecuteSql("update t_base_device set F_ErrorCount=0,F_LockedState=0,F_HaveGoods=0,F_ManTaskReserve=0,F_RunState=0 where F_ErrorCount!=0 or F_LockedState!=0 or F_HaveGoods!=0 or F_ManTaskReserve!=0 or F_RunState!=0");
                Model.MDevice device = null;

                ISendDeviceOrder sdo = null;
                if (CStaticClass.Order == true)
                {
                    //所有控件容器
                    Panel pp = FrmControlMonitor.FormInstance.plAccessorial1;

                    foreach (Control ctrl in pp.Controls)
                    {
                        if (ctrl.Tag != null && ctrl.Tag.ToString().Trim() != "")
                        {
                            if (((ctrl.GetType().ToString() == "System.Windows.Forms.Button") || (ctrl.GetType().ToString() == "System.Windows.Forms.PictureBox")) && (ctrl.Enabled == true))
                            {
                                device = BaseDeviceService.GetDeviceInfo(Convert.ToInt32(ctrl.Tag));

                                sdo = CommModeCreate.CreateSendDeviceOrder(device.DeviceIndex);

                                switch (device.RunState)
                                {
                                    //空闲
                                    case 0:
                                        break;

                                    default:
                                        sdo.SendDeviceOrder(4, 0, 0, device.DeviceIndex, 0, 0, 0, 0, 0, 0);
                                        sdo.SendDeviceOrder(4, 0, 0, device.DeviceIndex, 0, 0, 0, 0, 0, 0);
                                        break;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            CDisassembleTask.MyTaskIntoSteps();
        }
    }
}