using System;
using System.Data;
using System.Threading;
using bizFacade;
using MesServerWork;
//using SystemFramework;


namespace MesServerFunctions
{
    partial class FunctionMES
    {
        /// <summary>
        /// 分线上总线的数量
        /// </summary>
        public static int SubLineLoadPartCount = 2;
        /// <summary>
        /// 分线上总线已经匹配的数量
        /// </summary>
        public static int SubLineLoadPartCountMatch = 0;
        /// <summary>
        /// 正常逻辑工作
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="EngineTypeID"></param>
        /// <param name="EngineType"></param>
        /// <param name="EngineID"></param>
        /// <param name="PartPallet_Code"></param>
        private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm)
        {
            int IsAllowWork;
            int RepairPartStatusPLC = 0;
            int MES_QualityMask = 1;

            if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0)
            {
                MIS_BASE.WritePLC(34, OpName, true);
                string msg = "【" + OpName + "】" + "PLC传递机型为空！";
                MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg);
                SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空");
                return;
            }

            MIS_BASE.Write_FixAllow(OpName, true);

            //初始化物料临时表
            //第二步，将零件信息转移到零件_临时表中（本地BOM与订单BOM的选择显示关系）
            //BaseDataSystemMES.MesServer_Process_EngineTypeOver_BQ_FirstOP(OpName);

            ////5 显示订单、机型信息 线首工位用
            //SendMessage.ShowMoby_FirstOpName(OpName);
            ////3显示操作指导图片 PicShow_String_FirstOpName
            //SendMessage.PicShow_FirstOpName(OpName);
            ////1（直接在界面通过选择机型确认工序内容）
            //SendMessage.ProcessList_FirstOpName(OpName);
            ////界面显示物料信息
            //SendMessage.MaterialList_FirstOpName(OpName);

            ////第四步，获取是否允许工作
            //BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork);

            // 暂时先定义为扫描完成才能进行压装工作，因为考虑到工作完成后，操作工未必会去扫描物料的情况
            //if (IsAllowWork == 1)
            //{
            //    //通知PLC允许工作,允许工作在保存完成时清空
            //    MIS_BASE.Write_FixAllow(OpName, true);
            //}
            //else
            //{
            //    SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料！");
            //}

        }


        /// <summary>
        /// 保存MOBY信息
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="engineTypeID"></param>
        /// <param name="engineType"></param>
        /// <param name="engineID"></param>
        private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm)
        {

            if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null)
            {
                MIS_BASE.InitHashtable_MesServerCode();
            }
            if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName))
            {
                MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID;
            }
            if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName))
            {
                MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType;
            }
            if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName))
            {
                MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID;
            }
            if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName))
            {
                MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm;
            }
        }

        /// <summary>
        /// 返修件需要工作
        /// </summary>
        /// <param name="OpName">工位号</param>
        private void IsNeedRepaire_OK(string OpName)
        {

            int isRepair;
            int engineTypeID;

            string engineType = "";
            string engineID = "";
            string palletCode = "";
            string orderForm = "";
            string repairCode = "";
            //从监控系统中查询出本工位信息
            BaseDataSystemMES.OpName_MIS_Moby_Select(OpName,
            out  orderForm, out  engineTypeID, out  engineType,
            out  engineID, out palletCode, out isRepair, out repairCode);

            EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm);
        }
        /// <summary>
        /// 正常匹配分线和总线
        /// </summary>
        /// <param name="opName"></param>
        /// <param name="engineID">总线工件号</param>
        /// <param name="engineTypeID">总线工件机型代码</param>
        /// <param name="engineType">总线工件机型</param>
        private void Match(string opName, string engineID, int engineTypeID, string engineType, int PartPallet_Code)
        {
            try
            {
                bool m_EngineGetOver_PLC_SubLine;
                int engineTypeID_SubLine;
                int partPallet_Code_SubLine;
                int PalletInfo = 1;//总线托盘状态

                string opName_SubLine = "";//分线工件信息
                string engineID_SubLine;
                string engineType_SubLine;
                string AlarmStr;
                if (MIS_BASE.hashtable_OpNameRepair == null)
                {
                    MIS_BASE.InitHashtable_MesServerCode();
                }
                //第一步：获取分线中间交互工位号
                if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName))
                {
                    opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString();
                }
                if (opName_SubLine == "")
                {
                    return;
                }

                //第二步：获取分线传递机型信号
                MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine);
                if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配

                //第三步：判断合格标志
                MIS_BASE.Read_PalletInfo(opName_SubLine, out  PalletInfo);
                if (PalletInfo == 2) return; //若不合格则返回不进行匹配
                string OrderForm;
                //第四步：获取分线的信息，匹配验证
                MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm);
                //判断分线数据是否合格
                //if (!BaseDataSystemMES.QulityDataVerify(opName, engineID_SubLine, out AlarmStr) && !BaseDataSystemMES.QualityVerifyStatus_Hash_Read(opName))
                //{
                //    SendInfomation("LineoutAlert", AlarmStr, opName);
                //    return;
                //}

                if (engineTypeID_SubLine == engineTypeID)
                {
                    BaseDataSystemMES.SubLineLoadPartCountMatch_Select(opName, out SubLineLoadPartCountMatch);
                    SubLineLoadPartCountMatch = SubLineLoadPartCountMatch + 1;
                    BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch);


                    BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移
                    MIS_BASE.Write_Match(opName, true);//匹配结果
                    MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成
                    if(SubLineLoadPartCountMatch== SubLineLoadPartCount)
                    {
                        MIS_BASE.Write_FixAllow(opName, true);
                        SubLineLoadPartCountMatch = 0;
                        BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch);

                    }

                    SendMessageFun.SendInfomation("MatchSuccess", "1", opName);
                    sendmessage(opName, 1, "Match");//匹配结果
                }
                else
                {
                    MIS_BASE.Write_Match(opName, false);//匹配结果
                    MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成//68:1、取消返修；2、匹配成功  自己监控发送 MES|MatchingCompleted

                    //发送匹配完成和匹配结果信息
                    SendMessageFun.AsyncSendMessage_Notice(opName,"匹配失败，工件型号不匹配！");
                    SendMessageFun.SendInfomation("MatchSuccess", "0", opName);
                    sendmessage(opName, 0, "Match");//匹配结果
                }

            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog("Match:" + err.ToString());

            }
        }



        /// <summary>
        /// 强制匹配分线和总线
        /// </summary>
        /// <param name="opName"></param>
        private void ForceMatch(string opName)
        {
            try
            {
                bool m_EngineGetOver_PLC_SubLine;
                bool m_EngineGetOver_PLC;

                int engineTypeID_SubLine;
                int engineTypeID;
                int partPallet_Code_SubLine;
                int partPallet_Code;

                string opName_SubLine = "";//分线工件信息
                string engineID_SubLine;
                string engineType_SubLine;
                string engineID;
                string engineType;
                if (MIS_BASE.hashtable_OpNameRepair == null)
                {
                    MIS_BASE.InitHashtable_MesServerCode();
                }
                //获取分线中间交互工位号
                if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName))
                {
                    opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString();
                }
                if (opName_SubLine == "")
                {
                    return;
                }

                MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine);//1:读取分线工件到位的传递机型信号。

                if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配

                MIS_BASE.Read_EngineGetOver_PLC(opName, out m_EngineGetOver_PLC);//2:读取总线工件到位的传递机型信号。

                if (!m_EngineGetOver_PLC) return;//必须工件同时到位才能进行匹配
                string OrderForm;
                MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out  OrderForm);//获取分线的信息
                MIS_BASE.GetEngineTypeFromPLC(opName, out engineTypeID, out engineType, out engineID, out partPallet_Code, out OrderForm);

                BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移

                MIS_BASE.Write_Match(opName, true);//匹配结果
                MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成

                SendMessageFun.SendInfomation("MatchSuccess", "1", opName);//界面显示匹配成功

                MIS_BASE.Write_FixAllow(opName, true);//允许PLC工作

                //发送匹配完成和匹配结果信息
                sendmessage(opName, 1, "MatchingComplete");//匹配完成
                sendmessage(opName, 1, "Match");//匹配结果
            }
            catch
            {

            }
        }

        /// <summary>
        /// 空料握手plc
        /// </summary>
        /// <param name="OpName"></param>
        private void Handshake_Fun(object e)
        {

            DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e;
            string OpName = Convert.ToString(msgEvent.OpName);
            int tagValue = Convert.ToInt32(msgEvent.TagValue);

            if (tagValue == 1)
            {
                int planCount = 0; // 计划上料数量
                int haveUplaodCount = 0; // 已上料数量
                int remainingQuantity = 0; // 待上料数量
                                           // 读取当前选择的计划中的机型，写入PLC
                                           // 获取订单的机型
                string Program_No = "";
                Db.GetEngineType_Order(OpName, Program_No, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm, out int isCheckOk, out planCount, out haveUplaodCount, out remainingQuantity);
                if (isCheckOk == 2)
                {
                    MIS_BASE.WritePLC(34, OpName, true);

                    MIS_BASE.WritePLC(95, OpName, planCount);
                    MIS_BASE.WritePLC(96, OpName, haveUplaodCount);
                    MIS_BASE.WritePLC(97, OpName, remainingQuantity);

                    MIS_BASE.WritePLC(35, OpName, true);
                    return;
                }
                else
                {
                    BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID);

                    MIS_BASE.WritePLC(34, OpName, false);

                    // 写入机型代码 （大机型） 机型 发动机号 订单号
                    MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID);
                    MIS_BASE.Write_EngineType_MES(OpName, EngineType);
                    MIS_BASE.Write_EngineID_MES(OpName, EngineID);
                    MIS_BASE.Write_OrderForm_MES(OpName, OrderForm);
                    MIS_BASE.WritePLC(95, OpName, planCount);
                    MIS_BASE.WritePLC(96, OpName, haveUplaodCount);
                    MIS_BASE.WritePLC(97, OpName, remainingQuantity);

                    Thread.Sleep(500);
                    // MES传递机型
                    MIS_BASE.WritePLC(35, OpName, true);
                }
            }
            else
            {
                MIS_BASE.WritePLC(35, OpName, false);
            }
        }
    }
}
