//using BasicData;

using DoWhatPlc;
using MesServerWork;
using MisDataFunction;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
//using SystemFramework;

namespace MisDataSaveDateSim
{
    public partial  class MisData:Form
    {
        public void InitFormBtnColor()
        {
            try
            {
                if (!Cbx_StatusDisplay.Checked) return;
                string OpName = WorkStationNum_Now;
                foreach (Control GroupBox in this.groupBox_SignialSimulatorOld.Controls)
                {
                    foreach (Control Btn in GroupBox.Controls)
                    {
                        if (Btn.Name.Length < 8) continue;
                        if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_")
                        {
                            ControlData Ctrl1 = new ControlData(Btn, OpName);
                            Thread t=new Thread(new ParameterizedThreadStart(InitFormBtn_Thread));
                            t.Start(Ctrl1);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }
            

        }

        static object test;
        static void InitFormBtn_Thread(Object  obj)
        {
            try
            {
                ControlData Btn = (ControlData)obj;

                test = DtWebApi.ReadWritePLC.ReadPLC(Btn.TagType.ToString(), Btn.opName);

                bool Result = Convert.ToBoolean(test);
                if (Btn.btn.InvokeRequired)
                {
                    Action<System.Drawing.Color> actionDelegate = (x) => { Btn.btn.BackColor = x; };
                    if (Result)
                    {
                        Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green);
                    }
                    else
                    {
                        Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray);
                    }
                }
                else
                {
                    if (Result)
                    {
                        Btn.btn.BackColor = System.Drawing.Color.Green;
                    }
                    else
                    {
                        Btn.btn.BackColor = System.Drawing.Color.SlateGray;
                    }
                }
            }
            catch (Exception err)
            {
                ControlData Btn = (ControlData)obj;
                //ApplicationLog.WriteLog(err, err.Message+"采集数据值："+ "；按钮名称："+test+ Btn.btn .Name +"工位号"+ WorkStationNum_Now);
            }
        }






        /// <summary>
        /// 通过点击界面按钮写入Bool信号
        /// </summary>
        /// <param name="tagType"></param>
        /// <param name="opName"></param>
        private void WriteBoolSignalByFormBtn(Object Sender)
        {
            try
            {
                string BtnName = ((System.Windows.Forms.Control)Sender).Name;
                string[] Array_BtnNameSplit = BtnName.Split('_');
                int tagType = Convert.ToInt32(Array_BtnNameSplit[2]);
                string OpName = WorkStationNum_Now;

                QualityDataQueryStruct QualityQueryStruct = new QualityDataQueryStruct(OpName, tagType);
                Thread t = new Thread(new ParameterizedThreadStart(WriteBoolSignal_Thread));
                t.Start(QualityQueryStruct);

            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }
        }

        void WriteBoolSignal_Thread(object obj)
        {
            try
            {
                QualityDataQueryStruct QDQ = (QualityDataQueryStruct)obj;
                if (IsDemoMesServer==1)
                {
                    string tagValueStr = "";
                    MIS_BASE.Read_TagTypeID(QDQ.tagType, QDQ.OpName, out tagValueStr);

                    if (tagValueStr=="1")
                    {
                        tagValueStr = "True";
                    }
                    else if (tagValueStr == "0")
                    {
                        tagValueStr = "False";
                    }
                    
                    bool ReadResult = Convert.ToBoolean(tagValueStr);
                    if (ReadResult)
                    {
                        MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, false);
                    }
                    else
                    {
                        MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, true);
                    }
                }
                else
                {
                    bool ReadResult = Convert.ToBoolean(DtWebApi.ReadWritePLC.ReadPLC(QDQ.tagType.ToString(), QDQ.OpName));
                    if (ReadResult)
                    {
                        DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, false);
                    }
                    else
                    {
                        DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, true);
                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }

        }



        /// <summary>
        /// 写入机型
        /// </summary>
        /// <param name="Sender"></param>
        private void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(object Sender)
        {
            try
            {
                string BtnName = ((System.Windows.Forms.Control)Sender).Name;
                string OpName = WorkStationNum_Now;
                if (BtnName == "Btn_Write_PLC")
                {
                    foreach (Control Tbx in this.groupBox_PLC.Controls)
                    {
                        if (Tbx.Name.Length < 12) continue;
                        if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") continue;

                        string[] TbxName_Split = Tbx.Name.Split('_');
                        int TagType = Convert.ToInt32(TbxName_Split[2]);

                        HashtableList htList = DtWebApi.OpcDemo.GetHashtableList();
                        int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]);

                        string tagValue = Tbx.Text.Trim();
                        short tagValue_int;
                        string tagValue_str;
                        byte tagValue_byte;
                        bool tagValue_bool;

                        switch (tagDataType)
                        {
                            case 2:
                                if (!Regex.IsMatch(tagValue, @"^[-]?\d*$"))
                                {
                                    MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数！");
                                    return;
                                }
                                if (tagValue == "") return;
                                tagValue_int = Convert.ToInt16(tagValue);
                                WriteAnyData_Thread(TagType, OpName, tagValue_int);
                                break;
                            case 8:
                                tagValue_str = tagValue.ToString();
                                WriteAnyData_Thread(TagType, OpName, tagValue_str);
                                break;
                            case 17:
                                if (!Regex.IsMatch(tagValue, @"^[-]?\d*$"))
                                {
                                    MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数！");
                                    return;
                                }
                                if (Convert.ToInt32(tagValue) > 255)
                                {
                                    MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内");
                                    return;
                                }
                                if (tagValue == "") return;
                                tagValue_byte = Convert.ToByte(tagValue);
                                WriteAnyData_Thread(TagType, OpName, tagValue_byte);
                                break;
                            case 11:
                                tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue));
                                WriteAnyData_Thread(TagType, OpName, tagValue_bool);
                                break;
                            default:
                                tagValue_str = tagValue.ToString();
                                WriteAnyData_Thread(TagType, OpName, tagValue_str);
                                break;
                        }
                    }
                }
                else if (BtnName == "Btn_Write_MES")
                {
                    foreach (Control Tbx in this.groupBox_MES.Controls)
                    {
                        if (Tbx.Name.Length < 12) continue;
                        if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") continue;

                        string[] TbxName_Split = Tbx.Name.Split('_');
                        int TagType = Convert.ToInt32(TbxName_Split[2]);
                        HashtableList htList = DtWebApi.OpcDemo.GetHashtableList();
                        int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]);
                        //int tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[TagType.ToString()]);

                        string tagValue = Tbx.Text.Trim();
                        short tagValue_int;
                        string tagValue_str;
                        byte tagValue_byte;
                        bool tagValue_bool;

                        switch (tagDataType)
                        {
                            case 2:
                                if (!Regex.IsMatch(tagValue, @"^[-]?\d*$"))
                                {
                                    MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数！");
                                    return;
                                }
                                tagValue_int = Convert.ToInt16(tagValue);
                                WriteAnyData_Thread(TagType, OpName, tagValue_int);
                                break;
                            case 8:
                                tagValue_str = tagValue.ToString();
                                WriteAnyData_Thread(TagType, OpName, tagValue_str);
                                break;
                            case 17:
                                if (!Regex.IsMatch(tagValue, @"^[-]?\d*$"))
                                {
                                    MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数！");
                                    return;
                                }
                                if (Convert.ToInt32(tagValue) > 255)
                                {
                                    MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内");
                                    return;
                                }
                                tagValue_byte = Convert.ToByte(tagValue);
                                WriteAnyData_Thread(TagType, OpName, tagValue_byte);
                                break;
                            case 11:
                                tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue));
                                WriteAnyData_Thread(TagType, OpName, tagValue_bool);
                                break;
                            default:
                                tagValue_str = tagValue.ToString();
                                WriteAnyData_Thread(TagType, OpName, tagValue_str);
                                break;
                        }
                    }
                }

            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);
            }
        }


        void WriteAnyData_Thread(int tagType, string opName, object tagValue)
        {
            try
            { 
                QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, tagValue);

                Thread t = new Thread(new ParameterizedThreadStart(WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread));
                t.Start(QualityStruct);
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);
            }
        }

        void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread(object obj)
        {
            try
            { 
                QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;

                MIS_BASE.WritePLC(QualityStruct.tagType, QualityStruct. OpName, QualityStruct.tagValue);
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);
            }
        }



        /// <summary>
        /// 根据工位号查询质量数据,返回质量数据列表
        /// </summary>
        /// <param name="opName"></param>
        /// <returns></returns>
        QualityDataType[] ReadPLC_ValueListForQualityDataTypeArray(string opName)
        {
            try
            {
                int i1 = 0;
                Hashtable valueList;
                valueList = Function.ReadPLC_Sync_DataList_MesRead(opName);
                if (valueList != null)
                {
                    QualityDataType[] QualityValue = new QualityDataType[valueList.Count];
                    foreach (DictionaryEntry de in valueList)
                    {
                        try
                        {
                            QualityValue[i1] = (QualityDataType)de.Value;
                            i1++;
                        }
                        catch (Exception err)
                        {
                            //ApplicationLog.WriteLog(err, err.Message);
                        }
                    }
                    //ThisWorkStationData = QualityValue;
                    return QualityValue;
                }
                return null;
            }
            catch (Exception err)
            {
                
                //ApplicationLog.WriteLog(err, err.Message);
                return null;
            }
           

        }


        //public QualityDataType[] ThisWorkStationData
        //{ get; set; }

        //object QueryThisWorkStationDataByTagTypeFromThisWorkStationDataProperty(int TagType)
        //{
            //try
            //{ 
            //    foreach (QualityDataType Data in ThisWorkStationData)
            //    {
            //        if (Data.tagValueType  == TagType)
            //        {
            //            return Data.tagValue;

            //        }

            //    }
            //    return null;
            //}
            //catch (Exception err)
            //{
            //    ApplicationLog.WriteLog(err, err.Message);
            //    return null;
            //}
            
        //}

        void RefreshBtnColor(object obj)
        {
            try
            {
                ControlChangeByTagType ControlValue = (ControlChangeByTagType)obj;

                if (!Cbx_StatusDisplay.Checked) return;
                string OpName = WorkStationNum_Now;

                foreach (Control GroupBox in this.groupBox_SignialSimulatorOld.Controls)
                {
                    foreach (Control Btn in GroupBox.Controls)
                    {
                        if (Btn.Name.Length < 8) continue;
                        if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_")
                        {
                            string BtnName = Btn.Name;
                            string[] BtnName_SplitArray = BtnName.Split('_');
                            if (Btn.InvokeRequired)
                            {
                                Action<System.Drawing.Color> ActionDelegate = (x) => { Btn.BackColor = x; };
                                if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType)
                                {
                                    if (ControlValue.Value == "1")
                                    {
                                        Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.Green);

                                    }
                                    else
                                    {
                                        Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray);
                                    }
                                }


                            }
                            else
                            {
                                if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType)
                                {
                                    if (ControlValue.Value == "1")
                                    {
                                        Btn.BackColor = System.Drawing.Color.Green;
                                    }
                                    else
                                    {

                                        Btn.BackColor = System.Drawing.Color.LightGray;
                                    }
                                }
                            }
                        }

                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }

        }
        void RefreshBtnColor_Thread(int TagType, string Value)
        {
            ControlChangeByTagType ControlValue = new ControlChangeByTagType(TagType, Value);
            Thread t = new Thread(new ParameterizedThreadStart(RefreshBtnColor));
            t.Start(ControlValue);
        }


        /// <summary>
        /// 按钮颜色还原
        /// </summary>
        void RefreshBtnColorWriteNull()
        {
            try
            {
                string OpName = WorkStationNum_Now;

                foreach (Control GroupBox in this.groupBox_SignialSimulatorOld.Controls)
                {
                    foreach (Control Btn in GroupBox.Controls)
                    {
                        if (Btn.Name.Length < 8) continue;
                        if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_")
                        {
                            if (Btn.InvokeRequired)
                            {
                                Action<System.Drawing.Color> ActionDelegate = (x) => { Btn.BackColor = x; };
                                Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray);
                            }
                            else
                            {
                                Btn.BackColor = System.Drawing.Color.LightGray;
                            }
                                
                        }
                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }

        }

    }
}
