using DataLinkMesWork;
using ExternalDataSync;
using NPOI.POIFS.Properties;
using OpcBasic;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using SystemFramework;
using static System.Configuration.ConfigurationManager;

namespace MesWork
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Temp {
        public static MesWorkForm mesWorkForm = null;
    }
    /// <summary>
    /// 配置信息
    /// </summary>
    public partial class MesWorkForm
    {

        public static int workerThreads = 4000;
        public static int completionPortThreads = 2000;

        public static string NotHandlerSignal = AppSettings["NotHandlerSignal"];
        public static string BasicDataTableFile = AppSettings["BasicDataTableFile"];
        public static int IsDemoMesServer = Convert.ToInt32(AppSettings["IsDemoMesServer"]);
        public static int IsAllowWrite = Convert.ToInt32(AppSettings["IsAllowWrite"]);
        public static int IsWriteMonitorLog = Convert.ToInt32(AppSettings["IsWriteMonitorLog"]);
        public static int IsWriteLog4 = Convert.ToInt32(AppSettings["IsWriteLog4"]);
    
        public static string ConnectionString = AppSettings["ConnectionString"];
       

        public static string LineID_Product = AppSettings["LineID_Product"];
        //所有上线工位的工位名称
        public static string OPCodes_LineSet = AppSettings["OPCodes_LineSet"];

        public static string WebAPI_Url_Boms = AppSettings["WebAPI_Url_Boms"];

        public static string WebAPI_Url_Quality = AppSettings["WebAPI_Url_Quality"]; 
        public static string ProgramPartial = AppSettings["ProgramPartial"]; 

        public static int WebSvrPort = Convert.ToInt32(AppSettings["WebSvrPort"]);


        public static Color color_Faw = Color.FromArgb(0, 44, 101);//蓝色，大众：0,44,101
        public static Color color_Good = Color.FromArgb(132, 185, 235);//浅蓝，自定义
        public static Color color_Wait = Color.FromArgb(240, 230, 140);//淡黄，显示等待状态
        public static Color color_Bad = SystemColors.ActiveBorder;//灰色，显示操作过程
        public static Color color_Control = SystemColors.Control;//控件默认颜色
        public static Color color_Grey = Color.FromArgb(192, 192, 192);//灰色，Table底色

        public static Color color_Green = Color.FromArgb(22, 161, 136);//绿色
        public static Color color_Yellow = Color.FromArgb(246, 227, 74);//黄色
        public static Color color_Red = Color.FromArgb(255, 0, 0);//红色

        /// <summary>
        /// 
        /// </summary>
        public static ConcurrentQueue<OpcData.CustomeEvetnArgs> taskSql = new ConcurrentQueue<OpcData.CustomeEvetnArgs>();
        /// <summary>
        /// 在线状态
        /// </summary>
        public static bool OnLine_Sql = false;
        /// <summary>
        /// PMC列表
        /// </summary>
        public static DataTable dt_pmc_Simplify = null;
        /// <summary>
        /// PLC数据
        /// </summary>
        public static DataTable dt_PLC_Data = null;
        /// <summary>
        /// PMC列表
        /// </summary>
        public static Hashtable ht_PLM_Old = new Hashtable();
        /// <summary>
        /// PMC列表
        /// </summary>
        public static Hashtable ht_PLM_Curr = new Hashtable();
        /// <summary>
        /// ht_OpName_PMCReadTagIDArray
        /// </summary>
        public static Hashtable ht_OpName_PMCReadTagIDArray = new Hashtable();
        /// <summary>
        /// 工位打开记录
        /// </summary>
        public static List<String> list_OpenForm = new List<String>();
        /// <summary>
        /// IP和工位号的对应关系
        /// </summary>
        public static Dictionary<String, List<String>> G_DC_IP_OP = null;
        /// <summary>
        /// 设备的在线状态
        /// </summary>
        public static Hashtable ht_IP_OnLine = new Hashtable();
        /// <summary>
        /// 任务类型信息
        /// </summary>
        public static Hashtable ht_TaskTypeInfo = new Hashtable();
        /// <summary>
        /// 工位的自动信号
        /// </summary>
        public static Hashtable ht_Signal__Station_Auto = new Hashtable();
        /// <summary>
        /// 工位的运行信号
        /// </summary>
        public static Hashtable ht_Signal__Station_Running = new Hashtable();
        /// <summary>
        /// 工位的手动信号
        /// </summary>
        public static Hashtable ht_Signal__Station_Manual = new Hashtable();
        /// <summary>
        /// 工位的报警信号
        /// </summary>
        public static Hashtable ht_Signal__Station_Alarm = new Hashtable();
        /// <summary>
        /// 工位的掉线信号
        /// </summary>
        public static Hashtable ht_Signal__Station_OffLine = new Hashtable();
        /// <summary>
        /// 主界面显示的当前上线型号
        /// </summary>
        public static string RunSort = "6DM-1";


        /// <summary>
        /// 允许移动
        /// </summary>
        public static bool allowDrag = false;
        /// <summary>
        /// 鼠标状态
        /// </summary>
        private static bool isMouseDown = false;
        /// <summary>
        /// 记录鼠标指针的坐标
        /// </summary>
        private static Point mouseOffset;
        /// <summary>
        /// 工位内容
        /// </summary>
        public static Hashtable ht_Station_Content = null;
        /// <summary>
        /// 工位文本描述
        /// </summary>
        public static Hashtable ht_Station_Label = null;

      
        /// <summary>
        /// Agv的DB地址
        /// </summary>
        public static DataTable dt_OPNameInfo = null;


     
        /// <summary>
        /// 监控数据的所有变化，从这里产生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OPCTagData_TagDataOnChangeMIS(object sender, OpcData.CustomeEvetnArgs e)
        {
            //ThreadPool.QueueUserWorkItem(new WaitCallback(MIS_Funtion), e);
            //// 设备状态日志
            //ThreadPool.QueueUserWorkItem(TagTypeCodeID_TagDataOnChange, e);

            MesWorkForm.taskSql.Enqueue(e);
        }


        /// <summary>
        /// 定时触发，检测PLC在线状态，周期：3 s
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eState"></param>
        public override void PlcStateEvent(object sender, OpcData.PlcStateEvetnArgs eState)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(MIS_Device), eState);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="t"></param>
        /// <param name="location"></param>
        /// <param name="content"></param>
        public override void E_WriteLog(Enum_LogType t, string location, string content)
        {
            if (content .Contains("GetTagIDByTagTypeCodeID()，"))
            {
                return;
            }
            WriteLog_Info(t.ToString(), $"<[<{location}>]>{content}");
        }
        /// <summary>
        /// 
        /// </summary>
        [STAThread]
        static void Main()
        {
            new System.Threading.Mutex(true, $"WC_MES_{MesWorkForm.ProgramPartial}1", out bool bCanRun);
            if (!bCanRun)
            {
                MessageBox.Show("MES采集系统 已经在运行！不可重复启动！");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Temp.mesWorkForm = new MesWorkForm());
        }
        /// <summary>
        /// 读写取方法
        /// </summary>
        /// <param name="readWhat"></param>
        /// <param name="opOrIp"></param>
        private void DemoRead(string doWhat, string opOrIp)
        {
            try
            {
                string opName = "OP1010";
                object tagValue = 1;
                bool result = false;
                ConcurrentDictionary<string, object> tagAdrListTagFormat = null;

                switch (doWhat)
                {
                    case "TagID":
                        tagValue = ReadPLC("71010001");
                        result = WritePLC("71010001", tagValue);
                        break;
                    case "TagTypeCodeID":
                        tagValue = ReadPLC(10, opName);
                        result = WritePLC(10, opName, tagValue);
                        break;
                    //case "Cmd":
                    //    tagValue = ReadPLC((int)EnumTagTypeCodeID.EngineID, opName);
                    //    result = WritePLC((int)EnumTagTypeCodeID.EngineID, opName, tagValue);
                    //    break;
                    case "OpAllTag"://OP所有点
                        tagAdrListTagFormat = ReadPLC_GroupData(opOrIp);
                        break;
                    case "OpMonitorTag"://OP监控点
                        tagAdrListTagFormat = ReadPLC_GroupMonitor(opOrIp);
                        break;
                    case "IpAllTag"://IP所有点
                        tagAdrListTagFormat = ReadPLC_IpTag(opOrIp);
                        break;
                    case "IpMonitorTag"://IP监控点
                        tagAdrListTagFormat = ReadPLC_IpMonitorTag(opOrIp);
                        break;
                    case "RegionRead"://按区域读取（起始地址 + 长度）
                        {
                            string tagStartAdr = "DB411.10";
                            ushort tagAdrListMaxLength = 100;
                            GetDbAndMaxLengthByOpName(opOrIp, out tagStartAdr, out tagAdrListMaxLength);
                            tagAdrListTagFormat = ReadQualityDataList(opOrIp, tagStartAdr, tagAdrListMaxLength);
                        }
                        break;
                    case "ReadBytes"://按区域读取（起始地址 + 长度）
                        {
                            string tagStartAdr = "DB411.10";
                            ushort tagAdrListMaxLength = 100;
                            var bates1 = ReadByteData_Op(opOrIp, tagStartAdr, tagAdrListMaxLength);
                            var bates2 = ReadByteData_Ip(opOrIp, tagStartAdr, tagAdrListMaxLength);
                        }
                        break;
                    case "WriteBytes"://按区域读取（起始地址 + 长度）
                        {
                            string tagStartAdr = "DB411.10";
                            var result1 = WritePLC_Bytes_Op(opOrIp, tagStartAdr, new byte[1024]);
                            var result2 = WritePLC_Bytes_Ip(opOrIp, tagStartAdr, new byte[1024]);
                        }
                        break;
                    default:
                        break;
                }
                //ReadByteData_Op(string opName, string startAdrr, ushort length)
                foreach (System.Collections.Generic.KeyValuePair<string, object> de in tagAdrListTagFormat)//得到工位监控点哈希表
                {
                    TagFormat TF = (TagFormat)de.Value;
                    string recResult = TF.OpName + "  (" + TF.TagTypeCodeID + ")" + TF.TagValue.ToString(); ;
                }
            }
            catch (System.Exception err)
            {
                ApplicationLog.WriteLog("listView_ShowQualityData_Init" + err);
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        private string Hello_You_All_Never_Know(string[] args)
        {
            return Guid.NewGuid().ToString();
        }
        /// <summary>
        /// 测试按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click(object sender, System.EventArgs e)
        {
            var tagTypeCodeIDList = DriverCache[CacheType.Cache_OpTagTypeCodeIDList];
        }
        /// <summary>
        /// 定义列
        /// </summary>
        /// <param name="dt_pmc"></param>
        private void DatatableCol_Simplify(DataTable dt_pmc) 
        {
            dt_pmc_Simplify = new DataTable();
            dt_pmc_Simplify.Columns.Add("TagID");
            dt_pmc_Simplify.Columns.Add("TagName");
            dt_pmc_Simplify.Columns.Add("TagValue");
            dt_pmc_Simplify.Columns.Add("工位号");
            dt_pmc_Simplify.Columns.Add("数据来源");
            dt_pmc_Simplify.Columns.Add("IP");
            dt_pmc_Simplify.Columns.Add("TagTypeID");
            dt_pmc_Simplify.Columns.Add("TagLong");
            dt_pmc_Simplify.Columns.Add("DbName");
            dt_pmc_Simplify.Columns.Add("变量类型");
            dt_pmc_Simplify.Columns.Add("变量地址");
            dt_pmc_Simplify.Columns.Add("变量其它");
            dt_pmc_Simplify.Columns.Add("列位置");
            dt_pmc_Simplify.Columns.Add("变量类型代码");
            dt_pmc_Simplify.Columns.Add("变量类型名称");
            dt_pmc_Simplify.Columns.Add("是否启用");
            dt_pmc_Simplify.Columns.Add("是否监控");

            var dt_pmcT = dt_pmc.Copy();
           
            for (int i = 0; i < dt_pmcT.Rows.Count; i++)
            {
                var TagID = dt_pmcT.Rows[i]["TagID"].ToString();
                var TagName = dt_pmcT.Rows[i]["TagName"].ToString();
                var TagValue = "0";
                var 工位号 = dt_pmcT.Rows[i]["工位号"].ToString();
                var 数据来源 = dt_pmcT.Rows[i]["数据来源"].ToString();
                var IP = dt_pmcT.Rows[i]["IP"].ToString();
                var TagTypeID = dt_pmcT.Rows[i]["TagTypeID"].ToString();
                var TagLong = dt_pmcT.Rows[i]["TagLong"].ToString();
                var DbName = dt_pmcT.Rows[i]["DbName"].ToString();
                var 变量类型 = dt_pmcT.Rows[i]["变量类型"].ToString();
                var 变量地址 = dt_pmcT.Rows[i]["变量地址"].ToString();
                var 变量其它 = dt_pmcT.Rows[i]["变量其它"].ToString();
                var 列位置 = dt_pmcT.Rows[i]["列位置"].ToString();
                var 变量类型代码 = dt_pmcT.Rows[i]["变量类型代码"].ToString();
                var 变量类型名称 = dt_pmcT.Rows[i]["变量类型名称"].ToString();
                var 是否启用 = dt_pmcT.Rows[i]["是否启用"].ToString();
                var 是否监控 = dt_pmcT.Rows[i]["是否监控"].ToString();

                ht_PLM_Old.Add(TagID, "-101");

                dt_pmc_Simplify.Rows.Add(
                    TagID,
                    TagName,
                    TagValue,
                    工位号 ,
                    数据来源 ,
                    IP ,
                    TagTypeID ,
                    TagLong ,
                    DbName ,
                    变量类型,
                    变量地址 ,
                    变量其它 ,
                    列位置,
                    变量类型代码,
                    变量类型名称,
                    是否启用,
                    是否监控
                    );
            }
        }
        /// <summary>
        /// 添加到窗体
        /// </summary>
        /// <param name="stationName"></param>
        /// <param name="c"></param>
        private void SetMember(string stationName, Control c)
        {
            panel_Lyout.Controls.Add(c);
            if (c is Panel)
            {
                ht_Station_Content.Add(stationName, c);
            }
            if (c is Label)
            {
                ht_Station_Label.Add(stationName, c);
            }
        }
        /// <summary>
        /// 写入信号
        /// </summary>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="ststionName"></param>
        /// <param name="value"></param>
        public static void WritePLC_IF(int tagTypeCodeID,string ststionName,object value)
        {
            if (IsAllowWrite == 1)
            {
                WritePLC(tagTypeCodeID, ststionName, value);
            }
        }


        public static string CVT_ReadValue(object value)
        {
            var result = "";
            
            if (value == null)
            {
                return result;
            }
            if (value.ToString ().ToLower () == "true" | value.ToString().ToLower() == "1")
            {
                result = "1";
            }
            if (value.ToString().ToLower() == "false" | value.ToString().ToLower() == "0")
            {
                result = "0";
            }

            return result;
        }



        /// <summary>
        /// 写日志
        /// 2023.10.30.llx
        /// </summary>
        public static void WriteLog_Info(string type, string msg, Exception ex = null)
        {
            if (IsWriteLog4 == 1)
            {
                MW_Log.LoggerHelper.Info(type, msg, ex);
            }
        }

        private void Loop()
        {
            while (true)
            {
                taskSql.TryDequeue(out OpcData.CustomeEvetnArgs e);
                if (e != null)
                {
                    MIS_Funtion(e);
                    TagTypeCodeID_TagDataOnChange(e);
                }
                if (taskSql.Count < 3)
                {
                    Thread.Sleep(15);
                }
            }
        }

        public void UseMisFuntion(Object e)
        {
            MIS_Funtion(e);
        }
    }
} 
