using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataLinkMesWork;
using MesDataFunction;
using MesServerFunctions;
using MesServerWork;
using System.Windows.Forms;

namespace MisDataFunDll
{
    public partial class MisDataBaseFun
    {
        /// <summary>
        /// 扫描托盘码进行托盘校验 主要Pack线使用 拉取Pack号校验
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="BarCode"></param>
        /// <param name="EngineID"></param>
        /// <returns>1 已通过或者无需验证 2 验证失败 3 本次验证成功</returns>
        public static int ScanPalletCode(string OpName,string BarCode, string EngineID)
        {
            if(MisDataFun.GetSpecialOpExist(OpName, "到站扫托盘码"))
            {
                // 判断是否完成二次验证 
                string IsMatchBarcode = "0";
                MIS_BASE.Read_TagValueByTagTypeID(54, OpName, out IsMatchBarcode);
                if (IsMatchBarcode != "1")
                {

                    MIS_BASE.Read_EngineGetOver_PLC(OpName, out bool PartLoad_EngineGetOver_PLC);
                    if (!PartLoad_EngineGetOver_PLC)
                    {
                        string msg1 = "无法扫码，PLC未传递机型!";
                        MisDataFun.LogRecording_OP(OpName, "ERROR", "Barcode", msg1);
                        SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg1, "条码扫描");
                        return 2;
                    }

                    // 这里根据BarCode获取到 对于需要与PLC托盘信息校验的码值
                    string CheckCode = MisDataFun.GetPartCodeByBarCodde(OpName, BarCode);
                    // 部分特殊工位不需要拉去PACK进行校验 如 150
                    if (MisDataFun.GetSpecialOpExist(OpName, "校验托盘码不拉PACK码")) CheckCode = BarCode;

                    if (EngineID == CheckCode)
                    {
                        // MES比对信息完成
                        MIS_BASE.Write_MachineTime_ReadOver(OpName, true);

                        string msgErr = "【" + OpName + "】" + "托盘信息与扫码信息比对成功！";
                        MisDataFun.LogRecording_OP(OpName, "INFO", "barcode", msgErr);
                        SendMessageFun.AsyncSendMessage_Notice(OpName, msgErr);

                        return 3;
                    }
                    else
                    {
                        // MES比对信息完成 比对不成功
                        MIS_BASE.Write_MachineTime_ReadOver(OpName, false);
                        // MES报警
                        MIS_BASE.Write_TagValueByTagTypeID(34, OpName, true);

                        string msgErr = "【" + OpName + "】" + "托盘信息与扫码信息比对失败，扫码信息：" + BarCode;
                        SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msgErr, "条码扫描");
                        MisDataFun.LogRecording_OP(OpName, "ERROR", "barcode", msgErr);
                        return 2;
                    }
                }
            }
            return 1;
        }

        /// <summary>
        /// 前序是否合格校验
        /// </summary>
        /// <param name="OpName"></param>
        /// <returns></returns>
        public static bool NotAllowWorkVerify(string OpName,string EngineID)
        {
            // 查询是否 不允许工作
            MisDataFun.Get_NotAllowWork(EngineID, OpName, out bool NotAllowWork);
            if (NotAllowWork)
            {
                string msg = "前序不合格 不进行工作：" + EngineID;
                MisDataFun.LogRecording_OP(OpName, "INFO", "MOM", msg);
                SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg, "返修放行");
                MIS_BASE.Write_NotAllowWork(OpName, true); // 不允许工作
                MIS_BASE.Write_MesErrorType(OpName, 1004); // 工位报警 前序不合格 不允许工作！
                return false;
            }
            return true;
        }

        /// <summary>
        /// 传递机型 判空 
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="EngineID"></param>
        /// <param name="EngineTypeID"></param>
        /// <returns>true 通过 false 不通过</returns>
        public static bool EngineTypeVerify(string OpName, string EngineID, int EngineTypeID)
        {
            // 判断PLC机型是否写入
            if (EngineTypeID == 0 || EngineID == "")
            {
                MIS_BASE.Write_TagValueByTagTypeID(34, OpName, true);// MES报警
                string msg = "【" + OpName + "】" + "PLC机型写入为空，EngineTypeID：" + EngineTypeID + "，EngineID：" + EngineID;
                SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg, "传递机型");
                MisDataFun.LogRecording_OP(OpName, "ERROR", "EngineTypeGetOver", msg);
                MIS_BASE.Write_MesErrorType(OpName, 1002); // 工位报警 未读取到托盘产品信息！
                return false;
            }
            return true;
        }

        /// <summary>
        /// 上线用传递机型 判空 并且 判断一致性
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="EngineID"></param>
        /// <param name="EngineTypeID"></param>
        /// <param name="EngineID_MES"></param>
        /// <param name="EngineTypeID_MES"></param>
        /// <returns>true 通过 false 不通过</returns>
        public static bool EngineTypeVerifyOnLine(string OpName,string EngineID,int EngineTypeID,string EngineID_MES,int EngineTypeID_MES)
        {
            // 判断PLC机型是否写入
            if (EngineTypeID == 0 || EngineID == "")
            {
                MIS_BASE.Write_TagValueByTagTypeID(34, OpName, true);// MES报警
                string msg = "【" + OpName + "】" + "PLC机型写入为空，EngineTypeID：" + EngineTypeID + "，EngineID：" + EngineID;
                SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg, "传递机型");
                MisDataFun.LogRecording_OP(OpName, "ERROR", "EngineTypeGetOver", msg);
                MIS_BASE.Write_MesErrorType(OpName, 1002); // 工位报警 未读取到托盘产品信息！
                return false;
            }
            //判断PLC机型与MES机型是否一致
            if (EngineTypeID != EngineTypeID_MES || EngineID != EngineID_MES)
            {
                MIS_BASE.Write_TagValueByTagTypeID(34, OpName, true);// MES报警
                string msg = "【" + OpName + "】" + "PLC机型与MES机型不一致，EngineTypeID：" + EngineTypeID + "，EngineID：" + EngineID + "，EngineTypeID_MES：" + EngineTypeID_MES + "，EngineID_MES：" + EngineID_MES;
                SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg, "传递机型");
                MisDataFun.LogRecording_OP(OpName, "ERROR", "EngineTypeGetOver", msg);
                MIS_BASE.Write_MesErrorType(OpName, 1001); // 工位报警 PLC机型与MES机型不一致 信息校验失败！
                return false;
            }
            return true;
        }

        public static bool CheckMesApiIsOk(string OpName, string EngineID, string apiName)
        {
            string procedureName;
            procedureName = "MOM_接口_Moby_执行状态_查询";
            SqlParameter[] thisParms = new SqlParameter[3];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@产品编号", EngineID);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OpName);
            thisParms[2] = new System.Data.SqlClient.SqlParameter("@接口名称", apiName);

            DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out DataTable dt);
            if(dt.Rows.Count > 0)
            {
                int result = Convert.ToInt32(dt.Rows[0]["result"]);
                if (result != 2) return true;
                else
                {
                    string msg = $"产品{EngineID}未成功入站 请成功入站后再操作";
                    SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg, "扫码校验");
                    MisDataFun.LogRecording_OP(OpName, "WARNING", "MOM", msg);
                    return false;
                }
            }
            return false;
        }

        /// <summary>
        /// 写入 保存完成和工作完成 并且对此进行一定判断校验
        /// </summary>
        /// <param name="isOver"></param>
        public static void WriteMesReadOver(string OpName, bool isOver)
        {
            if (isOver)
            {
                MIS_BASE.Read_WorkStart(OpName, out bool isWorkStart);
                if (!isWorkStart)
                {
                    MisDataFun.LogRecording_OP(OpName, "WARNING", "WriteMesReadOver", "产品未在位 不予写入工作完成");
                    return;
                }
                MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", "MES保存数据完成！");
                MisDataFun.LogRecording_OP(OpName, "INFO", "MIS", "MES工作完成！");
            }
            else
            {
                MIS_BASE.Write_FalseGO(OpName, false); // 不合格放行（MES）
                MIS_BASE.Write_ConfirmOkGo(OpName, false); // 合格放行（MES）
            }
            //通知PLC，MES工作完成
            MIS_BASE.Write_MesWorkFinish(OpName, isOver);
            //通知PLC，MES保存完成
            MIS_BASE.Write_MesReadOver(OpName, isOver);
        }

        /// <summary>
        /// 上盖装配新产品 根据工位扫码 写入产品信息至PLC
        /// </summary>
        /// <param name="OpName"></param>
        /// <param name="BarCode"></param>
        /// <returns></returns>
        public static bool WriteEngineDataByEngineID(string OpName, string BarCode)
        {
            string procedureName;
            procedureName = "生产计划_派工订单_执行列表_获取产品信息";
            SqlParameter[] thisParms = new SqlParameter[2];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@BarCode", BarCode);

            DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out DataTable dt);
            if (dt.Rows.Count > 0)
            {
                // 写入产品信息 并且默认为扫描托盘码完成
                string EngineID = dt.Rows[0]["发动机号"].ToString();
                int EngineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]);
                string EngineType = dt.Rows[0]["产品型号"].ToString();
                string OrderForm = dt.Rows[0]["订单号"].ToString();
                MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); // 机型代码（MES）
                MIS_BASE.Write_EngineID_MES(OpName, EngineID); // 发动机号（MES）
                MIS_BASE.Write_EngineType_MES(OpName, EngineType); // 机型（MES）
                MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); // 订单号（MES）
                MIS_BASE.Write_MachineTime_ReadOver(OpName, true); // 托盘信息校验成功
                MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); // 传递机型（MES）
                return true;
            }
            string msg = $"无 {BarCode} 对应产品 请确认产品编码是否正确";
            SendMessageFun.AsyncSendMessage_Notice_Error(OpName, msg, "扫码校验");
            MisDataFun.LogRecording_OP(OpName, "WARNING", "MOM", msg);
            return false;
        }
    }
}
