using MisDataFunDll;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MesServerFunctions
{

    /// <summary>
    /// 命令
    ///显示托盘信息√            case "ShowMoby":
    ///显示操作指南√            case "ProcessList":
    ///显示物料√                case "MaterialList":
    ///显示操作图片√            case "PicShow":
    ///显示拧紧位置√            case "ShaftPosition":
    ///实时显示质量数据√        case "ShowTimelyQuality":
    ///手动拧紧实时显示质量数据√case "ShowTimelyQuality_Tight":
    ///√                        case "OrderFormList":
    ///弹窗消息√                case "Notice":
    ///LED消息提醒√             case "ScrollNotice":
    ///物料检测初始化√          case "MaterialCheckPosition":
    ///返修质量数据显示√        case "RepairQuality"
    ///
    /// </summary>
    public class SendMessage
    {
        /// <summary>
        /// MES/InstantMessaging/BQ
        /// </summary>
        public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"];
      
        /// <summary>
        /// 5 显示订单、机型信息 上线工位
        /// </summary>
        /// <param name="opName"></param>
        public static void ShowMoby_FirstOpName(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = ShowMoby_String_FirstOpName(opName);
            string cmd = "ShowMoby";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }
        /// <summary>
        /// 5 显示订单、机型信息  非上线工位
        /// </summary>
        /// <param name="opName"></param>
        public static void ShowMoby(string opName, int type = 1)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = ShowMoby_String(opName, type);
            string cmd = "ShowMoby";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }
        public static void MaterialList_Dif(string opName, string msgText)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            string cmd = "MaterialList_Dif";
            if (msgText.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{msgText}"));
            }
        }
        public static void AsyncSendMessage_Notice(string opname, string notice)
        {
            //通知Web界面
            MisDataFun.Web_Notice_Insert(opname, notice);
            Notice(opname);
        }
        public static void Notice(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = Notice_String(opName);
            string cmd = "Notice";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }
        /// <summary>
        /// 1（直接在界面通过选择机型确认工序内容）
        /// </summary>
        /// <param name="opName"></param>
        public static void ProcessList(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = ProcessList_String(opName);
            string cmd = "ProcessList";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }
        public static void ProcessList_FirstOpName(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = ProcessList_String_FirstOpName(opName);
            string cmd = "ProcessList";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }
        /// <summary>
        /// 2显示物料
        /// </summary>
        /// <param name="opName"></param>
        public static void MaterialList(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = MaterialList_String(opName);
            string cmd = "MaterialList";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }

        }
        public static void MaterialList_FirstOpName(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = MaterialList_String_FirstOpName(opName);
            string cmd = "MaterialList";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }

        }
        /// <summary>
        /// 3显示操作指导图片
        /// </summary>
        /// <param name="opName"></param>
        public static void PicShow(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = PicShow_String(opName);
            string cmd = "PicShow";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }
        public static void PicShow_FirstOpName(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = PicShow_String_FirstOpName(opName);
            string cmd = "PicShow";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }

        /// <summary>
        /// 4订单完工模块刷新完成数量
        /// </summary>
        /// <param name="opName"></param>
        public static void OrderFormList(string opName)
        {
            var topic = $"{MqttTargetTopic}/{opName}";
            var responseStr = OrderFormList_String();
            string cmd = "OrderFormList";
            if (responseStr.Length > 0)
            {
                Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"));
            }
        }

        //实时显示质量数据√
        public static void ShowTimelyQuality(string opName)
        {

        }

        public static void SendActuallyCount(string OpName, int tagValue)
        {
            //当工件离开时，更新在线产量、在线节拍
            //if (tagValue == 0)
            {
                try
                {
                    int opNameCount = 0;//在线产量
                    int opNameCountTime = 0;//在线节拍

                    MisDataFun.OpNameCount_BQ(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New

                    SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName);

                }
                catch (Exception err)
                {
                    ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount");
                }
            }
        }

        public static void SendInfomation(string Command, string Value, string OpName)
        {

            string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value;
            AsyncSendMessage(SendMessage);
        }

        public static void AsyncSendMessage(string Message)
        {
            //lock (locker)
            {
                //"MES|MachinePlan|OpName|Value
                var array = Message.Split('|');
                var cmd = array[1];
                var opName = array[2];
                var topic = $"{MqttTargetTopic}/{opName}";
                Task.Run(() => Mqtt.Publish(topic, Message));
            }


        }

        public static void AsyncSendNotOpMessage(string topicEnd,string Message)
        {
            {
                var topic = $"{MqttTargetTopic}/{topicEnd}";
                Task.Run(() => Mqtt.Publish(topic, Message));
            }
        }

        private static string ProcessList_String(string OpName)
        {
            string jsonStr_Process = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                DataTable dt_Proccess;

                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.Process_Select(OpName, EngineTypeID, out dt_Proccess);
                if (dt_Proccess != null)
                {
                    if (dt_Proccess.Rows.Count > 0)
                    {
                        jsonStr_Process = JsonConvert.SerializeObject(dt_Proccess);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ProcessList");
            }
            return jsonStr_Process;
        }
        private static string ProcessList_String_FirstOpName(string OpName)
        {
            string jsonStr_Process = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                DataTable dt_Proccess;

                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.Process_Select(OpName, EngineTypeID, out dt_Proccess);
                if (dt_Proccess != null)
                {
                    if (dt_Proccess.Rows.Count > 0)
                    {
                        jsonStr_Process = JsonConvert.SerializeObject(dt_Proccess);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ProcessList");
            }
            return jsonStr_Process;
        }
        //
        private static string PicShow_String(string OpName)
        {
            string data = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                byte[] imgBytesIn;
                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.GetImageFile(OpName, EngineTypeID, out imgBytesIn);
                if (imgBytesIn == null)
                {
                    return data;
                }
                data = Convert.ToBase64String(imgBytesIn);
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:PictureShow");
            }
            return data;
        }

        private static string PicShow_String_FirstOpName(string OpName)
        {
            string data = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                byte[] imgBytesIn;
                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.GetImageFile(OpName, EngineTypeID, out imgBytesIn);
                if (imgBytesIn == null)
                {
                    return data;
                }
                data = Convert.ToBase64String(imgBytesIn);
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:PictureShow");
            }
            return data;
        }
        /// <summary>
        /// 上线工位
        /// </summary>
        /// <param name="OpName"></param>
        /// <returns></returns>
        private static string ShowMoby_String(string OpName, int type = 1)
        {
            string data = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                //非上线工位
                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                data = orderNum + "&" + EngineTypeID + "&" + EngineType + "&" + EngineID + "&" + PartPallet_Code + "&" + IsrepairBarcode + "&" + repairBarcode + "&" + EngineTypeString;
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MobySelect");
            }
            return data;
        }
        private static string ShowMoby_String_FirstOpName(string OpName)
        {
            string data = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                //上线工位
                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                data = orderNum + "&" + EngineTypeID + "&" + EngineType + "&" + EngineID + "&" + PartPallet_Code + "&" + IsrepairBarcode + "&" + repairBarcode + "&" + EngineTypeString;
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MobySelect");
            }
            return data;
        }
        private static string MaterialList_String(string OpName)
        {
            string jsonStr_Materail = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";

                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.PartMaterialVerify_Select(OpName, EngineTypeID, EngineType, out DataTable dt_Material);
                if (dt_Material != null)
                {
                    if (dt_Material.Rows.Count > 0)
                    {
                        jsonStr_Materail = JsonConvert.SerializeObject(dt_Material);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialList");
            }
            return jsonStr_Materail;
        }
        private static string MaterialList_String_FirstOpName(string OpName)
        {
            string jsonStr_Materail = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";

                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.PartMaterialVerify_Select(OpName, EngineTypeID, EngineType, out DataTable dt_Material);
                if (dt_Material != null)
                {
                    if (dt_Material.Rows.Count > 0)
                    {
                        jsonStr_Materail = JsonConvert.SerializeObject(dt_Material);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialList");
            }
            return jsonStr_Materail;
        }

        private static string ShowTimelyQuality_String(string OpName)
        {
            string text = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                DataTable dt;

                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.QualitySelect(OpName, EngineID, out dt);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        text = JsonConvert.SerializeObject(dt);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Quality_Select");
            }
            return text;
        }
        private static string ShowTimelyQuality_String_FirstOpName(string OpName)
        {
            string text = "";
            try
            {
                string orderNum = "";
                int EngineTypeID = 0;
                string EngineType = "";
                string EngineID = "";
                string PartPallet_Code = "";
                int IsrepairBarcode = 0;
                string repairBarcode = "";
                string EngineTypeString = "";
                DataTable dt;
                MisDataFun.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString);
                MisDataFun.QualitySelect(OpName, EngineID, out dt);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        text = JsonConvert.SerializeObject(dt);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Quality_Select");
            }
            return text;
        }

        private static string OrderFormList_String()
        {
            string enginetypelist = "";
            try
            {
                System.Data.DataTable dt = null;
                MisDataFun.EngineType_Select(out dt);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        enginetypelist = JsonConvert.SerializeObject(dt);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Orderenginetypeselect");
            }
            return enginetypelist;
        }

        /// <summary>
        /// 消息提醒
        /// </summary>
        /// <returns></returns>
        private static string Notice_String(string opname)
        {
            string text = "";
            try
            {
                System.Data.DataTable dt = null;
                MisDataFun.ShowWindowNotice(opname, out dt);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        text = JsonConvert.SerializeObject(dt);
                    }
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowWindowNotice");
            }
            return text;
        }

        /// <summary>
        /// 批量发送WEB消息（Value为BOOL值）
        /// </summary>
        /// <param name="MessageNumm">消息编号组合</param>
        /// <param name="Value">消息值组合</param>
        /// <param name="OpName">工位号</param>
        static public void Sendmessage(string MessageNumm, string Value, string OpName)
        {
            for (int i = 0; i < MessageNumm.Length; i++)
            {
                Sendmessage(MessageNumm[i], Value[i].ToString(), OpName);

            }
        }

        /// <summary>
        /// 选择发送给WEB的消息
        /// </summary>
        /// <param name="Num">消息类型</param>
        /// <param name="OpName">消息工位</param>
        static void Sendmessage(char Num, string Value, string OpName)
        {
            string SendMessage;
            switch (Num)
            {
                case '1':
                    //1（直接在界面通过选择机型确认工序内容）
                    SendMessage = "MES|ProcessList|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;

                case '2':
                    //2显示物料
                    SendMessage = "MES|MaterialList|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;

                case '3':

                    //3显示操作指导图片
                    SendMessage = "MES|PicShow|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case '4':
                    //3显示操作指导图片
                    SendMessage = "MES|OrderFormList|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;

                case '5':
                    SendMessage = "MES|ShowMoby|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case '6':
                    SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case '7':
                    SendMessage = "MES|WorkStart|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case '8':
                    SendMessage = "MES|OrderFormList|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case '9':
                    SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case 'a':
                    SendMessage = "MES|FixAllow|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case 'b':
                    SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
                case 'c':
                    SendMessage = "MES|ShowQuality|" + OpName + "|" + Value;
                    AsyncSendMessage(SendMessage);
                    break;
            }
        }
        ///// <summary>
        ///// 发送信息到MES通讯服务器或者其他的
        ///// </summary>
        ///// <param name="Message"></param>
        //static private void AsyncSendMessage1(string Message)
        //{
        //    MIS_BASE.asyncSendMessage(Message);
        //}


    }
}