using DataLinkMesWork1;
using MesServerWork;
using MisDataFunDll;
using MyLog4Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Net.Sockets;
using System.Reflection.Emit;
using System.Web.Http;

namespace MisDataSaveDate
{
    public class Analysis_MOM_Msg
    {
        /// <summary>
        /// UUID生成
        /// </summary>
        /// <returns></returns>
        public static string UuidUtil()
        {
            string result = Guid.NewGuid().ToString();

            return result;
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static Int64 GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }
        /// <summary>
        /// 接收检测数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string OnlineCheckData(string url, [FromBody] JObject jobj)
        {
            var result = new msgResHeader();
            result.MsgId = "";
            result.Message = "";
            result.Code = "200";
            result.Data = "";

            string errorMessage = "";
            string parentID = "";
            int AID = -1;

            if (jobj == null)
            {
                result.Code = "500";
                result.Message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                MyLogHelper.Info("接收检测数据_res", retString1);
                return retString1;
            }
            int isError = 0;
            string str = jobj.ToString();
            try
            {
                //存储日志
                var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //Event_MOM_Log_Insert,@创建时间,@内容
                var param = new SqlParameter[] {
                    new SqlParameter("@接口地址",url),
                    new SqlParameter("@接口类型",2), // 1. 主动调用接口  2. 被调用接口 
                    new SqlParameter("@请求内容",str),
                    new SqlParameter("@请求时间",CreateTime)
                };
                DataLinkMesWork1.DataAccess.ExecuteStoredProcedure("接口_IOT接口交互日志_请求记录", ref param, out DataTable dt, out errorMessage);

                // 解析订单内容，存储数据库，根据实际业务来写
                OnlineCheckData onlineCheckData = JsonConvert.DeserializeObject<OnlineCheckData>(str);
                if (onlineCheckData.MsgId == "")
                {
                    throw new Exception("参数MsgId为空！");
                }
                result.MsgId = onlineCheckData.MsgId;
                if (onlineCheckData.OpCode == "")
                {
                    throw new Exception("参数OpCode为空！");
                }
                if (onlineCheckData.ProductionCode == "")
                {
                    throw new Exception("参数ProductionCode为空！");
                }
                string OpName = onlineCheckData.OpCode;
                int Id_tagCF = 0;
                SqlParameter[] param1 = new SqlParameter[6];
                param1[0] = new SqlParameter("@EngineID", onlineCheckData.ProductionCode);
                param1[1] = new SqlParameter("@工位号", OpName);
                param1[2] = new SqlParameter("@操作者工号", onlineCheckData.CheckPerson);
                param1[3] = new SqlParameter("@扫码时间", onlineCheckData.ScanTime);
                param1[4] = new SqlParameter("@合格标志", onlineCheckData.QualityMark);
                param1[5] = new SqlParameter("@Id_tagCF", Id_tagCF);
                param1[5].Direction = ParameterDirection.Output;
                DataAccess.ExecuteStoredProcedure("测量数据合格索引_增加_测试设备", ref param1, out errorMessage);
                if (errorMessage != "")
                {
                    throw new Exception(errorMessage);
                }
                Id_tagCF = Convert.ToInt32(param1[5].Value.ToString());

                List<OnlineCheckData_CheckData> onlineCheckData_CheckDataList = onlineCheckData.CheckData;

                for (int i = 0; i < onlineCheckData_CheckDataList.Count; i++)
                {
                    OnlineCheckData_CheckData onlineCheckData_CheckData = onlineCheckData_CheckDataList[i];

                    var param2 = new SqlParameter[] {
                        new SqlParameter("@Id_tagCF", Id_tagCF),
                        new SqlParameter("@EngineID", onlineCheckData.ProductionCode),
                        new SqlParameter("@TagID",onlineCheckData_CheckData.CheckCode),
                        new SqlParameter("@TagValue",onlineCheckData_CheckData.CheckValue),
                        new SqlParameter("@IsGoodBad",onlineCheckData_CheckData.QualityMark),
                        new SqlParameter("@工位号",OpName),
                        new SqlParameter("@理论值",onlineCheckData_CheckData.StandardValue),
                        new SqlParameter("@上限值",onlineCheckData_CheckData.MaxValue),
                        new SqlParameter("@下限值",onlineCheckData_CheckData.MinValue),
                        new SqlParameter("@测量项目",onlineCheckData_CheckData.CheckName),
                        new SqlParameter("@测量单位",onlineCheckData_CheckData.Unit),
                    };
                    DataAccess.ExecuteStoredProcedure("测量数据合格_增加_测试设备", ref param2, out errorMessage);
                    if (errorMessage != "")
                    {
                        throw new Exception(errorMessage);
                    }
                }

                // 查询PLC是否传递机型，保证工位有件，可以写保存完成和工作完成
                MIS_BASE.Read_EngineGetOver_PLC(OpName, out bool tagValue);
                if (tagValue)
                {
                    // 电芯段OP040流程比较特殊，无PLC保存数据的流程，可以直接写完成。
                    if (OpName == "OP040")
                    {
                        //通知PLC，MES保存完成
                        MIS_BASE.Write_MesReadOver(OpName, true);
                        //通知PLC，MES工作完成
                        MIS_BASE.Write_MesWorkFinish(OpName, true);
                        MisDataFunDll.MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", "MES保存数据完成！");
                        MisDataFunDll.MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", "MES工作完成！");
                    }
                    else
                    {
                        // 查看PLC是否完成流程，如果完成的话流程结束，否则的话要等PLC完成流程（即允许保存）
                        DataTable dt2 = MisDataFunDll.MisDataFun.CheckAllFinish(OpName, onlineCheckData.ProductionCode, 2);
                        string msg1 = "查询PLC流程出错";
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            string result1 = dt2.Rows[0]["result"].ToString();
                            msg1 = dt2.Rows[0]["msg"].ToString();

                            if (result1 == "1") //已完成
                            {
                                //通知PLC，MES保存完成
                                MIS_BASE.Write_MesReadOver(OpName, true);
                                //通知PLC，MES工作完成
                                MIS_BASE.Write_MesWorkFinish(OpName, true);
                                MisDataFunDll. MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", msg1);
                                MisDataFunDll. MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", "MES保存数据完成！");
                                MisDataFunDll.MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", "MES工作完成！");
                            }
                            else
                            {
                                MisDataFunDll.MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", msg1);
                            }
                        }
                        else
                        {
                            MisDataFunDll.MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", msg1);
                        }
                    }

                }
            }
            catch (Exception err)
            {
                result.Code = "500";
                result.Message = err.Message;
                MisDataFunDll.MisDataFun.LogRecording_OP("All", "ERROR", "MIS", err.Message);
            }
            string retString = JsonConvert.SerializeObject(result);
            MyLogHelper.Info("接收检测数据_res", retString);
       
            return retString;
        }
        /// <summary>
        /// 接收查询检测次数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string OnlineCheckDataCount(string url, [FromBody] JObject jobj)
        {
            var result = new msgResHeader2();
            result.MsgId = "";
            result.Message = "";
            result.Code = "200";
            result.Data = new checkCountData();
            result.Data.CheckCountOk = 0;
            result.Data.CheckCountNg = 0;
            string errorMessage = "";
            string parentID = "";
            int AID = -1;

            if (jobj == null)
            {
                result.Code = "500";
                result.Message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                MyLogHelper.Info("接收查询检测次数_res", retString1);
                return retString1;
            }
            int isError = 0;
            string str = jobj.ToString();
            try
            {
                //存储日志
                var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //Event_MOM_Log_Insert,@创建时间,@内容
                var param = new SqlParameter[] {
                    new SqlParameter("@接口地址",url),
                    new SqlParameter("@接口类型",2), // 1. 主动调用接口  2. 被调用接口 
                    new SqlParameter("@请求内容",str),
                    new SqlParameter("@请求时间",CreateTime)
                };
                DataLinkMesWork1.DataAccess.ExecuteStoredProcedure("接口_IOT接口交互日志_请求记录", ref param, out DataTable dt, out errorMessage);

                // 解析订单内容，存储数据库，根据实际业务来写
                OnlineCheckData onlineCheckData = JsonConvert.DeserializeObject<OnlineCheckData>(str);
                if (onlineCheckData.MsgId == "")
                {
                    throw new Exception("参数MsgId为空！");
                }
                result.MsgId = onlineCheckData.MsgId;
                if (onlineCheckData.OpCode == "")
                {
                    throw new Exception("参数OpCode为空！");
                }
                if (onlineCheckData.ProductionCode == "")
                {
                    throw new Exception("参数ProductionCode为空！");
                }

                SqlParameter[] param1 = new SqlParameter[2];
                param1[0] = new SqlParameter("@EngineID", onlineCheckData.ProductionCode);
                param1[1] = new SqlParameter("@工位号", onlineCheckData.OpCode);
                DataLinkMesWork1.DataAccess.ExecuteStoredProcedure("CATL_测量数据合格_查询测试次数_测试设备", ref param1, out DataTable dt1, out errorMessage);
                if (errorMessage != "")
                {
                    throw new Exception(errorMessage);
                }

                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    result.Data.CheckCountOk = Convert.ToInt32(dt1.Rows[0]["OK"]);
                    result.Data.CheckCountNg = Convert.ToInt32(dt1.Rows[0]["NG"]);
                }

            }
            catch (Exception err)
            {
                result.Code = "500";
                result.Message = err.Message;
            }
            string retString = JsonConvert.SerializeObject(result);
            MyLogHelper.Info("接收查询检测次数_res", retString);
            return retString;
        }
        /// <summary>
        /// 接收打印任务
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReceivePrintTask(string url, [FromBody] JObject jobj)
        {
            var result = new msgResHeader();
            result.MsgId = "";
            result.Message = "";
            result.Code = "200";
            result.Data = "";

            string errorMessage = "";
            string parentID = "";
            int AID = -1;

            if (jobj == null)
            {
                result.Code = "500";
                result.Message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                MyLogHelper.Info("接收打印任务_res", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            try
            {
                //存储日志
                var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //Event_MOM_Log_Insert,@创建时间,@内容
                var param = new SqlParameter[] {
                    new SqlParameter("@接口地址",url),
                    new SqlParameter("@接口类型",2), // 1. 主动调用接口  2. 被调用接口 
                    new SqlParameter("@请求内容",str),
                    new SqlParameter("@请求时间",CreateTime)
                };
                DataLinkMesWork1.DataAccess.ExecuteStoredProcedure("接口_IOT接口交互日志_请求记录", ref param, out DataTable dt, out errorMessage);

                // 解析订单内容，存储数据库，根据实际业务来写
                PrintTaskData printTaskData = JsonConvert.DeserializeObject<PrintTaskData>(str);
                if (printTaskData.printTemplete == "")
                {
                    throw new Exception("参数printTemplete为空！");
                }

                if (printTaskData.productCode == "")
                {
                    throw new Exception("参数productCode为空！");
                }
                if (printTaskData.printDate == "")
                {
                    throw new Exception("参数printDate为空！");
                }
                string msg = $"MARK|{printTaskData.printTemplete}|{printTaskData.productCode},{printTaskData.printDate}";

                // 连接打印机
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    //socket.Connect(MesWorkForm.MarkingMachine_Ip, int.Parse(MesWorkForm.MarkingMachine_Port));
                }
                catch (Exception err)
                {
                    throw new Exception("连接打印机失败:" + err.Message);
                }
                // 发送数据
                try
                {
                    if (socket.Connected)
                    {
                        byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(msg);
                        //socket.Send(decBytes);
                        socket.Send(decBytes, 0, decBytes.Length, SocketFlags.None);
                    }
                    else
                    {
                        throw new Exception("连接打印机失败");
                    }
                }
                catch (Exception err)
                {
                    throw new Exception("发送打印数据失败:" + err.Message);
                }
                // 关闭
                try
                {
                    if (socket.Connected)
                    {
                        socket.Shutdown(SocketShutdown.Both);
                        socket.Close(100);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            catch (Exception err)
            {
                result.Code = "500";
                result.Message = err.Message;
            }
            string retString = JsonConvert.SerializeObject(result);
            MyLogHelper.Info("接收打印任务_res", retString);
            return retString;
        }

    }
}
