using DC_A95.MES_A95;
using NPOI.OpenXmlFormats.Dml;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using Opc.Ua;
using OpcBasic;
using Rhino.DocObjects;
using Rhino.Geometry;
using SlMesDbIterface;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SystemFramework;

/// <summary>
/// 
/// </summary>
namespace MesWork
{
    /// <summary>
    /// 操作数据库
    /// </summary>
    public class ExecuteDB
    {
        /// <summary>
        /// 报警开始
        /// </summary>
        /// <param name="opName"></param>
        /// <param name="alarming"></param>
        public static void Alarm_Start(string opName,int[] alarming)
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_Alarm_Start";

            for (int i = 0; i < alarming.Length ; i++)
            {
                var alarmCode = alarming[i];
                var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opName),
                 new SqlParameter("@AlarmCode", alarmCode),
                 new SqlParameter("@ChangeTime", ChangeTime)
                };
                SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);
            }

        }
        /// <summary>
        /// 报警结束
        /// </summary>
        /// <param name="opName"></param>
        public static void Alarm_End(string opName)
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_Alarm_End";

            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opName),
                 new SqlParameter("@ChangeTime", ChangeTime)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);

        }
        /// <summary>
        /// 安东开始
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="alarmCode">变量类型代码</param>
        public static void Alarm_Andon_Start(string opCode, int alarmCode)
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_Alarm_Andon_Start";

            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opCode),
                 new SqlParameter("@AlarmCode", alarmCode),
                 new SqlParameter("@ChangeTime", ChangeTime)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);

        }
        /// <summary>
        /// 安东结束
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="alarmCode"></param>
        public static void Alarm_Andon_End(string opCode, int alarmCode)
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_Alarm_Andon_End";

            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opCode),
                 new SqlParameter("@AlarmCode", alarmCode),
                 new SqlParameter("@ChangeTime", ChangeTime)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);

        }
       
        /// <summary>
        /// 安东确认
        /// </summary>
        /// <param name="opName"></param>
        /// <param name="alarmCode"></param>
        public static void Alarm_Andon_Sure(string opName, int alarmCode)
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_Alarm_Andon_Sure";

            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opName),
                 new SqlParameter("@AlarmCode", alarmCode),
                 new SqlParameter("@ChangeTime", ChangeTime)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);

        }
        public static DataTable Get_TaskTypeInfo()
        {
            var sql = $" SELECT [任务类型],[任务类型名称],[质量数据数量]" +
                $" ,[数据名称1],[数据单位1],[数据名称2],[数据单位2],[数据名称3],[数据单位3],[数据名称4],[数据单位4]" +
                $" FROM [配方_大柴_任务类型]";
            SqlOperation.ExecuteSql(sql, out DataTable dt, out string err);
            return dt;
        }

        public static void Save_StationPass_Info(string engineNo, string engineTypeNo, int palletNo, string orderNum, int orderNo,int orderSum,string processCode, string processName,
            string opCode, string opName, int passAttr, string opter, int QualityOk,int PassStatus, int upOrDown, int optFlag,string sortNo_PLC)
        {
            var weight = -1;

            var P_name = "Event_MOM_过点数据";
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            SqlParameter[] Parameters ={
                    new SqlParameter("@发动机流水号",engineNo),
                    new SqlParameter("@机型号",engineTypeNo),
                    new SqlParameter("@托盘号",palletNo),
                    new SqlParameter("@订单号",orderNum),
                    new SqlParameter("@订单序号",orderNo),
                    new SqlParameter("@订单数量",orderSum),
                    new SqlParameter("@工序编码",processCode),
                    new SqlParameter("@工序名称", processName),
                    new SqlParameter("@工位编码",opCode),
                    new SqlParameter("@工位名称",opName),
                    new SqlParameter("@过点属性",passAttr),
                    new SqlParameter("@采集时间",ChangeTime),
                    new SqlParameter("@操作者",opter),
                    new SqlParameter("@合格标志",QualityOk),
                    new SqlParameter("@过站状态",PassStatus),
                    new SqlParameter("@岔道上下件",upOrDown),
                    new SqlParameter("@重量",weight),
                    new SqlParameter("@操作标记",optFlag),
                    new SqlParameter("@机型标志",sortNo_PLC)
                };
            SqlOperation.ExecuteStoredProcedure(P_name, Parameters, out string err);
            if (err.Length > 0)
            {
                LogRecord.LogRecord.Insert_Log(Type_Log.Alarm, "", $"Save_StationPass_Info 报错！，，{err}");
            }
        }
        /// <summary>
        /// 增加：测量数据索引
        /// </summary>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="engineTypeNo"></param>
        /// <param name="engineNo"></param>
        /// <param name="opCode"></param>
        /// <param name="orderNum"></param>
        /// <param name="palletNo"></param>
        /// <param name="QCDataCount"></param>
        /// <param name="Operator"></param>
        /// <param name="QuaulityFlag"></param>
        /// <param name="Id_tagCF"></param>
        public static void Save_MeasureData_Index(int tagTypeCodeID, string engineTypeNo, string engineNo,string opCode,string orderNum, int palletNo,int QCDataCount, string Operator, int QuaulityFlag, out int Id_tagCF)
        {
            var P_name = "测量数据合格索引_增加";
            Id_tagCF = 0;
            SqlParameter[] thisParms = new SqlParameter[10];
            thisParms[0] = new SqlParameter("@TagID_CF", tagTypeCodeID);
            thisParms[1] = new SqlParameter("@EngineType", engineTypeNo);
            thisParms[2] = new SqlParameter("@EngineID", engineNo);
            thisParms[3] = new SqlParameter("@工位号", opCode);
            thisParms[4] = new SqlParameter("@订单号", orderNum);
            thisParms[5] = new SqlParameter("@托盘编号", palletNo);
            thisParms[6] = new SqlParameter("@质量数据数量", QCDataCount);
            thisParms[7] = new SqlParameter("@操作者工号", Operator);
            thisParms[8] = new SqlParameter("@合格标志", QuaulityFlag);
            thisParms[9] = new SqlParameter("@Id_tagCF", Id_tagCF);
            thisParms[9].Direction = ParameterDirection.Output;

            if(SqlOperation.ExecuteStoredProcedure(P_name, thisParms, out string err))
            {
                Id_tagCF=Convert.ToInt32(thisParms[9].Value.ToString());
            }
            else
            {
                Id_tagCF = -1;
            }
        }
         



















        /// <summary>
        /// 即时参数存储
        /// </summary>
        /// <param name="opName"></param>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="value"></param>
        /// <param name="tagID"></param>
        public static void Update_ImmediateParam(string opName, int tagTypeCodeID, string value, string tagID)
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_MES_工位_即时参数_变化";

            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@工位号", opName),
                 new SqlParameter("@变量类型代码",tagTypeCodeID ),
                 new SqlParameter("@值",value),
                 new SqlParameter("@更新时间", ChangeTime),
                 new SqlParameter("@TagID", tagID),
                 new SqlParameter("@开始时间", ChangeTime),
                 new SqlParameter("@结束时间", ChangeTime),
                 new SqlParameter("@持续时间", 0)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);
        }

        /// <summary>
        /// 设备状态变化
        /// </summary>
        /// <param name="opName"></param>
        /// <param name="tagTypeCodeID"></param>
        /// <param name="value"></param>
        /// <param name="tagID"></param>
        /// <param name="deviceMode"></param>
        public static void Event_StationStatus_Changed(string opName, string manual, string running, string alarm, string onLine = "1")
        {
            var ChangeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var name = "Event_StationStatus_Changed";

            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@工位号", opName),
                 new SqlParameter("@手动模式", manual),
                 new SqlParameter("@运行中",running ),
                 new SqlParameter("@报警",alarm),
                 new SqlParameter("@在线",onLine),
                 new SqlParameter("@更新时间", ChangeTime)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataSet ds, out string error);

        }








        /// <summary>
        /// 保存布局
        /// </summary>
        /// <param name="stationName"></param>
        /// <param name="px"></param>
        /// <param name="py"></param>
        public static void SaveLyout_P(string stationName, int px, int py)
        {
            var sql =
             $" UPDATE [MES_计划BOM_工位与名称] SET [PX] = {px},[PY] = {py}" +
             $" WHERE [工位号] = '{stationName}'";
            SqlOperation.ExecuteSql(sql, out string error);
        }
        /// <summary>
        /// 保存布局
        /// </summary>
        /// <param name="stationName"></param>
        /// <param name="pxt"></param>
        /// <param name="pyt"></param>
        public static void SaveLyout_PT(string stationName, int pxt, int pyt)
        {
            var sql =
             $" UPDATE [MES_计划BOM_工位与名称] SET [PX_T] = {pxt},[PY_T] = {pyt}" +
             $" WHERE [工位号] = '{stationName}'";
            SqlOperation.ExecuteSql(sql, out string error);
        }





        /// <summary>
        /// 查询工位信息
        /// </summary>
        /// <param name="dt"></param>
        public static void Select_Station(out DataTable dt)
        {
            var sql =
             $" SELECT [工位号],[工位名称],[PLC],[PLC代码]," +
             $"ISNULL([PX],0) AS PX,ISNULL([PY],0) AS PY,ISNULL([PX_T],0) AS PX_T,ISNULL([PY_T],0) AS PY_T,[控件启用]" +
             $" ,[区域代码]" +
             $" FROM [MES_计划BOM_工位与名称] WHERE [是否启用MES] = 1" + // AND [ProgramPartial] = {MesWorkForm.ProgramPartial}
             $" ORDER BY [工位号]"; 
            SqlOperation.ExecuteSql(sql, out dt, out string error);
        }
















        /// <summary>
        /// 检查上线的发动机流水号是否重复
        /// </summary>
        /// <param name="dt"></param>
        public static void Check_Repeat_LineSet(string opcode, string engineNo, out bool ifrepeat)
        {
            ifrepeat = false;
            var sql = $" SELECT count(AID) FROM [大柴_过点信息] where 工位编码='{opcode}' and 发动机流水号='{engineNo}'";
            SqlOperation.ExecuteSql(sql, out DataTable dt, out string error);
            if (int.Parse(dt.Rows[0][0].ToString()) > 0) ifrepeat = true;
        }
        public static void Save_ScanRecord_outLineSet(string opCode, string engineNo, string ActualNumber,string Decode_Result)
        {
            //保存扫码记录
            string sql = $@"INSERT INTO[MES_装配数据_零部件扫码记录]([工位号],[发动机流水号],[ActualNumber],[Decode_Result],[MaterialCode], Scanner_No,[操作时间])
                VALUES('{opCode}', {engineNo}, '{ActualNumber}', '{Decode_Result}', '{engineNo}', 1, getdate())";
            SqlOperation.ExecuteSql(sql,out string error);
        }
        public static void Get_EngineInfo_OutSide(int AGVCode,out string EngineNo,out int EngineTypeID,out string EngineType,out string OrderNum)
        {
            //根据agvcode获取发动机信息
            string sql = $@"SELECT TOP (1)[发动机流水号],[大机型ID],[机型号],[工单号] FROM [大柴_上线记录_外装线] 
                where AGV号={AGVCode} and 外装线绑定状态=1 and [发动机流水号]<>'' order by 操作时间 desc";
            SqlOperation.ExecuteSql(sql,out DataTable dt,out string error);
            if(dt.Rows.Count==1)
            {
                EngineNo = dt.Rows[0]["发动机流水号"].ToString();
                EngineTypeID = int.Parse(dt.Rows[0]["大机型ID"].ToString());
                EngineType = dt.Rows[0]["机型号"].ToString();
                OrderNum = dt.Rows[0]["工单号"].ToString();

            }
            else
            {
                EngineNo = "";
                EngineTypeID = 0;
                EngineType = "";
                OrderNum = "";
            }
        }

        /// <summary>
        /// 内装线上线工位：请求下载
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="partCode"></param>
        /// <param name="palletNo"></param>
        /// <param name="engineNo"></param>
        /// <param name="sortNo"></param>
        /// <param name="sortName"></param>
        /// <param name="printCode"></param>
        /// <param name="orderNo"></param>
        public static void Select_OnLine_Plan_Engine(string opCode,string partCode, int palletNo
            , out string engineNo
            , out int sortNo
            , out string sortName
            , out string printCode
            , out string orderNo
            , out int errCode
            , out string errMessage
            , out int printPosition

          )
        {
            engineNo = "";
            sortNo = 0;
            sortName = "";
            printCode = "";
            orderNo = "";
            errCode = 0;
            errMessage = "";
            printPosition = 0;

            var name = "Event_Query_上线发动机数据";
            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opCode),
                 new SqlParameter("@PartCode",partCode ),
                 new SqlParameter("@PalletNo",palletNo )
            };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out DataTable dt, out string error);
            if (dt.Rows.Count > 0)
            {
                engineNo = dt.Rows[0]["发动机编号"].ToString();
                sortNo = int.Parse(dt.Rows[0]["机型ID"].ToString());
                sortName = dt.Rows[0]["机型号"].ToString();
                printCode = dt.Rows[0]["缸体打印码"].ToString();
                orderNo = dt.Rows[0]["工单号"].ToString();

                errCode = Convert.ToInt32(dt.Rows[0]["Code"]);
                errMessage = dt.Rows[0]["Message"].ToString();
                printPosition = Convert.ToInt32(dt.Rows[0]["PrintPosition"]);
            }

        }

       
        /// <summary>
        /// 执行计划：成功上线的发动机，更新执行计划为2
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="engineNo"></param>
        public static void Update_ExcutePlan_LineSetOK(string opCode,string engineNo)
        {
            var name = "Event_执行计划_验证完成";
            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opCode),
                 new SqlParameter("@EngineNo", engineNo)
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters,out DataTable dt,out string err);
            if (err.Length > 0)
            {
                LogRecord.LogRecord.Insert_Log(Type_Log.Alarm, "", $"Update_ExcutePlan_LineSetOK 报错！，，{err}");
            }

        }


        public static void Event_OutSide_OnLine(string opCode, string engineNo, int engineTypeID, int orderNo, string engineTypeCode, int agvCode)
        {
            var name = "Event_OutSide_OnLine";
            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opCode),
                 new SqlParameter("@EngineNo", engineNo),
                 new SqlParameter("@EngineTypeNo",engineTypeID),
                 new SqlParameter("@OrderNo",orderNo ),
                 new SqlParameter("@EngineTypeCode",engineTypeCode),
                 new SqlParameter("@AgvCode",agvCode),
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out string error);
        }


        public static bool Event_QueryRecipes_ColdTest(string opCode, string sortNo, out DataTable dt)
        {
            var name = "Event_QueryRecipes_ColdTest";
            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@StationName", opCode),
                 new SqlParameter("@SortNo",sortNo),
                };
            return SqlOperation.ExecuteStoredProcedure(name, sqlParameters, out dt, out string error);
        }

    }
}
