using Model;
using PlcUiControl;
using PlcUiForm;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YangjieTester.主界面
{
    [FormDescriptionAttribute("历史记录")]
    public partial class HistoryDataForm : PlcBaseForm
    {
        public HistoryDataForm()
        {
            InitializeComponent();
        }
        private void HistoryDataForm_Load(object sender, EventArgs e)
        {
            dtpStart.Value = DateTime.Now.AddDays(-1);
            dtpEnd.Value = DateTime.Now;
            cob查询类型.SelectedIndex = 0;
            cob时间区间选择.SelectedIndex = 0;
        }

        private void cobDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cob时间区间选择.SelectedIndex == 0)
            {
                dtpStart.Value = DateTime.Now.AddHours(-1);
                dtpEnd.Value = DateTime.Now;
            }
            else if (cob时间区间选择.SelectedIndex == 1)
            {
                dtpStart.Value = DateTime.Now.AddDays(-1);
                dtpEnd.Value = DateTime.Now;
            }
            else if (cob时间区间选择.SelectedIndex == 2)
            {
                dtpStart.Value = DateTime.Now.AddMonths(-1);
                dtpEnd.Value = DateTime.Now;
            }
            else if (cob时间区间选择.SelectedIndex == 3)
            {
                dtpStart.Value = DateTime.Now.AddYears(-1);
                dtpEnd.Value = DateTime.Now;
            }
            btnQuery_Click(sender, e);
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取用户选择的时间范围

                DateTime startTime = dtpStart.Value;
                DateTime endTime = dtpEnd.Value;
                // 查询数据

                if (cob查询类型.SelectedIndex == 0)
                {
                    var alarmList = AlarmService.GetAlarmsByTimeRange(startTime, endTime)
                                    .Select((item, index) => { item.RowNumber = index + 1; return item; })
                                    .ToList();

                    // 绑定到 DataGridView
                    dgvHistoryData.DataSource = alarmList;
                    dgvHistoryData.Columns[0].Visible = false;
                    // 可选：调整列标题
                    dgvHistoryData.Columns["RowNumber"].HeaderText = "序号";
                    dgvHistoryData.Columns["Timestamp"].HeaderText = "时间";
                    if (dgvHistoryData.Columns["Timestamp"] != null)
                        dgvHistoryData.Columns["Timestamp"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss.fff";
                    dgvHistoryData.Columns["Username"].HeaderText = "用户";
                    dgvHistoryData.Columns["AlarmMessage"].HeaderText = "报警信息";
                    dgvHistoryData.Columns["AlarmType"].HeaderText = "类型";
                }
                if (cob查询类型.SelectedIndex == 1)
                {
                    var tipsDisplays = TipsService.GetTipsByTimeRange(startTime, endTime)
                                    .Select((item, index) => { item.RowNumber = index + 1; return item; })
                                    .ToList();


                    // 绑定到 DataGridView
                    dgvHistoryData.DataSource = tipsDisplays;
                    dgvHistoryData.Columns[0].Visible = false;
                    // 可选：调整列标题
                    dgvHistoryData.Columns["RowNumber"].HeaderText = "序号";
                    dgvHistoryData.Columns["Timestamp"].HeaderText = "时间";
                    if (dgvHistoryData.Columns["Timestamp"] != null)
                        dgvHistoryData.Columns["Timestamp"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss.fff";
                    dgvHistoryData.Columns["Username"].HeaderText = "用户";
                    dgvHistoryData.Columns["Message"].HeaderText = "提示信息";
                    dgvHistoryData.Columns["Type"].HeaderText = "类型";
                }
                else if (cob查询类型.SelectedIndex == 2)
                {
                    var operationRecords = OperationRecordService.GetOperationRecordByTimeRange(startTime, endTime)
                                    .Select((item, index) => { item.RowNumber = index + 1; return item; })
                                    .ToList();

                    // 绑定到 DataGridView
                    dgvHistoryData.DataSource = operationRecords;
                    dgvHistoryData.Columns[0].Visible = false;
                    // 可选：调整列标题
                    dgvHistoryData.Columns["RowNumber"].HeaderText = "序号";
                    dgvHistoryData.Columns["Timestamp"].HeaderText = "时间";
                    if (dgvHistoryData.Columns["Timestamp"] != null)
                        dgvHistoryData.Columns["Timestamp"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss.fff";
                    dgvHistoryData.Columns["Username"].HeaderText = "用户";
                    dgvHistoryData.Columns["OperationType"].HeaderText = "操作类型";
                    dgvHistoryData.Columns["ControlName"].HeaderText = "控件";
                    dgvHistoryData.Columns["OldValue"].HeaderText = "操作前的值";
                    dgvHistoryData.Columns["NewValue"].HeaderText = "操作后的值";
                    dgvHistoryData.Columns["Detail"].HeaderText = "详细信息";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnAdd_Click(object sender, EventArgs e)
        {
            List<Alarm> alarms = new List<Alarm>();
            for (int i = 0; i < 2; i++)
            {
                alarms.Add(new Alarm() { AlarmMessage = DateTime.Now.ToString(), AlarmType = AlarmType.Error, Timestamp = DateTime.Now });
            }
            //AlarmService.Log(new Alarm() { AlarmMessage = dtpStart.Value.ToString(), AlarmType = AlarmType.Error, Timestamp = dtpStart.Value }, AppSession.CurrentUser);
            AlarmService.LogBatch(alarms, AppSession.CurrentUser);
        }

        private void myUiButton1_Click(object sender, EventArgs e)
        {
            OperationRecord operationRecord = new OperationRecord()
            {
                Timestamp = DateTime.Now,
                OperationType = OperationType.ButtonSetValue,
                ControlName = "测试控件",
                OldValue = null,
                NewValue = "新值",
                Detail = "测试详细信息",

                User = AppSession.CurrentUser
            };
            OperationRecordService.Log(operationRecord);
        }

        private void cobQueryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cobDate_SelectedIndexChanged(null, null);
        }

        private void btn导出_Click(object sender, EventArgs e)
        {
            using (var saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "CSV 文件 (*.csv)|*.csv";
                saveFileDialog.FileName = "ExportData.csv";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        ExportData.ExportDataGridViewToCsv(dgvHistoryData, saveFileDialog.FileName);
                        MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
