using DataLinkMesWork1;
using MesServerFunctions;
using MesServerWork;
using MisDataFunDll;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MisDataSaveDate
{
    public partial class FuntionMesRead
    {

        #region 2023.05.14,新增报警

        public static Hashtable Base_TagIdList = new Hashtable();
        public static Hashtable Base_ObjList = new Hashtable();


        public static void GetAlarmInit()
        {
            Base_TagIdList.Clear();
            GetTagIdList("", out DataTable dt);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tagid = dt.Rows[i]["TagID"].ToString();

                if (tagid[0].ToString() == "9")
                {
                    var opName = dt.Rows[i]["工位号"].ToString();
                    var ItemName = dt.Rows[i]["测量项目"].ToString(); // 报警内容
                    var ShaftID = dt.Rows[i]["测量位置"].ToString(); // 报警类型

                    string SendMessage = "MES|PlcAlarm|" + opName + "|" + tagid + "&@TagValue&" + ItemName + "&" + ShaftID;
                    Base_TagIdList.Add(tagid, SendMessage);

                    //在存一份报警对象到键值对中
                    Base_ObjList.Add(tagid, dt.Rows[i]);
                }
            }
        }

        public static void Send_AlarmMsg(string tagid, string tagVvalue)
        {
            var val = Base_TagIdList[tagid];
            if (val != null)
            {
                //var msg = Base_TagIdList[tagid].ToString();
                //var sendmsg = msg.Replace("@TagValue", tagVvalue);
                //SendMessageFun.AsyncSendMessage(sendmsg);
                string alarmTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var msg = Base_TagIdList[tagid].ToString();
                var sendmsg = msg.Replace("@TagValue", tagVvalue) + "&" + alarmTime;
                SendMessageFun.AsyncSendMessage(sendmsg);
                // 去存一份记录到数据库
                DataRow errObj = (DataRow)Base_ObjList[tagid];
                MisDataFun.Alarm_Insert2(Convert.ToInt32(errObj["TagID"]), errObj["工位号"].ToString(), errObj["测量项目"].ToString(), Convert.ToInt32(tagVvalue), errObj["测量位置"].ToString(), alarmTime);
            }
        }

      

        static public void GetTagIdList(string opName, out DataTable dt)
        {
            string procedureName;
            procedureName = "MES_基本变量_原始数据_根据工位号查询";
            SqlParameter[] thisParms = new SqlParameter[1];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName);
            DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt);
        }





        #endregion

        public static void Alarm_Insert_Init(string Opname)
        {
            DataTable dt;
            MisDataFun.Alarm_Moby_Search(out dt);
            if (dt == null) return;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string TagId = dt.Rows[i]["TagId"].ToString();
                object tagValueStr = "";
                string tagValue = "0";
                MIS_BASE.Read_TagValueByTagID(TagId, out tagValueStr);
                if (tagValueStr != null)
                {
                    switch (tagValueStr.ToString().ToLower())
                    {
                        case "1":
                        case "true":
                            tagValue = "1";
                            break;
                        default:
                            tagValue = "0";
                            break;
                    }
                    Send_AlarmMsg(TagId, tagValue);
                }
            }
        }

        public static void Alarm_InitAlarm_Send(string opName, out Hashtable ht)
        {
            var tagValues = MIS_BASE.ReadPLC_OpName(opName); 
            //过滤出来质量数据 //获得带合格标志的质量数据
            var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value);
            ht = new Hashtable();

            foreach (KeyValuePair<string, DeviceDriver_BasicData.CustomeEvetnArgs> _cd in keyValues)
            {
                var tf = _cd.Value;
                string TagID = tf.TagID.ToString();
                if (TagID[0].ToString() == "9")
                {
                    string tagValue = tf.TagValue.ToString();
                    if (tf.TagValue == null) return;
                    switch (tagValue.ToLower())
                    {
                        case "1":
                        case "true":
                            tagValue = "1";
                            break;
                        default:
                            tagValue = "0";
                            break;
                    }
                    if (tagValue == "1")
                    {
                        ht.Add(tf.TagID, tagValue);
                    }
                }
            }
        }
        public static bool Alarm_Insert(string TagID, string tagTypeID, string opName, int TagValue,
             DateTime alarmStartTime, DateTime alarmEndTime, int TimeDiff,
             string Text1, string Text2, string TagOrderBy)
        {


            string produceName = "测量数据工位报警全部_增加数据";
            SqlParameter[] thisParms = new SqlParameter[10];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@TagID", TagID);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagTypeID", tagTypeID);
            thisParms[2] = new System.Data.SqlClient.SqlParameter("@opName", opName);
            thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue);
            thisParms[4] = new System.Data.SqlClient.SqlParameter("@alarmStartTime", alarmStartTime);
            thisParms[5] = new System.Data.SqlClient.SqlParameter("@alarmEndTime", alarmEndTime);
            thisParms[6] = new System.Data.SqlClient.SqlParameter("@TimeDiff", TimeDiff);
            thisParms[7] = new System.Data.SqlClient.SqlParameter("@Text1", Text1);
            thisParms[8] = new System.Data.SqlClient.SqlParameter("@Text2", Text2);
            thisParms[9] = new System.Data.SqlClient.SqlParameter("@TagOrderBy", TagOrderBy);
            if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms))
            {

                return true;
            }
            return false;
        }

        /// <summary>
        /// 报错详细工件记录日志 （有可能报错 所以封装）
        /// </summary>
        /// <param name="errorStep">1.申请上线 2.传递机型 3.允许保存 4.扫码</param>
        /// <param name="e"></param>
        public static void Alarm_SaveFileLog4Error(string errorStep, object e, string FunName, Exception err)
        {
            try
            {
                MyLog4Net.MyLogHelper.Error($"{FunName}异常：", $"Message:{err.Message}    InnerException: {err.InnerException}");
                string leftErrorStep;
                if (errorStep == "PartLoad")
                {
                    leftErrorStep = "申请上线";
                }
                else if (errorStep == "EngineGetOver")
                {
                    leftErrorStep = "传递机型";
                }
                else if (errorStep == "MesRead")
                {
                    leftErrorStep = "允许保存";
                }
                else if (errorStep == "Barcode")
                {
                    leftErrorStep = "扫码";
                }
                else
                {
                    leftErrorStep = $"未知类型{errorStep}";
                }

                DeviceDriver_BasicData.CustomeEvetnArgs msgEvent = (DeviceDriver_BasicData.CustomeEvetnArgs)e;
                string OpName = Convert.ToString(msgEvent.OpName);
                MIS_BASE.GetEngineTypeFromPLC(OpName, out int EngineTypeID, out string EngineType, out string EngineID, out int PartPallet_Code, out string OrderForm);
                MyLog4Net.MyLogHelper.Error($"{FunName}{leftErrorStep}操作异常：", $"工位号：{OpName}、总成号：{EngineID}、机型：{EngineType}、机型代码：{EngineTypeID}、订单号：{OrderForm}、托盘号：{PartPallet_Code}");

                string saveString = $"{FunName}{leftErrorStep}操作异常  Message:{err.Message}    InnerException: {err.InnerException}：工位号：{OpName}、总成号：{EngineID}、机型：{EngineType}、机型代码：{EngineTypeID}、订单号：{OrderForm}、托盘号：{PartPallet_Code}";
                MisDataFun.LogRecording_OP(OpName, "ERROR", "Manage", saveString);
                var sql =
                    $"INSERT INTO 合力_系统日志 ([工位号],[日志类型],[日志文本])"+ 
                    $"  VALUES('{OpName}', 'system', '{saveString}')";
                DataAccess.ExecuteDataTable(sql, out DataTable dt);
            }
            catch (Exception ex)
            {
                MyLog4Net.MyLogHelper.Error($"{FunName}保存错误日志失败：", $"Message:{ex}");
            }
        }

        public static void Alarm_SystemError(string FunName, Exception err)
        {
            MyLog4Net.MyLogHelper.Error($"系统{FunName}方法异常：", $"Message:{err.Message}   InnerException:{err.InnerException}");
        }
    }
}
