using ExternalDataSync;
using MesWork;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SlMesDbIterface;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Configuration.ConfigurationManager;
/// <summary>
/// 报警类型
/// </summary>
public enum Type_Log
{
    /// <summary>
    /// 报警
    /// </summary>
    Alarm = 1,
    /// <summary>
    /// 登录
    /// </summary>
    Login = 2,
    /// <summary>
    /// 提示
    /// </summary>
    Tip = 3,
    /// <summary>
    /// 操作（生产计划、点按钮操作）
    /// </summary>
    Operation = 4,
    /// <summary>
    /// MES处理信号
    /// </summary>
    MesHandler = 5,
    /// <summary>
    /// 配方下载
    /// </summary>
    RecipesDownload = 6,
    /// <summary>
    /// 发动机上线
    /// </summary>
    OnLine = 7,
    /// <summary>
    /// 发动机下线
    /// </summary>
    OffLine = 8,
    /// <summary>
    /// MES请求接口的日志
    /// </summary>
    Interface_MesReq = 9,
    /// <summary>
    /// MES请求接口的日志
    /// </summary>
    RecipesDownload_ColdTest = 10,
    /// <summary>
    /// 
    /// </summary>
    Undefined = 1000

}
namespace LogRecord
{
    /// <summary>
    /// 日志处理
    /// </summary>
    public partial class LogRecord : Form
    {
        /// <summary>
        /// 构造
        /// </summary>
        public LogRecord()
        {
            InitializeComponent();
            //this.WindowState = FormWindowState.Maximized;
        }
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="_Width"></param>
        /// <param name="_Height"></param>
        public LogRecord(int _Width,int _Height)
        {
            InitializeComponent();
            //this.Width = _Width;
            //this.Height = _Height;
            cb_Type.DataSource = Enum.GetNames(typeof(Type_Log));
            cb_Type.Text = Type_Log.Undefined.ToString ();
            cb_StationName.Items.Add("");
            cmb_StationNames_WebAPI.Items.Add("");
            foreach (var stationName in MesWorkForm.opNameList)
            {
                cb_StationName.Items.Add(stationName);
                cmb_StationNames_WebAPI.Items.Add(stationName);
            }
            cb_StationName.SelectedIndex = 0;
            cmb_StationNames_WebAPI.SelectedIndex = 0;

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

            dtpicker_end.Value = DateTime.Now.AddDays(1);
            dtpicker_start.Value = DateTime.Now.AddDays(-3);
            dt_End.Value = DateTime.Now.AddDays(1);
            dt_Start.Value = DateTime.Now.AddDays(-1);
            WebAPI_LogType_Binding();
        }
        private void WebAPI_LogType_Binding()
        {
            var sql = "SELECT [请求CMD] FROM [历史_WebApi接口传递数据日志] group by [请求CMD] order by [请求CMD]";
            SqlOperation.ExecuteSql(sql, out DataTable dt, out string error);
            DataRow irow = dt.NewRow();
            irow[0] = "";
            dt.Rows.InsertAt(irow, 0);
            cmb_RequestCMD.ValueMember = "请求CMD";
            cmb_RequestCMD.DisplayMember= "请求CMD";
            cmb_RequestCMD.DataSource = dt;
            
        }
        /// <summary>
        /// 钩子
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogRecord_Load(object sender, EventArgs e)
        {
            var start = dtp_Start.Value;
            var end = dtp_End.Value;

            Refresh_Log(Type_Log.Undefined,"", start, end);
        }
        /// <summary>
        /// 刷新日志的显示
        /// </summary>
        private void Refresh_Log(Type_Log type, string stationName, DateTime start, DateTime end)
        {
            var dt = Select_Log(type, stationName, start, end);
            dgv_Log.DataSource = dt;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var 类型 = (Type_Log)Enum.Parse(typeof(Type_Log),dt.Rows[i]["类型"].ToString());
                switch (类型)
                {
                    case Type_Log.Alarm:
                        RowsColor(i, MesWorkForm.color_Red, dgv_Log);
                        break;
                    case Type_Log.Login:
                        RowsColor(i, MesWorkForm.color_Green, dgv_Log);
                        break;
                    case Type_Log.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;
        }
        /// <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;
            }
        }
        /// <summary>
        /// 增加日志
        /// </summary>
        /// <param name="LogType"></param>
        /// <param name="Log_Content"></param>
        /// <returns></returns>
        public static bool Insert_Log(Type_Log 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;

        }
        public static bool Insert_ScanLog_EleCraft(Type_Log 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>
        /// <returns></returns>
        public static DataTable Select_Log(Type_Log type,string stationName,DateTime start,DateTime end)
        {
            var whereStr = "";
            if (type != Type_Log.Undefined)
            {
                whereStr = whereStr + $" AND [Log_Type] = '{type.ToString()}'";
            }
            if (stationName != "")
            {
                whereStr = whereStr + $" AND [Log_Station] = '{stationName}'";
            }
            if (start != null & end != null) 
            {
                whereStr = whereStr + $" AND [Log_Time] >= '{start.ToString("G")}' AND [Log_Time] < '{end.ToString("G")}'";
            }
            var sql =
$" SELECT " +
$"  [Log_Time] AS 时间" +
$" ,[Log_Station] AS 工位号" +
$" ,[Log_Type] AS 类型" +
$" ,[Log_Content] AS 内容" +

$" FROM [记录_日志_运行日志]" +
$" WHERE 1=1 {whereStr}" +
$" ORDER BY [Log_Time] DESC";
            DataLinkMesWork.SQLCommon.ExecuteDataTable(sql, MesWorkForm.ConnectionString,out DataTable dt, out string err2);
            return dt;

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

            Refresh_Log(type, stationName, start,end);
        }

        private void btn_WebAPILog_Query_Click(object sender, EventArgs e)
        {
            var wherestr = $"WHERE [请求时间]>='{dtpicker_start.Value}' AND [请求时间]<='{dtpicker_end.Value}'";
            if (cmb_RequestCMD.Text.Trim() != "") wherestr += $" AND [请求CMD]='{cmb_RequestCMD.Text.Trim()}'";
            if(cmb_StationNames_WebAPI.Text.Trim()!="") wherestr += $" AND [请求内容] LIKE '%{cmb_StationNames_WebAPI.Text.Trim()}%'";

            var sql = $"SELECT Top(500) [TaskID],[请求CMD],[请求FROM],[请求时间],[请求内容],[响应时间],[响应内容] FROM [历史_WebApi接口传递数据日志] {wherestr}";
            sql += " ORDER BY [请求时间] DESC";
            SqlOperation.ExecuteSql(sql, out DataTable dt, out string error);
            dgv_WebApiLog.DataSource = dt;
            dgv_WebApiLog.Columns["请求时间"].ValueType = typeof(DateTime);
            dgv_WebApiLog.Columns["请求时间"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dgv_WebApiLog.Columns["响应时间"].ValueType = typeof(DateTime);
            dgv_WebApiLog.Columns["响应时间"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
        }

        private void dgv_WebApiLog_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                txt_RequestContext.Text = dgv_WebApiLog.CurrentRow.Cells["请求内容"].Value.ToString();
                txt_ResponseContext.Text = dgv_WebApiLog.CurrentRow.Cells["响应内容"].Value.ToString();
                try
                {
                    var _msgRequest = JsonConvert.DeserializeObject<JObject>(txt_RequestContext.Text);
                    if (_msgRequest["content"] != null) txt_Key_TaskCodeOrOPName.Text = _msgRequest["content"]["taskCode"].ToString();
                    else if (_msgRequest["WorkCellCode"] != null) txt_Key_TaskCodeOrOPName.Text = _msgRequest["WorkCellCode"].ToString();
                    else txt_Key_TaskCodeOrOPName.Text = "";
                }
                catch (Exception)
                {
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        private void LogRecord_Resize(object sender, EventArgs e)
        {
            tabControl_LogQuery.Width = this.Width-20;
            tabControl_LogQuery.Height= this.Height-45;

            dgv_Log.Width= tabControl_LogQuery.Width - 44;
            dgv_Log.Height = tabControl_LogQuery.Height - 117;

            dgv_WebApiLog.Width = tabControl_LogQuery.Width - 501;
            dgv_WebApiLog.Height = tabControl_LogQuery.Height - 116;
            txt_RequestContext.Left = txt_ResponseContext.Left= label10.Left = label9.Left = tabControl_LogQuery.Width-459;

            dg_WebAPI_And_RunLog.Width = tabControl_LogQuery.Width - 501;
            dg_WebAPI_And_RunLog.Height = tabControl_LogQuery.Height - 116;
            txt_RequestContext_3.Left = txt_ResponseContext_3.Left= label11.Left = label12.Left = tabControl_LogQuery.Width-459;
        }

        private void btn_QueryALL_Click(object sender, EventArgs e)
        {
            var name = "大柴_日志查询_TaskCode";
            var sqlParameters = new SqlParameter[] {
                 new SqlParameter("@TaskCode", this.txt_Key_TaskCodeOrOPName.Text.Trim()),
                 new SqlParameter("@StartTime",dt_Start.Value),
                 new SqlParameter("@EndTime",dt_End.Value),
                };
            SqlOperation.ExecuteStoredProcedure(name, sqlParameters,out DataTable dt, out string error);
            dg_WebAPI_And_RunLog.DataSource = dt;
            dg_WebAPI_And_RunLog.Columns["发生时间"].ValueType = typeof(DateTime);
            dg_WebAPI_And_RunLog.Columns["发生时间"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";

        }

        private void dg_WebAPI_And_RunLog_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            txt_RequestContext_3.Text = dg_WebAPI_And_RunLog.CurrentRow.Cells["请求内容"].Value.ToString();
            txt_ResponseContext_3.Text = dg_WebAPI_And_RunLog.CurrentRow.Cells["响应内容"].Value.ToString();

        }

        private void dgv_Log_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var workcell = dgv_Log.CurrentRow.Cells["工位号"].Value.ToString().Trim();
                txt_Key_TaskCodeOrOPName.Text= workcell;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
            