using BasicData;

using MesWork;
using Newtonsoft.Json;
using OpcBasic;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MesServerWork
{

    /*
HeartBeatMIS                          15
EngineTypeGetOverMES                          5
PartPalletGoOver                          6
MaterialVerifyOver                          7
FalseGo                          8
ConfirmOkGo                          51
PartLoadFinish                          52
UnloadCompleted                          53
MachineTime_ReadOver                          54
FixAllow                          66
FixOver                          67
MatchingCompleted                          68
Match                          69
Reserved_1                          70
IsAutoGetEngineID                          71
RepairUplineMES                          72
ProcessCode                          77
BoltCode                          88
RepairStatus                          93
Reserved_3                          24
Reserved_4                          25
Reserved_5                          26
Reserved_6                          27
Reserved_7                          28
Reserved_8                          29
Reserved_9                          30
Reserved_10                          31
Reserved_11                          32
Reserved_12                          33
Reserved_13                          34
Reserved_14                          35
MesReadOver                          20
Reserved_15                          110
Reserved_16                          111
Reserved_17                          112
OnLineState                          79
EngineTypeID_MES                          73
EngineID_MES                          74
EngineType_MES                          75
MarkID                          42
RepairPathString                          4
SPareint1                          113
SPareint2                          114
SPareint3                          115
Sparestring1                          116
Sparestring2                          117
HeartBeatPLC                          14
WorkStart                          2
RepairPartStatusPLC                          3
PartLoad                          43
EngineTypeGetOverPLC                          44
PartLoadOK                          48
Reserved_18                          49
PalletDown                          50
Reserved_19                          58
FixOK                          59
Reserved_20                          76
Reserved_21                          61
Reserved_22                          62
Reserved_23                          63
Reserved_24                          64
Reserved_25                          65
EngineTypeID                          9
EngineID                          10
EngineType                          11
PartPalletCode                          80
PalletInfo                          22
MesRead                          19
PutOn                          1000
WorkOn                          1001
Alarm                          1002
NoPart                          1003
Block                          1004
PartPalletStatus                          13
TargetTimeRead                          16
QualityMask                          21
RepairStatusPLC                          23
MachineTargetTime                          17
MachineActualTime                          18
PLCSPareint1                          36
PLCSPareint2                          37
PLCSPareint3                          38
PLCSarestring1                          39
PLCSarestring2                          40
 */



    public partial class MIS_BASE
    {


        /// <summary>
        ///引用程序集Hashtable
        /// </summary>
        public static Hashtable Hashtable_assembly = new Hashtable();
        /// <summary>
        /// 
        /// </summary>
        static public NameValueCollection hashtable_TagTypeTagName = null;

        /// <summary>
        /// 
        /// </summary>
        static public NameValueCollection hashtable_TagTypeChange = null;
        /// <summary>
        /// 
        /// </summary>                                                                
        static public NameValueCollection hashtable_WebTagTypeChange = null;
        /// <summary>
        /// 
        /// </summary>
        static public NameValueCollection hashtable_MesTagTypeChange = null;
        /// <summary>
        /// 
        /// </summary>
        static readonly object l = new object();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="opName"></param>
        /// <returns></returns>
        public static object ReadPLC(int tagTypeCodeID, string opName)
        {
            try
            {
                return PlcLinkForm.ReadPLC(tagTypeCodeID, opName);

            }
            catch { return "-3"; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagID"></param>
        /// <param name="tagValue"></param>
        public static object ReadPLC(string tagID)
        {
            return PlcLinkForm.ReadPLC(tagID);
        }
        /// <summary>
        /// 20230218
        /// 按组读质量数据，返回带合格标志的质量数据列表
        /// </summary>
        /// <param name="opName"></param>
        /// <returns></returns>
        public static Hashtable ReadPLC_Sync_DataList_MesRead_ByOnlyDataGroup(string opName)
        {
            lock (l)
            {

                var tagValues = GetDbAndMaxLengthByOpNameByBytes(opName);

                var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value);

                TagFormat tagFormatTemp;
                int tagIndex = 1;
                int isOK = 0;

                Hashtable ht = new Hashtable();


                foreach (KeyValuePair<string, object> _cd in keyValues)
                {
                    if (_cd.Key.ToString()[0].ToString() == "7")
                    {
                        tagFormatTemp = (TagFormat)_cd.Value;
                        if (tagIndex % 3 == 1)
                        {
                            isOK = Convert.ToInt32(tagFormatTemp.TagValue);
                        }
                        else if (tagIndex % 3 == 2)
                        {
                            var TF = (TagFormat)_cd.Value;

                            QualityDataType qualityDataType;
                            qualityDataType = GetQualityDataType(TF);
                            qualityDataType.isGoodBad = isOK;
                            ht.Add(qualityDataType.tagID, qualityDataType);
                        }
                        else if (tagIndex % 3 == 0)
                        {
                            var TF = (TagFormat)_cd.Value;

                            QualityDataType qualityDataType;
                            qualityDataType = GetQualityDataType(TF);
                            qualityDataType.isGoodBad = isOK;
                            ht.Add(qualityDataType.tagID, qualityDataType);
                        }

                        tagIndex++;
                    }
                    //Console.WriteLine($"key：{kv.Key} value：{kv.Value}");
                }
                return ht;
            }
        }

        public static ConcurrentDictionary<string, object> GetDbAndMaxLengthByOpNameByBytes(string opName)
        {
            string tagStartAdr = "";
            ushort tagAdrListMaxLength = 0;
            PlcLinkForm.GetDbAndMaxLengthByOpName(opName, out tagStartAdr, out tagAdrListMaxLength);
            var tagAdrListTagFormat = PlcLinkForm.ReadQualityDataList(opName, tagStartAdr, tagAdrListMaxLength);
            return tagAdrListTagFormat;
        }


        public static BasicData.QualityDataType GetQualityDataType(TagFormat TF)
        {
            QualityDataType qualityDataType;

            qualityDataType = new QualityDataType();

            qualityDataType.tagID = TF.TagID;
            qualityDataType.tagTypeID = TF.TagTypeID;//变量类型
            qualityDataType.opName = TF.OpName;
            int.TryParse(TF.TagQuality, out int TagQuality);
            qualityDataType.tagQuality = TagQuality;
            qualityDataType.tagValueType = TF.TagTypeCodeID;
            int.TryParse(TF.TagOrderBy, out int TagOrderBy);
            qualityDataType.tagOrderBy = TagOrderBy;
            int.TryParse(TF.TagItemOrderBy, out int TagItemOrderBy);
            qualityDataType.tagItemOrderBy = TagItemOrderBy;
            qualityDataType.tagProperty = TF.TagProperty;//变量特点
            qualityDataType.tagValue = TF.TagValue;//变量值

            return qualityDataType;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="opName"></param>
        /// <param name="tagValue"></param>
        public static void ReadTagValue(int tagTypeCodeID, string opName, out string tagValue)
        {
            tagValue = "0";
            try
            {
                var tagValueObj = PlcLinkForm.ReadPLC(tagTypeCodeID, opName);
                var type = tagValueObj.GetType().Name.ToLower();
                if (type == "bool" | type == "boolean")
                {
                    var val = tagValueObj.ToString().ToLower();

                    if (val == "true")
                    {
                        tagValue = "1";
                    }
                }
                else
                {
                    tagValue = tagValueObj.ToString();
                }
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagID"></param>
        /// <param name="tagValue"></param>
        /// <returns></returns>
        public static bool WritePLC(string tagID, object tagValue)
        {
            return PlcLinkForm.WritePLC(tagID, tagValue);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="opName"></param>
        /// <param name="tagValue"></param>
        /// <returns></returns>
        public static bool WritePLC(int tagTypeCodeID, string opName, object tagValue)
        {
            return PlcLinkForm.WritePLC(tagTypeCodeID, opName, tagValue);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="opName"></param>
        /// <param name="tagValue"></param>
        /// <returns></returns>
        public static bool WriteTagValue(int tagTypeCodeID, string opName, object tagValue)
        {
            return PlcLinkForm.WritePLC(tagTypeCodeID, opName, tagValue);
        }

        public static ConcurrentDictionary<string, object> ReadPLC_OpName(string opName)
        {
            try
            {
                string tagStartAdr = "";
                ushort tagAdrListMaxLength = 0;
                PlcLinkForm.GetDbAndMaxLengthByOpName(opName, out tagStartAdr, out tagAdrListMaxLength);
                var tagAdrListTagFormat = PlcLinkForm.ReadQualityDataList(opName, tagStartAdr, tagAdrListMaxLength);
               
                return tagAdrListTagFormat;
            }
            catch (Exception err)
            {
                return null;

            }

        }

        public static List<string> Get_opNameList()
        {
            return PlcLinkForm.opNameList;
        }
        public static DoWhatPlc.HashtableList GetHashtableList()
        {
            DoWhatPlc.HashtableList hsList = new DoWhatPlc.HashtableList();
            hsList.hashtable_MesDll = DoWhatPlc.HashtableList.hashtable_MesDll_Temp;
            hsList.hashtable_MesServerCode = DoWhatPlc.HashtableList.hashtable_MesServerCode_Temp;
            hsList.hashtable_TagTypeDataType = DoWhatPlc.HashtableList.hashtable_TagTypeDataType_Temp;
            hsList.hashtable_TagType = DoWhatPlc.HashtableList.hashtable_TagType_Temp;
            hsList.hashtable_OpNameRepair = DoWhatPlc.HashtableList.hashtable_OpNameRepair_Temp;
            hsList.hashtable_TagTypeTagName = DoWhatPlc.HashtableList.hashtable_TagTypeTagName_Temp;


            hsList.hashtable_workStepProperty = DoWhatPlc.HashtableList.hashtable_workStepProperty_Temp;
            hsList.hashtable_QualityMesRead = DoWhatPlc.HashtableList.hashtable_QualityMesRead_Temp;
            hsList.hashtable_IsAllowWork = DoWhatPlc.HashtableList.hashtable_IsAllowWork_Temp;
            hsList.hashtable_WorkGroupIndex = DoWhatPlc.HashtableList.hashtable_WorkGroupIndex_Temp;
            hsList.hashtableOpName_OpType = DoWhatPlc.HashtableList.hashtableOpName_OpType_Temp;
            hsList.hashtable_tagTable_OpName_SaveData = DoWhatPlc.HashtableList.hashtable_tagTable_OpName_SaveData_Temp;



            hsList.hashtable_EngineGetOver_EngineID = DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineID_Temp;
            hsList.hashtable_EngineGetOver_EngineTypeID = DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineTypeID_Temp;
            hsList.hashtable_EngineGetOver_EngineType = DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineType_Temp;
            hsList.hashtable_EngineGetOver_OrderForm = DoWhatPlc.HashtableList.hashtable_EngineGetOver_OrderForm_Temp;

            hsList.BasicDataTagValue = MesServerWork.MIS_BASE.BasicDataTagValue;
            hsList.BasicDataTagValueUpDown = MesServerWork.MIS_BASE.BasicDataTagValueUpDown;
            hsList.hashtable_EngineTypeID = MesServerWork.MIS_BASE.hashtable_EngineTypeID;
            hsList.hashtable_tagTable_OpName_SaveData = MesServerWork.MIS_BASE.hashtable_tagTable_OpName_SaveData;
            return hsList;
        }


        public static List<DoWhatPlc.TagIDTagFormat> ReadPLC_GroupMonitor(string opName)
        {
            List<DoWhatPlc.TagIDTagFormat> TagIDTagFormatList = new List<DoWhatPlc.TagIDTagFormat>();
            var cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(opName);
            foreach (KeyValuePair<string, object> _cd in cd)
            {
                var tagID = _cd.Key;

                var pp1 = JsonConvert.SerializeObject(_cd.Value);
                var pp2 = JsonConvert.DeserializeObject<DoWhatPlc.TagFormat>(pp1);
                DoWhatPlc.TagIDTagFormat TagTF = new DoWhatPlc.TagIDTagFormat(tagID, pp2);

                TagIDTagFormatList.Add(TagTF);
            }
            return TagIDTagFormatList;
        }

        public static List<DoWhatPlc.TagIDTagFormat> ReadPLC_GroupData_Qd(string opName)
        {
            List<DoWhatPlc.TagIDTagFormat> TagIDTagFormatList = new List<DoWhatPlc.TagIDTagFormat>();
            var cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(opName);
            foreach (KeyValuePair<string, object> _cd in cd)
            {
                var tagID = _cd.Key;
                var pp1 = JsonConvert.SerializeObject(_cd.Value);
                var pp2 = JsonConvert.DeserializeObject<DoWhatPlc.TagFormat>(pp1);
                DoWhatPlc.TagIDTagFormat TagTF = new DoWhatPlc.TagIDTagFormat(tagID, pp2);

                TagIDTagFormatList.Add(TagTF);
            }
            return TagIDTagFormatList;
        }
        public static List<DoWhatPlc.TagIDTagFormat> ReadPLC_GroupData(string opName)
        {
            try
            {
                List<DoWhatPlc.TagIDTagFormat> TagIDTagFormatList = new List<DoWhatPlc.TagIDTagFormat>();
                var cd = MesWork.PlcLinkForm.ReadPLC_GroupData(opName);
                foreach (KeyValuePair<string, object> _cd in cd)
                {
                    var tagID = _cd.Key;

                    var pp1 = JsonConvert.SerializeObject(_cd.Value);
                    var pp2 = JsonConvert.DeserializeObject<DoWhatPlc.TagFormat>(pp1);
                    DoWhatPlc.TagIDTagFormat TagTF = new DoWhatPlc.TagIDTagFormat(tagID, pp2);

                    TagIDTagFormatList.Add(TagTF);
                }
                return TagIDTagFormatList;
            }
            catch (Exception err)
            {
                return null;

            }

        }
    }



}
