using bizFacade;
using DataLinkMesWork;
using DoWhatPlc;
using MesServerWork;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MisDataSaveDate
{
    public partial class  Funtion
    {
       

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

                    }
                    else
                    {
                        //MIS_BASE.Write_TagTypeID(20, opName, true);
                    }
                }
                else
                {
                   // MIS_BASE.Write_TagTypeID(20, opName, true);
                }

            }
        }

        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 MIS_BASE.BasicDataTagValue, out MIS_BASE.BasicDataTagValueUpDown, out MIS_BASE.hashtable_EngineTypeID, out MIS_BASE.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, MIS_BASE.BasicDataTagValue,
                    MIS_BASE.BasicDataTagValueUpDown,
                    out dt_WWW,//数据列表
                    out qualityMask,//工位合格标志
                    out engineTypeID,//发动机类型代码
                    out engineID,//发动机编号
                    out engineType, //发动机型号
                    out partPallet,//托盘编号
                    out engineTraceCode, //发动机条码
                    out engineCap,//缸盖号,
                    MIS_BASE.hashtable_EngineTypeID,//发动机类型转换表
                   out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK);




                // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据
                if (Convert.ToInt32(MIS_BASE.hashtable_tagTable_OpName_SaveData[opName]) != 0)
                {
                    DateTime lastupdatetime = DateTime.Now;

                    BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF);
                    BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW);

                }

                //启动线程保存过站信息



                MIS_BASE.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)
            {
                MIS_BASE.Write_TagTypeID(20, opName, true);
                ////ApplicationLog.WriteLog(err, err.Message);
            }

        }
        public static bool BaseData_tagTable_QualityData_B5A_IndexInsert
           (string EngineID, int tagID, string EngineType, int EngineTypeID, string opName,
           int isGoodBad, string PartPalletCode, out int Id_tagCF)
        {
            string procedureName;
            procedureName = "测量数据合格索引_增加";
            Id_tagCF = 0;
            SqlParameter[] thisParms = new SqlParameter[8];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID);
            thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType);
            thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID);
            thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName);
            thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode);
            thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad);
            thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF);
            thisParms[7].Direction = ParameterDirection.Output;

            if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms))
            {
                Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString());
                return true;
            }
            return false;
        }
        public static bool BaseData_tagTable_QualityData_B5A_Insert
   (int Id_tagCF, int engineTypeID, string engineID, string opName, DataTable dt)
        {
            string procedureName;
            procedureName = "测量数据合格_增加";
            SqlParameter[] thisParms = new SqlParameter[6];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID);
            thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID);
            thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", SqlDbType.Int, 4, "TagID");
            thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", SqlDbType.NVarChar, 100, "TagValue");
            thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", SqlDbType.Int, 4, "IsGoodBad");
            //thisParms[6] = new System.Data.SqlClient.SqlParameter("@测量位置", SqlDbType.NVarChar, 50, "测量位置");
            //thisParms[7] = new System.Data.SqlClient.SqlParameter("@测量项目", SqlDbType.NVarChar, 50, "测量项目");
            //thisParms[8] = new System.Data.SqlClient.SqlParameter("@工位号", opName);
            //thisParms[9] = new System.Data.SqlClient.SqlParameter("@理论值", SqlDbType.NVarChar, 50, "理论值");
            //thisParms[10] = new System.Data.SqlClient.SqlParameter("@上限值", SqlDbType.NVarChar, 50, "上限值");
            //thisParms[11] = new System.Data.SqlClient.SqlParameter("@下限值", SqlDbType.NVarChar, 50, "下限值");
            //thisParms[12] = new System.Data.SqlClient.SqlParameter("@测量单位", SqlDbType.NVarChar, 50, "测量单位");
            //thisParms[13] = new System.Data.SqlClient.SqlParameter("@列位置", SqlDbType.Int, 4, "列位置");
            //thisParms[14] = new System.Data.SqlClient.SqlParameter("@变量排序", SqlDbType.Int, 4, "变量排序");
            //table.Columns.Add("TagID", typeof(System.Int32));
            //table.Columns.Add("TagValue", typeof(System.String));
            //table.Columns.Add("IsGoodBad", typeof(System.Int32));
            //table.Columns.Add("测量位置", typeof(System.String));
            //table.Columns.Add("测量项目", typeof(System.String));
            //table.Columns.Add("工位号", typeof(System.String));
            //table.Columns.Add("理论值", typeof(System.String));
            //table.Columns.Add("上限值", typeof(System.String));
            //table.Columns.Add("下限值", typeof(System.String));
            //table.Columns.Add("测量单位", typeof(System.String));
            //table.Columns.Add("列位置", typeof(System.Int32));
            //table.Columns.Add("变量排序", typeof(System.Int32));
            return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, dt);
        }
        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);
            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;
        }
        /// <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;
            }
        }
    }
}
