using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace MesWork.Pages
{
    /// <summary>
    /// 日志查询页面 — 现代化风格，统一 CRUD 模块设计
    /// 直接查询 [记录_日志_项目运行日志] 表
    /// </summary>
    public partial class UC_LogRecord : UserControl
    {
        private const string KEYWORD_HINT = "关键字搜索...";

        public UC_LogRecord()
        {
            InitializeComponent();
            InitColumns();
            InitFilterData();
            // 绑定数据完成后自动着色
            dgv_Data.DataBindingComplete += dgv_Data_DataBindingComplete;
        }

        private void InitColumns()
        {
            dgv_Data.AutoGenerateColumns = false;
            dgv_Data.Columns.Clear();
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "AID", HeaderText = "AID", DataPropertyName = "AID", Visible = false });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "工位号", HeaderText = "工位号", DataPropertyName = "工位号", FillWeight = 70 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "类型", HeaderText = "类型", DataPropertyName = "类型", FillWeight = 70 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "请求时间", HeaderText = "请求时间", DataPropertyName = "请求时间", FillWeight = 100 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "请求内容", HeaderText = "请求内容", DataPropertyName = "请求内容", FillWeight = 200 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "响应时间", HeaderText = "响应时间", DataPropertyName = "响应时间", FillWeight = 100 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "响应内容", HeaderText = "响应内容", DataPropertyName = "响应内容", FillWeight = 200 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "CMD", HeaderText = "CMD", DataPropertyName = "CMD", FillWeight = 60 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "FROM", HeaderText = "FROM", DataPropertyName = "FROM", FillWeight = 50 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "TO", HeaderText = "TO", DataPropertyName = "TO", FillWeight = 50 });
        }

        private void InitFilterData()
        {
            // 日志类型下拉
            cmb_Type.Items.Add("全部");
            foreach (var name in Enum.GetNames(typeof(Log_Type)))
                cmb_Type.Items.Add(name);
            cmb_Type.SelectedIndex = 0;

            // 日期范围
            dtp_End.Value = DateTime.Now.AddDays(1);
            dtp_Start.Value = DateTime.Now.AddDays(-3);

            // 搜索框事件
            txt_Keyword.GotFocus += (s, e) => { if (txt_Keyword.Text == KEYWORD_HINT) { txt_Keyword.Text = ""; txt_Keyword.ForeColor = Color.FromArgb(31, 41, 55); } };
            txt_Keyword.LostFocus += (s, e) => { if (string.IsNullOrWhiteSpace(txt_Keyword.Text)) { txt_Keyword.Text = KEYWORD_HINT; txt_Keyword.ForeColor = Color.FromArgb(156, 163, 175); } };
            txt_Keyword.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { btn_Query_Click(s, e); e.SuppressKeyPress = true; } };
        }

        // ====================================================================
        // 查询
        // ====================================================================

        private void btn_Query_Click(object sender, EventArgs e)
        {
            try
            {
                string sql = BuildQuerySql();
                DataLinkMesWork.SQLCommon.ExecuteDataTable(sql, MesWorkForm.ConnectionString, out DataTable dt, out string err);
                if (dt != null)
                {
                    dgv_Data.DataSource = dt;
                    lbl_RecordCount.Text = $"共 {dt.Rows.Count} 条记录";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 数据绑定完成后按日志类型着色（首次加载和每次查询都会触发）
        /// </summary>
        private void dgv_Data_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dgv_Data.Rows.Count; i++)
            {
                string typeStr = dgv_Data.Rows[i].Cells["类型"]?.Value?.ToString() ?? "";
                Color rowColor;
                switch (typeStr)
                {
                    case "ZK_Alarm":
                    case "ZK_Delete":
                        rowColor = Color.FromArgb(254, 226, 226); // 红底
                        break;
                    case "ZK_Login":
                        rowColor = Color.FromArgb(220, 252, 231); // 绿底
                        break;
                    case "ZK_Tip":
                        rowColor = Color.FromArgb(254, 249, 195); // 黄底
                        break;
                    default:
                        rowColor = (i % 2 == 0) ? Color.White : Color.FromArgb(248, 250, 252);
                        break;
                }
                dgv_Data.Rows[i].DefaultCellStyle.BackColor = rowColor;
            }
            dgv_Data.ClearSelection();
        }

        /// <summary>
        /// 导出 Excel（重新查询全量数据后导出）
        /// </summary>
        private void btn_Export_Click(object sender, EventArgs e)
        {
            if (dgv_Data.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出，请先查询", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            using (var sfd = new SaveFileDialog())
            {
                sfd.Filter = "Excel 文件|*.xlsx";
                sfd.FileName = $"运行日志_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        string sql = BuildQuerySql();
                        DataLinkMesWork.SQLCommon.ExecuteDataTable(sql, MesWorkForm.ConnectionString, out DataTable dt, out string err);

                        if (dt != null && dt.Rows.Count > 0)
                        {
                            bool exported = NPOITest.ExeclHelper.DataTableToExcel(dt, "运行日志", sfd.FileName);
                            if (exported)
                            {
                                MessageBox.Show($"导出成功！共 {dt.Rows.Count} 条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{sfd.FileName}\"");
                            }
                            else
                            {
                                MessageBox.Show("导出失败，请检查文件是否被占用", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("查询数据失败，请重试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        /// <summary>
        /// 根据当前筛选条件构建日志查询SQL（查询和导出共用）
        /// </summary>
        private string BuildQuerySql(bool includeAID = true)
        {
            var start = dtp_Start.Value;
            var end = dtp_End.Value;
            string keyword = txt_Keyword.Text == KEYWORD_HINT ? "" : txt_Keyword.Text.Trim();
            string logType = cmb_Type.Text == "全部" ? "" : cmb_Type.Text;

            string where = $" AND [请求时间] >= '{start:G}' AND [请求时间] < '{end:yyyy-MM-dd 23:59:59}'";
            if (!string.IsNullOrEmpty(keyword))
                where += $" AND ([请求内容] LIKE '%{keyword}%' OR [响应内容] LIKE '%{keyword}%' OR [工位号] LIKE '%{keyword}%')";
            if (!string.IsNullOrEmpty(logType))
                where += $" AND [日志类型] = '{logType}'";

            string sql =
                " SELECT [工位号] '工位号'" +
                ",[日志类型] '类型'" +
                ",[请求时间] '请求时间'" +
                ",[请求内容] '请求内容'" +
                ",[响应时间] '响应时间'" +
                ",[响应内容] '响应内容'" +
                ",[请求CMD] 'CMD'" +
                ",[请求FROM] 'FROM'" +
                ",[请求TO] 'TO'" +
                (includeAID ? ",[AID] 'AID'" : "") +
                " FROM [记录_日志_项目运行日志]" +
                " WHERE 1=1 " + where +
                " ORDER BY [请求时间] DESC";
            return sql;
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            cmb_Type.SelectedIndex = 0;
            txt_Keyword.Text = KEYWORD_HINT;
            txt_Keyword.ForeColor = Color.FromArgb(156, 163, 175);
            dtp_Start.Value = DateTime.Now.AddDays(-3);
            dtp_End.Value = DateTime.Now.AddDays(1);
            btn_Query_Click(sender, e);
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (Visible && dgv_Data.DataSource == null)
                btn_Query_Click(this, EventArgs.Empty);
        }
    }
}
