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

namespace MesServerFunctions
{
    partial class FunctionMES
    {
        /// <summary>
        /// 处理WEB页面发送过来的请求（m_Command + "|" + m_Value;）
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="Content"></param>
        private void WebSubmit(object e)
        {
            try
            {
                DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e;
                string OpName=Convert.ToString(msgEvent.OpName);
                string Content = Convert.ToString(msgEvent.TagValue);

                string[] dataArray = Content.Split('|');
                if (dataArray.Length != 2)
                    return;
                //消息类型
                string m_Command = dataArray[0].ToString();
                //消息参数
                string m_Value = dataArray[1].ToString();
                //消息参数数量
                string[] m_Value_array = m_Value.Split('&');
                //消息参数长度
                int m_Value_length = m_Value_array.Length;

                //工件信息
                string engineID = "";
                if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null)
                {
                    MIS_BASE.InitHashtable_MesServerCode();
                }
                if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName))
                {
                    engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString();
                }

                DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs();
                _e.OpName = OpName;
                _e.TagValue = m_Value;

                //根据请求的命令处理逻辑
                switch (m_Command)
                {
                    case "Barcode":
                        if (m_Value_length > 1) return;
                        fun_Barcode(_e);
                        break;
                    case "ConfirmOkGo"://合格放行
                        //删除不合格放行记录
                        //修改托盘状态
                        //Update_PalletStatus(OpName, 1, false);
                        BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID);
                        MIS_BASE.Write_ConfirmOkGo(OpName, true);
                        MIS_BASE.Write_FalseGO(OpName, false);
                        Thread.Sleep(1000);
                        MIS_BASE.Write_ConfirmOkGo(OpName, false);
                        break;
                    case "FalseGO"://返修放行
                        //修改托盘状态
                        //Update_PalletStatus(OpName, 3, false);
                        BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID);
                        MIS_BASE.Write_FalseGO(OpName, true);
                        MIS_BASE.Write_ConfirmOkGo(OpName, false);
                        Thread.Sleep(1000);
                        MIS_BASE.Write_FalseGO(OpName, false);
                        break;
                    case "NgGO"://不合格放行
                        //修改托盘状态
                        //Update_PalletStatus(OpName, 2, false);
                        //保存不合格信息(必须保存不合格放行信息，由于B5A的Moby没有不合格标志位)
                        BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", "");
                        MIS_BASE.Write_FalseGO(OpName, true);
                        MIS_BASE.Write_ConfirmOkGo(OpName, false);
                        Thread.Sleep(1000);
                        MIS_BASE.Write_FalseGO(OpName, false);
                        break;
                    case "OnLineState"://在线0、离线1、屏蔽2
                        try
                        {
                            if (m_Value_length > 1) return;
                            int a = Convert.ToInt32(m_Value);
                            if (a <= 2)
                            {
                                BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString());
                                MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value));
                                if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES！");
                                if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES！");
                            }
                        }
                        catch
                        {

                        }
                        break;
                    case "Reset"://复位，将MES所有的信息都复位了
                        SetMoby(OpName);//将MES所有信号清空
                        break;
                    case "FixAllow"://重新拧紧
                        MIS_BASE.Write_FixAllow(OpName, false);
                        MIS_BASE.Write_FixAllow(OpName, true);
                        break;
                    case "IsAutoGetEngineID"://自动手动申请编号（线首）
                        if (m_Value_length > 1) return;
                        MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value));
                        break;
                    case "PartPalletGoOver"://空托盘放行
                         int Is_PartPalletGoOver;
                        MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver);
                        if (Is_PartPalletGoOver == 1)
                        {
                            MIS_BASE.Write_PartPalletGoOver(OpName, 1);
                        }
                        else
                        {
                            MIS_BASE.Write_PartPalletGoOver(OpName,0);
                        }
                        break;
                    case "SetMoby"://清空托盘（线首）
                        SetMoby(OpName);//将MES所有信号清空
                        //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1);
                        break;
                    case "RepairUplineMES"://返修上线
                        MIS_BASE.Write_RepairUpline_MES(OpName, true);
                        break;
                    case "CancelRepair"://将返修件置为正常件

                        break;
                    case "PartPalletCode"://申请写入托盘号
                        //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1);
                        break;
                    case "WritePartPalletCode"://写入托盘号
                        if (m_Value_length > 1) return;
                        MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value));
                        break;
                    case "Normal"://启用正常拧紧工位
                        MIS_BASE.Write_Normal(OpName, 1);
                        MIS_BASE.Write_UnNormal(OpName, 0);
                        break;
                    case "UnNormal"://启用备用拧紧工位
                        MIS_BASE.Write_Normal(OpName, 0);
                        MIS_BASE.Write_UnNormal(OpName, 1);
                        break;
                    case "ResetDevice"://复位设备
                        MIS_BASE.Write_ResetDevice(OpName, true);
                        System.Threading.Thread.Sleep(1000);
                        MIS_BASE.Write_ResetDevice(OpName, false);
                        break;
                    case "IsNeedRepaire"://返修上线(返修上线点)
                        if (Convert.ToInt32(m_Value) == 1)
                        {
                            //修改托盘状态
                            MIS_BASE.Write_PalletInfo(OpName, 3);
                            //通知修改成功
                            MIS_BASE.Write_UpdatePalletOK(OpName, true);
                            IsNeedRepaire_OK(OpName);

                        }
                        else if (Convert.ToInt32(m_Value) == 0)
                        {
                            //通知修改成功
                            MIS_BASE.Write_UpdatePalletOK(OpName, true);
                            //直接给出工作完成
                            MIS_BASE.Write_MaterialVerifyOver(OpName, true);
                        }
                        else
                        { }

                        break;
                    case "ContinueMatch":
                        BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true);
                        break;
                    //初始化网页信号
                    case "IniSingalToWeb":
                        InitializeSingalToWeb(OpName);
                        break;
                    case "Reset_Engine"://返修上线(返修上线点)
                        SetMoby(OpName);//将MES所有信号清空
                        //fun_EngineTypeGetOverPLC(OpName, 0);
                        //fun_EngineTypeGetOverPLC(OpName, 1);
                        break;
                    case "BackWorkGo"://返修放行 
                        // 写入返修工位字符串 (204.48)
                        MIS_BASE.WritePLC(4, OpName, m_Value.ToString());
                        // 写入拧紧结束
                        MIS_BASE.WritePLC(28, OpName, true);
                        Thread.Sleep(1000);
                        MIS_BASE.WritePLC(28, OpName, false);
                        break;
                    case "remedyWork"://补拧工件
                        // 接受传来的补拧程序号 补拧数量 拆分
                        string[] arr = m_Value.ToString().Split('&');
                        string codeNumber = arr[0];
                        string workCount = arr[1];
                        // 写入地址  在工件离开后清空
                        MIS_BASE.WritePLC(88, OpName, workCount);
                        MIS_BASE.WritePLC(77, OpName, codeNumber);
                        // 若这个点被置0了说明PLC那补拧结束了
                        MIS_BASE.WritePLC(30, OpName, true);
                        break;
                    case "remedyWorkEnd"://补拧工件
                        MIS_BASE.WritePLC(77, OpName, 0);
                        MIS_BASE.WritePLC(88, OpName, 0);
                        MIS_BASE.WritePLC(30, OpName, false);
                        break;
                    case "closeWebWindow":// 前端窗口关闭
                        // 将持久化存储表中工位的登陆状态设置为接受值
                        BaseDataSystemMES.Set_TempData(OpName, "登陆状态", m_Value);
                        MIS_BASE.WritePLC(54, OpName, false);
                        break;
                    case "FaultBackWorkType"://返修 拆解返工  选择工位返工  选择工位返工 等
                        // 写入地址
                        MIS_BASE.WritePLC(24, OpName, m_Value);
                        break;
                    case "SkipDiskBearing":// 跳过盘轴
                        MIS_BASE.WritePLC(32, OpName, true);
                        Thread.Sleep(1000);
                        MIS_BASE.WritePLC(32, OpName, false);
                        break;
                    case "QuitEngineTypeCheck":// 发送给服务器换型请求，等待服务器换型判断发送到页面端
                        DataTable dt;
                        dt = BaseDataSystemMES.EngineTypeChange(OpName, m_Value);
                        //提示机型发生变化
                        if (dt.Rows.Count > 0)
                        {
                            string mesValue = Newtonsoft.Json.JsonConvert.SerializeObject(dt);//<DoWhatPlc.CustomeEvetnArgs>(recData);
                            string message = "MES|MaterialList_Dif_Resources|" + OpName + "|" + mesValue;
                            SendMessage.AsyncSendMessage(message);
                            // 写入MOBY 写入机型信息与清空总成号
                            BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, mesValue);
                            BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, "");
                            //通知web显示
                            SendMessageFun.SendMessage("5", "1", OpName);
                        }
                        break;
                    default: break;
                }
            }
            catch(Exception err)
            {
                ////ApplicationLog.WriteLog(err, "Function02:WebSubmit");
            }
        }
        private void SetMoby(string OpName)
        {
            try
            {
                //清空Moby时，需要将MES信号清空
                MIS_BASE.Write_ClearMesMoby(OpName);

                BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName);

                Sendmessage("513", "1111", OpName);

                //获取返工订单数据
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode);
                DataTable dt = new DataTable();
                dt = BaseDataSystemMES.Get_BackWorkData(EngineID);
                string Back_OpName = dt.Rows[0]["工位号"].ToString();

                //通知web显示  在返修工位显示故障来源工位的物料数据与工艺图片
                //物料数据
                MesWebFun_base.MesWebFun_base mb = new MesWebFun_base.MesWebFun_base();
                string MaterialListStr = mb.ProcessRequest("MaterialList", Back_OpName);
                string message = "MES|MaterialList_Resources|" + OpName + "|" + MaterialListStr;
                SendMessage.AsyncSendMessage(message);
                //工艺图片
                string PictureShowStr = mb.ProcessRequest("PictureShow", Back_OpName);
                message = "MES|PicShow_Resources|" + OpName + "|" + PictureShowStr;
                SendMessage.AsyncSendMessage(message);

                MIS_BASE.Write_ResetDevice(OpName, true);
                System.Threading.Thread.Sleep(1000);
                MIS_BASE.Write_ResetDevice(OpName, false); 
            }
            catch
            {

            }
        }
        /// 网页重现登录，恢复关闭前的页面状态
        /// </summary>
        /// <param name="Opname">工位号</param>
        private void InitializeSingalToWeb(string Opname)
        {

            //工件到位 DBX0.1
            bool S_WorkStart;
            bool S_FixAllow;
            bool S_EngineGetOver;
            bool S_MaterialVerifyOver;

            MIS_BASE.Read_WorkStart(Opname, out S_WorkStart);
            MIS_BASE.Read_FixAllow(Opname, out S_FixAllow);
            MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver);
            MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver);

            DataTable tempDt;
            BaseDataSystemMES.Get_TempData(Opname, "登陆状态", out tempDt);
            if (tempDt.Rows.Count > 0) MIS_BASE.WritePLC(54, Opname, tempDt.Rows[0]["数值"]);

            Sendmessage("135", "1111", Opname);
            string S_plcStatus;//DBX501.5 PLC直通，1 强制放行 0 正常循环
            // 新增查询PLC直通状态 网页显示
            MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus);
            if (Convert.ToInt32(S_plcStatus) == 0)
            {
                SendMessageFun.SendInfomation("PlcStatus", "0", Opname);
            }
            else
            {
                SendMessageFun.SendInfomation("PlcStatus", "1", Opname);
            }

            string strValue = MIS_BASE.ReadPLC(40, Opname).ToString();

            // 查询螺丝号是否存在  存在则发送给前端
            string CodeNumber;
            MIS_BASE.Read_TagTypeID(125, Opname, out CodeNumber);
            if (CodeNumber != "0")
            {
                SendMessageFun.SendInfomation("CodeNumber", CodeNumber, Opname);
            }

            // 查询螺丝号下拧紧排序是否存在  存在则发送给前端
            string CodeNumberWorkNumber;
            MIS_BASE.Read_TagTypeID(126, Opname, out CodeNumberWorkNumber);
            if (CodeNumberWorkNumber != "0")
            {
                SendMessageFun.SendInfomation("CodeNumberWorkNumber", CodeNumberWorkNumber, Opname);
            }


            if (S_WorkStart == true)
            {
                SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname);
            }
            if (S_FixAllow == true)
            {
                SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname);
            }
            if (S_MaterialVerifyOver == true)
            {
                SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname);
            }
            if (S_EngineGetOver == true)
            {
                SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname);
                Sendmessage("2", "1111", Opname);
                //SendMessage.ShowMoby(Opname);
                // 直接发送实时的 质量数据
                string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(Opname);
                //推送质量数据到MES的页面
                SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + Opname + "|" + message);
            }
            InitAlarm(Opname);
        }
        private void InitAlarm(string Opname)
        {
            FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht);
            foreach (DictionaryEntry kv in ht)
            {
                var TagID = kv.Key.ToString();
                var TagValue = kv.Value.ToString();
                FuntionMesRead.Send_AlarmMsg(TagID, TagValue);
            }

        }
    }
}
