//using BasicData;
using bizFacade;
using DoWhatPlc;
using Newtonsoft.Json;
//using bizFacade;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
//using SystemFramework;

namespace MisDataFunction
{
    partial class Function
    {
        /// <summary>
        /// 获取质量数据Hashtable
        /// </summary>
        /// <param name="opName"></param>
        /// <returns></returns>
        //static public Hashtable ReadPLC_Sync_DataList_MesRead(string opName)
        //{
        //    return (Hashtable)MesDataFunction.OpcOperation.ReadPLC_Sync_DataList_MesRead(opName);
        //}
        static object lockerReadPLC_Sync_DataList_MesRead1 = new object();
        public static void ReadPLC_Sync_DataList_MesRead(string opName, out Hashtable valueList, out DataTable BasicDataTagValue, out DataTable BasicDataTagValueUpDown, out Hashtable hashtable_EngineTypeID, out Hashtable hashtable_tagTable_OpName_SaveData)
        {
            //QualityDataSaveList QualityDataType
            valueList = new Hashtable();
            //var qualityDataSaveList = DtWebApi.SaveData.ReadPLC_Sync_DataList_MesRead(opName);
            var qualityDataSaveList = MesServerWork.MIS_BASE.ReadPLC_Sync_DataList_MesRead(opName);
            foreach (DictionaryEntry de in qualityDataSaveList.valuList)
            {
                valueList.Add(de.Key, JsonConvert.DeserializeObject<QualityDataType>(de.Value.ToString()));
            }
            BasicDataTagValue = qualityDataSaveList.BasicDataTagValue;
            BasicDataTagValueUpDown = qualityDataSaveList.BasicDataTagValueUpDown;
            hashtable_EngineTypeID = qualityDataSaveList.hashtable_EngineTypeID;
            hashtable_tagTable_OpName_SaveData = qualityDataSaveList.hashtable_tagTable_OpName_SaveData;
        }
        public static Hashtable ReadPLC_Sync_DataList_MesRead(string opName)
        {
            lock (lockerReadPLC_Sync_DataList_MesRead1)
            {
                Hashtable ht = new Hashtable();
                var cd = ReadPLC_GroupData(opName);
                //var cd = PlcLinkForm.ReadPLC_GroupData(opName);

                foreach (var _cd in cd)
                {
                    var tagID = Convert.ToInt32(_cd.TagID);
                    var TF =_cd.TF;

                    QualityDataType qualityDataType;
                    qualityDataType = new QualityDataType();

                    qualityDataType.tagID = TF.TagID;
                    qualityDataType.tagTypeID = TF.TagTypeID;//变量类型
                    qualityDataType.opName = opName;
                    qualityDataType.isGoodBad = 192;
                    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;//变量值

                    ht.Add(tagID, qualityDataType);
                }
                return ht;
            }

        }

        /// <summary>
        /// 允许保存(针对半自动和手动压装工位)
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="tagValue"></param>
        private static void MesRead(string opName, string tagValue, int tagid)
        {
            if (tagValue == "0")
            {
                Write_TagTypeID(20, opName, false);
            }
            else
            {
                SaveQualityData(opName, Convert.ToInt32(tagValue), tagid);
            }
        }

        private static void SaveQualityData(string opName, int tagValue, int tagID)
        {
            try
            {
                int id_tagCF;
                int qualityMask = 0;
                int engineTypeID = 0;
                string engineID = "";
                string engineType = "";
                string engineTraceCode = "";
                string engineCap = "";
                string partPallet = "";
                DataTable dt_WWW;
                dt_WWW = BaseDataSystemMES.BuildDataTables_WWW();
                Hashtable valueList;
                //valueList = ReadPLC_Sync_DataList_MesRead(opName);
                ReadPLC_Sync_DataList_MesRead(opName, out valueList, out BasicDataTagValue, out BasicDataTagValueUpDown, out hashtable_EngineTypeID, out hashtable_tagTable_OpName_SaveData);
                valueList = GetQualityData_GoodBad_Values(valueList);
                int mes_MustTest = 0;
                int onLineState = 0;
                int partMoveDirection = 0;
                int pressIsOK = 0;
                int pressIsNoOK = 0;
                BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, BasicDataTagValue,
                    BasicDataTagValueUpDown,
                    out dt_WWW,//数据列表
                    out qualityMask,//工位合格标志
                    out engineTypeID,//发动机类型代码
                    out engineID,//发动机编号
                    out engineType, //发动机型号
                    out partPallet,//托盘编号
                    out engineTraceCode, //发动机条码
                    out engineCap,//缸盖号,
                    hashtable_EngineTypeID,//发动机类型转换表
                   out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK);




                // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据
                if (Convert.ToInt32(hashtable_tagTable_OpName_SaveData[opName]) != 0)
                {
                    DateTime lastupdatetime = DateTime.Now;
                    
                    BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF);
                    BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW);
                 
                }
                Write_TagTypeID(20, opName, true);
                #region 
                //string orderForm = "";
                //string operatorCode = "";
                //int shiftCode = 1;
                //DateTime arrivedTime;
                //DateTime leavedTime;
                //int TimeDiff;
                //int targetTime = 0;
                //string lineType = "";
                //string isPass;
                //int machineWorkOn = 0;
                //int arrivedOrLeaved = 2;
                //int cartColorOpName = 0;
                //int cartColorConfirm = 0;
                //// int partMoveDirection;
                //int partGoOver = 0;
                //if (qualityMask == 1)
                //{
                //    isPass = "PASS";
                //}
                //else
                //{
                //    isPass = "FAIL";
                //}

                ////工位上下线类型 
                ////（0普通工位）（1正常上线）（2正常下线）（3返修上线）（4返修下线）
                //int OpNameUpDownType;
                //OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]);
                //arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName];
                //leavedTime = DateTime.Now;
                //TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds);

                //lineType = hashtableOpName_LineType[opName].ToString();

                //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString();
                ////isHaveComputer = MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString();
                ////有计算机的工位，通过工位计算机保存[测量数据发动机在线状态]。
                //if (Convert.ToInt32(isHaveComputer) == 0)
                //{
                //    //1->0 工件离开 工件刚刚离开
                //    if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1)
                //    {

                //        //[测量数据发动机在线状态]
                //        QualityDataSystem.WorkStartInsert
                //            (opName, orderForm, engineTypeID, engineType, engineID, partPallet.ToString(), operatorCode, shiftCode,
                //            arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, machineWorkOn,
                //            arrivedOrLeaved, cartColorOpName, cartColorConfirm, partMoveDirection, partGoOver, mes_MustTest, onLineState, OpNameUpDownType);
                //    }
                //}
                #endregion
            }
            catch (Exception err)
            {
                Write_TagTypeID(20, opName, true);
                ////ApplicationLog.WriteLog(err, err.Message);
            }

        }
        public static void SaveQualityData_Mes(string opName, int tagID)
        {
            try
            {
                int id_tagCF;
                int qualityMask = 0;
                int engineTypeID = 0;
                string engineID = "";
                string engineType = "";
                string engineTraceCode = "";
                string engineCap = "";
                string partPallet = "";
                DataTable dt_WWW;
                dt_WWW = BaseDataSystemMES.BuildDataTables_WWW();
                Hashtable valueList;
                valueList = ReadPLC_Sync_DataList_MesRead(opName);
                valueList = GetQualityData_GoodBad_Values(valueList);
                int mes_MustTest = 0;
                int onLineState = 0;
                int partMoveDirection = 0;
                int pressIsOK = 0;
                int pressIsNoOK = 0;
                BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, BasicDataTagValue,
                    BasicDataTagValueUpDown,
                    out dt_WWW,//数据列表
                    out qualityMask,//工位合格标志
                    out engineTypeID,//发动机类型代码
                    out engineID,//发动机编号
                    out engineType, //发动机型号
                    out partPallet,//托盘编号
                    out engineTraceCode, //发动机条码
                    out engineCap,//缸盖号,
                    hashtable_EngineTypeID,//发动机类型转换表
                   out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK);
                // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据
                if (Convert.ToInt32(hashtable_tagTable_OpName_SaveData[opName]) != 0)
                {
                    DateTime lastupdatetime = DateTime.Now;
                    BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF);
                    //BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW);
                  
                }


            }
            catch (Exception err)
            {
                Write_TagTypeID(20, opName, true);
                ////ApplicationLog.WriteLog(err, err.Message);
            }

        }
        
        /// <summary>
        /// 确定合格标志
        /// </summary>
        /// <param name="valuList"></param>
        /// <returns></returns>
        static public Hashtable GetQualityData_GoodBad_Values(Hashtable valuList)
        {
            try
            {
                Hashtable valuList_Temp;
                valuList_Temp = (Hashtable)valuList.Clone();
                int[] value_GoodBad_New = new int[128];
                int tagID;
                QualityDataType value;
                //1：获得合格标志
                foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 
                {
                    tagID = Convert.ToInt32(de.Key);
                    value = (QualityDataType)de.Value;
                
                    //拧紧数据合格标志
                    if (value.tagProperty == 1)
                    {
                        if (value.tagTypeID == 8203)
                        {
                            value_GoodBad_New = (int[])value.tagValue;
                            break;
                        }
                        else
                        {
                            value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue);
                        }
                    }
                    //拧紧数据合格标志
                    if (value.tagProperty == 8)
                    {
                        if (value.tagTypeID == 8203)
                        {
                            value_GoodBad_New = (int[])value.tagValue;
                            break;
                        }
                        else
                        {
                            value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue);
                        }
                    }
                    //压装数据合格标志
                    if (value.tagProperty == 7)
                    {
                        value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue);
                    }
                }
                //将合格标志赋予每个变量
                foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 
                {
                    tagID = Convert.ToInt32(de.Key);
                    value = (QualityDataType)de.Value;
                    //201706061720新加
                    if (value .tagTypeID ==11)
                    {
                        if (value.tagValue.ToString ()=="False")
                        {
                            value.tagValue ="0";
                        }
                        else
                        {
                            value.tagValue = "1";
                        }
                        valuList_Temp[tagID] = value;
                        //value.tagValue = Convert.ToInt32(value.tagValue);
                    }


                    //测量变量
                    if (value.tagProperty == 2 || value.tagProperty == 6)
                    {
                        try
                        {
                            if (value_GoodBad_New != null)
                            {
                                value.isGoodBad = Convert.ToInt32(value_GoodBad_New[value.tagOrderBy - 1]);
                                valuList_Temp[tagID] = value;
                            }
                            else
                            {
                                value.isGoodBad = 0;
                                valuList_Temp[tagID] = value;
                            }
                        }
                        catch (Exception err)
                        {
                            ////ApplicationLog.WriteLog(err, err.Message);

                        }
                    }
                   


                }
                return valuList_Temp;
            }
            catch//转换出了故障时
            {
                return valuList;
            }
        }



        /// <summary>
        /// 制定工位PLC是否传递过机型 （默认不传递机型不保存过站信息）
        /// </summary>
        static Hashtable EngTypeGetOver = new Hashtable();

        static Hashtable EngineData_Hash = new Hashtable(); //保存

        public static void IsEngTypeGetOver_Write(string OpName, bool value)
        {
            if (EngTypeGetOver.ContainsKey(OpName))
            {
                EngTypeGetOver[OpName] = value;
            }
            else
            {
                EngTypeGetOver.Add(OpName, value);
            }
        }


        public static bool IsEngTypeGetOver_Read(string OpName)
        {
            if (EngTypeGetOver.ContainsKey(OpName))
            {
                return Convert.ToBoolean(EngTypeGetOver[OpName]);
            }
            else
            {
                return true;
            }
        }

        public static void EngineData_Hash_Write(string OpName, object value)
        {
            if (EngineData_Hash.ContainsKey(OpName))
            {
                EngineData_Hash[OpName] = value;

            }
            else
            {
                EngineData_Hash.Add(OpName, value);
            }
        }

        public static object EngineData_Hash_Read(string OpName)
        {
            if (EngineData_Hash.ContainsKey(OpName))
            {
                return EngineData_Hash[OpName];
            }
            else
            {
                return null;
            }

        }


        private DataTable ChangeQualificationMark(DataTable dt)
        {
            var dtNew = dt.Copy();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var 变量排序 = dt.Rows[i]["变量排序"].ToString();
                if (变量排序 == "0")
                {

                }
            }


            return dtNew;
        } 




    }
    struct EngineData
    {
        public EngineData(string engineID, int pallet)
        {
            EngineID = engineID;
            Pallet = pallet;
        }

        public string EngineID;//工件编号
                               //public string EngineType;
                               //public int EngineTypeID;
        public int Pallet;//托盘号

    }






}
