
using HslCommunication.WebSocket;
using Newtonsoft.Json;
using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;
using OpcBasic;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Threading;
using System.Windows.Forms;
using WebApi;
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 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 int WebApi_Port = Convert.ToInt32(AppSettings["WebApi_Port"]);

        /// <summary>
        /// 当前工位号
        /// </summary>
        public static string Curr_Station = AppSettings["Curr_Station"] ?? "";

        /// <summary>
        /// 称重类型：Ground=地面称重, Hanging=空中称重/吊称
        /// </summary>
        public static string WeighingType = AppSettings["WeighingType"] ?? "Hanging";

        /// <summary>
        /// 码块订货号解析顺序：0=订货号在前, 1=流水号在前
        /// </summary>
        public static int CodeBlockOrderNoReverse = int.TryParse(AppSettings["CodeBlockOrderNoReverse"], out var _cbonr) ? _cbonr : 0;

        /// <summary>
        /// 工位1现场工位号，Hanging模式下代表放油前工位
        /// </summary>
        public static string Station1OpName = AppSettings["Station1OpName"] ?? "";

        /// <summary>
        /// 工位2现场工位号，Hanging模式下代表放油后工位
        /// </summary>
        public static string Station2OpName = AppSettings["Station2OpName"] ?? "";

        /// <summary>
        /// 是否启用扫码枪：1=启用, 0=禁用
        /// </summary>
        public static int IsUseBarcode = int.TryParse(AppSettings["IsUseBarcode"], out var _iub) ? _iub : 0;
        /// <summary>
        /// 工位1扫码枪COM口（如COM3），空则不启用
        /// </summary>
        public static string Station1BarCOM = AppSettings["Station1BarCOM"] ?? "";
        /// <summary>
        /// 工位2扫码枪COM口（如COM4），空则不启用
        /// </summary>
        public static string Station2BarCOM = AppSettings["Station2BarCOM"] ?? "";
        /// <summary>
        /// 扫码枪波特率
        /// </summary>
        public static int BarcodeBaudRate = int.TryParse(AppSettings["BarcodeBaudRate"], out var _bbr) ? _bbr : 9600;

        /// <summary>
        /// 设备工位名称列表（如 OP10, OP20），在OnStart中从设备表加载
        /// </summary>
        public static System.Collections.Generic.List<string> StationOpNames = new System.Collections.Generic.List<string>();

        /// <summary>
        /// 工位显示名称映射（opName → "OP10 — 称重位1"），在OnStart中从设备表加载
        /// </summary>
        public static System.Collections.Generic.Dictionary<string, string> StationDisplayNames
            = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// 称重作业页面实例引用，供MIS_Funtion推送交互消息
        /// </summary>
        public static Pages.UC_Weighing WeighingPage;

        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_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);//红色

        public static Color color_Blue_FJ = Color.FromArgb(19, 34, 122);//深蓝
        public static Color color_White_FJ = Color.White;//白色
        public static Color color_Control = SystemColors.Control;//控件默认颜色



        public static bool OnLine_Sql = false;

        public static string Curr_UserName = "";
        public static string Curr_LoginID = "";
        public static string Curr_UserPassWord = "";


        /// <summary>
        /// WebApi
        /// </summary>
        public static InitServer initServer = null;


        /// <summary>
        /// 监控数据的所有变化，从这里产生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OPCTagData_TagDataOnChangeMIS(object sender, DeviceDriver_BasicData.CustomeEvetnArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(MIS_Funtion), e);
        }
        /// <summary>
        /// 定时触发，检测PLC在线状态，周期：3 s
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eState"></param>
        public override void PlcStateEvent(object sender, DeviceDriver_BasicData.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()
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            new System.Threading.Mutex(true, $"MES_PWT_A95", out bool bCanRun);
            if (!bCanRun)
            {
                MessageBox.Show("MES采集系统 已经在运行！不可重复启动！");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Temp.mesWorkForm = new MesWorkForm());
        }
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        private string Hello_You_All_Never_Know(string[] args)
        {
            return Guid.NewGuid().ToString() + Guid.NewGuid().ToString();
        }
     
        /// <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);
            }
        }


        /// <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 CommunicationCheckOnLine()
        {

            new Thread(new ThreadStart(delegate ()
            {
                while (true)
                {
                    try
                    {
                        MesWorkForm.OnLine_Sql = DataLinkMesWork.SQLCommon.ExecuteDataTable("select getdate()", ConnectionString, out DataTable dt, out string err);
                    }
                    catch (Exception) { }
                    Thread.Sleep(5000);
                }
            }))
            { IsBackground = true }.Start();

        }


        private void Loop_SelectAlarmShow()
        {
            while (true)
            {
                try
                {
                    B_DB_Opera.Query_AlarmData(Curr_Station, out int count, out string text);
                    if (count > 0)
                    {
                        label_Alarm.Text = $"({count})    {text}";
                        panel_Alarm.BackColor = Color.Red;
                    }
                    else
                    {
                        label_Alarm.Text = $"";
                        panel_Alarm.BackColor = Color.FromArgb(30, 58, 95);
                    }

                }
                catch (Exception err)
                {
                }
                Thread.Sleep(1000);
            }
        }   
        // Loop_ReadRealPageShow 已移除（旧UI控件引用），PLC信号显示将在 UC_Weighing 中实现

        public void ShowSignal(Control c,string opName)
        {
            if (!c.Name.Contains("_Show_"))
            {
                return;
            }
            var tagTypeCodeID = Convert.ToInt32(c.Name.Split('_')[3]);
            if (c is TextBox)
            {
                try
                {
                    c.Text = PlcLinkForm.ReadPLC(tagTypeCodeID, opName).ToString();
                }
                catch (Exception err)
                {
                    c.Text = "不存在该信号！";
                }
            }
        }


        public void ShowSignal(Control c, int tagTypeCodeID, string opName)
        {
            if (c is Panel)
            {
                try
                {
                    c.BackColor = PlcLinkForm.ReadPLC(tagTypeCodeID, opName).ToString().ToLower().Replace("true", "1").Replace("false", "0") == "1" ? Color.Lime : color_Grey;
                }
                catch (Exception err)
                {
                    c.BackColor = color_Grey;
                }
            }
        }

        public static ConcurrentDictionary<string, TagFormat> ReadPLC_OpName(string opName)
        {
            try
            {
                var res = new ConcurrentDictionary<string, TagFormat>();
                var tagAdrListTagFormat0 = PlcLinkForm.ReadPLC_GroupData_SingleTag(opName);
                foreach (var item in tagAdrListTagFormat0)
                {
                    var key = item.Key;
                    var value = (TagFormat)item.Value;
                    res.TryAdd(key, value);
                }
                return res;
            }
            catch (Exception err)
            {
                return null;

            }

        }

    }
}
