using ExternalDataSync;
using MesWork;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

/// <summary>
/// 报警类型
/// </summary>
public enum Log_Type
{
    /// <summary>
    /// 报警
    /// </summary>
    ZK_Alarm = 1,
    /// <summary>
    /// 登录
    /// </summary>
    ZK_Login = 2,
    /// <summary>
    /// 提示
    /// </summary>
    ZK_Tip = 3,
    /// <summary>
    /// MES处理信号
    /// </summary>
    ZK_MesHandler = 4,
    /// <summary>
    /// 配方下载
    /// </summary>
    ZK_DownloadRecipes = 5,
    /// <summary>
    /// 发动机上线
    /// </summary>
    ZK_OnLine = 6,
    /// <summary>
    /// 发动机下线
    /// </summary>
    ZK_OffLine = 7,
    /// <summary>
    /// MES请求接口的日志
    /// </summary>
    ZK_Interface_MesReq = 8,

    /// <summary>
    /// 1.AGV 请求进入
    /// </summary>
    AGV_To_MES_agvCallback = 9,
    /// <summary>
    /// 删除
    /// 2025.11.25.0024.LLX
    /// </summary>
    ZK_Delete = 10,

    /// <summary>
    /// 未定义
    /// </summary>
    Undefined = 1000

}


public enum Log_FromAndTo
{
    /// <summary>
    /// PLC
    /// </summary>
    PLC = 3,
    /// <summary>
    /// AGV（海康威视）
    /// </summary>
    HK_AGV = 4,
    /// <summary>
    /// LES（启明）
    /// </summary>
    WMS = 5,
    /// <summary>
    /// AGV（临工）
    /// </summary>
    ZK = 10,
    /// <summary>
    /// 未定义
    /// </summary>
    Undefined = 1000
}


namespace LogRecord
{
    /// <summary>
    /// 日志处理
    /// </summary>
    public partial class LogRecord 
    {
        /// <summary>
        /// 构造
        /// </summary>
        public LogRecord()
        {
            InitializeComponent();
            //this.Width = _Width;
            //this.Height = _Height;
            cb_Type.DataSource = Enum.GetNames(typeof(Log_Type));
            cb_Type.Text = Log_Type.Undefined.ToString();
            cb_From.DataSource = Enum.GetNames(typeof(Log_FromAndTo));
            cb_From.Text = Log_FromAndTo.Undefined.ToString();
            cb_To.DataSource = Enum.GetNames(typeof(Log_FromAndTo));
            cb_To.Text = Log_FromAndTo.Undefined.ToString();

            cb_StationName.Items.Add("");
            foreach (var stationName in MesWorkForm.opNameList)
            {
                cb_StationName.Items.Add(stationName);
            }
            cb_StationName.SelectedIndex = 0;

            var end = System.DateTime.Now.AddDays(1);
            var start = end.AddDays(-3);
            dtp_Start.Value = start;
            dtp_End.Value = end;
       
        }

    
        /// <summary>
        /// 钩子
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogRecord_Load(object sender, EventArgs e)
        {
        }
      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <param name="color"></param>
        /// <param name="dgv"></param>
        private void RowsColor(int row, Color color, DataGridView dgv)
        {
            var dt = (System.Data.DataTable)dgv.DataSource;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dgv.Rows[row].Cells[i].Style.BackColor = color;
            }
        }
      
        public static bool Insert_ScanLog_EleCraft(Log_Type LogType,string stationName, string Log_Content)
        {
            bool success = false;
            var sql =
$" INSERT INTO [记录_日志_扫码发送电子工艺]([Log_Station],[Log_Type],[Log_Time],[Log_Content])" +
$" VALUES('{stationName}','{LogType.ToString()}',getdate(),'{Log_Content}')";
            success = DataLinkMesWork.SQLCommon.ExecuteSql(sql, MesWorkForm.ConnectionString, out string err2);

            return success;
        }
   
       
        /// <summary>
        /// 手动刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            try
            {
                var start = dtp_Start.Value;
                var end = dtp_End.Value;
                var stationName = cb_StationName.Text;
                var type = (Log_Type)Enum.Parse(typeof(Log_Type), cb_Type.Text);
                var taskID = txt_TaskID.Text;

                var from = (Log_FromAndTo)Enum.Parse(typeof(Log_FromAndTo), cb_From.Text);
                var to = (Log_FromAndTo)Enum.Parse(typeof(Log_FromAndTo), cb_To.Text);
                var req = txt_Req.Text;
                var rsp = txt_Rsp.Text;

                var whereStr = "";
                if (start != null & end != null)
                {
                    whereStr = whereStr + $" AND [请求时间] >= '{start.ToString("G")}' AND [请求时间] < '{end.ToString("yyyy-MM-dd 23:59:59")}'";
                }

                if (!string.IsNullOrEmpty(stationName) && !string.IsNullOrEmpty(req))
                {
                    whereStr = whereStr + $" AND ([工位号] = '{stationName}' OR [请求内容] like '%{req}%')";
                }
                else if (!string.IsNullOrEmpty(stationName))
                {
                    whereStr = whereStr + $" AND [工位号] = '{stationName}'";
                }
                else if (!string.IsNullOrEmpty(req))
                {
                    whereStr = whereStr + $" AND [请求内容] like '%{req}%'";
                }

                if (type != Log_Type.Undefined)
                {
                    whereStr = whereStr + $" AND [日志类型] = '{type.ToString()}'";
                }
                if (!string.IsNullOrEmpty(taskID))
                {
                    whereStr = whereStr + $" AND [TaskID] like '%{taskID}%'";
                }
                if (from != Log_FromAndTo.Undefined)
                {
                    whereStr = whereStr + $" AND [请求FROM] like '%{from}%'";
                }
                if (to != Log_FromAndTo.Undefined)
                {
                    whereStr = whereStr + $" AND [请求TO] like '%{to}%'";
                }
                if (!string.IsNullOrEmpty(rsp))
                {
                    whereStr = whereStr + $" AND [响应内容] like '%{rsp}%'";
                }


                var sql =
    $" SELECT " +
    $"  [工位号] '工位号'" +
    $" ,[日志类型] '类型'" +
    $" ,[请求时间] '请求时间'" +
    $" ,[请求内容] '请求内容'" +
    $" ,[响应时间] '响应时间'" +
    $" ,[响应内容] '响应内容'" +

    $" ,[请求CMD] 'CMD'" +
    $" ,[请求FROM] 'FROM'" +
    $" ,[请求TO] 'TO'" +
    $" ,[TaskID] 'TaskID'" +
    $" ,[AID] 'AID'" +

    $" FROM [记录_日志_项目运行日志]" +
    $" WHERE 1=1 {whereStr}" +
    $" ORDER BY [请求时间] DESC";
                DataLinkMesWork.SQLCommon.ExecuteDataTable(sql, MesWorkForm.ConnectionString, out DataTable dt, out string err2);
                label_Count.Text = $"消息数量：{dt.Rows.Count}";
                dgv_Log.DataSource = dt;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //  Log_Type LogType = Log_Type.Undefined;
                    var LogTypeStr = "";
                    try
                    {
                        LogTypeStr = dt.Rows[i]["类型"].ToString();
                       // LogType = (Log_Type)Enum.Parse(typeof(Log_Type), LogTypeStr);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show($"填充日志类型，类型转换出错！{err.Message}");
                        break;
                    }
                    switch (LogTypeStr)
                    {
                        case "ZK_Alarm":
                        case "ZK_Delete":
                            RowsColor(i, MesWorkForm.color_Red, dgv_Log);
                            break;
                        case "ZK_Login":
                            RowsColor(i, MesWorkForm.color_Green, dgv_Log);
                            break;
                        case "ZK_Tip":
                            RowsColor(i, MesWorkForm.color_Yellow, dgv_Log);
                            break;
                        default:
                            RowsColor(i, MesWorkForm.color_Grey, dgv_Log);
                            break;
                    }
                }
                dgv_Log.ClearSelection();
                //dgv_Log.CurrentCell = null;
                //dgv_Log.Rows[0].Selected = false;

            }
            catch (Exception err)
            {
                MessageBox.Show($"点击查询按钮产生的未预知错误：【{err.Message }】------{err.StackTrace}");
            }
        }


        private void dgv_Log_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var AID = dgv_Log.CurrentRow.Cells["AID"].Value.ToString();

                var sql = $"SELECT [请求内容安全] FROM [记录_日志_项目运行日志] WHERE [AID] = '{AID}'";
                DataLinkMesWork.SQLCommon.ExecuteDataTable(sql, MesWorkForm.ConnectionString, out DataTable dt, out string err2);
                var reqStrSafe = dt.Rows[0][0].ToString();
                var reqStr = dgv_Log.CurrentRow.Cells["请求内容"].Value.ToString();
                txt_RequestContext_3.Text = reqStr;
                txt_ResponseContext_3.Text = dgv_Log.CurrentRow.Cells["响应内容"].Value.ToString();
            }
            catch (Exception err)
            {
            }
        }

     
    }
}
            