using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;
using SlnMesnac.Common;
using SlnMesnac.Config;
using SlnMesnac.Repository;
using SlnMesnac.Repository.service;
using SlnMesnac.WPF.Attribute;
using SlnMesnac.WPF.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using TouchSocket.Sockets;

namespace SlnMesnac.WPF.ViewModel.IndexPage
{
    [RegisterAsSingletonAttribute]
    public partial class HistorySearchViewModel : ObservableObject
    {
        private ILogger<HistorySearchViewModel> _logger;
        private AppsettingsConfig _appSettings = new AppsettingsConfig();
        public Action<Real_DataInfo> Action;
        public delegate void RefreshDataInfo(Real_DataInfo real_Data);
        private RealReadDataService dataService = RealReadDataService.Instance;


        public event RefreshDataInfo? RefreshDataInfoEvent;
        public HistorySearchViewModel()
        {
            GetOrderInfoCommand = new RelayCommand<object>(t=> RefreshData(t));
            ExportCommand = new RelayCommand<object>(t=> ExportData(t));
            BeginDate = DateTime.Now.Date;  // 当天的 0:00:00
            EndDate = DateTime.Now.Date.AddDays(2).AddSeconds(-1);  // 当天的 23:59:59
            RefreshHistoryData();
        }

        private async Task RefreshHistoryData()
        {
            try
            {
                await RefreshData(null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        public RelayCommand<object> GetOrderInfoCommand { get; set; }
        public RelayCommand<object> ExportCommand { get; set; }




        /// <summary>
        /// 从MES获取订单信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [RelayCommand]
        private async Task RefreshData(object? parameter)
        {

            string mesOrderNo = MesOrderNo;
            string rfidCount = RfidCount;
            DateTime dateTime = BeginDate;
            DateTime dateTime1 = EndDate;
            Expression<Func<real_readdata, bool>> exp = (real_readdata s1) => true;


            if (!string.IsNullOrEmpty(MesOrderNo.Trim()))
            {
                exp = exp.And(x => x.orderno == mesOrderNo);
            }

            if (!string.IsNullOrEmpty(QueryIsCheck.Content.ToString().Trim()))
            {
                exp = exp.And(x => x.writestatus == QueryIsCheck.Content.ToString());
            }

            //查询记录
            List<real_readdata> real_readdataInfos = dataService.Helper.Query(exp);
            if (real_readdataInfos.Count > 0)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    realreaddata.Clear();
                    foreach (var item in real_readdataInfos)
                    {
                        realreaddata.Insert(0, item);
                    }
                });
            }
            else
            {
                realreaddata.Clear();
            }

        }

        /// <summary>
        /// 导出订单信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [RelayCommand]
        private async Task ExportData(object? parameter)
        {
            try
            {
                // 代码方式配置
                ExcelPackage.License.SetNonCommercialPersonal("provate");//个人

                if (realreaddata == null || realreaddata.Count == 0)
                {
                    MessageBox.Show("没有可导出的数据！");
                    return;
                }

                // 选择保存路径
                var dialog = new SaveFileDialog
                {
                    Filter = "Excel文件 (*.xlsx)|*.xlsx",
                    FileName = $"订单数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                };

                if (dialog.ShowDialog() != DialogResult.OK)
                    return;

                using (var package = new ExcelPackage())
                {
                    var sheet = package.Workbook.Worksheets.Add("Sheet1");

                    // ===== 表头 =====
                    sheet.Cells[1, 1].Value = "ID";
                    sheet.Cells[1, 2].Value = "订单号";
                    sheet.Cells[1, 3].Value = "产线";
                    sheet.Cells[1, 4].Value = "产品类型";
                    sheet.Cells[1, 5].Value = "RFID EPC";
                    sheet.Cells[1, 6].Value = "RFID ASCII";
                    sheet.Cells[1, 7].Value = "读取时间";
                    sheet.Cells[1, 8].Value = "写入时间";
                    sheet.Cells[1, 9].Value = "写入状态";
                    sheet.Cells[1, 10].Value = "序列号";

                    // 表头加粗
                    using (var range = sheet.Cells[1, 1, 1, 10])
                    {
                        range.Style.Font.Bold = true;
                    }

                    // ===== 数据 =====
                    int row = 2;
                    foreach (var item in realreaddata)
                    {
                        sheet.Cells[row, 1].Value = item.objid;
                        sheet.Cells[row, 2].Value = item.orderno;
                        sheet.Cells[row, 3].Value = item.lineno;
                        sheet.Cells[row, 4].Value = item.producttype;
                        sheet.Cells[row, 5].Value = item.rfidepc;
                        sheet.Cells[row, 6].Value = item.rfidascii;
                        sheet.Cells[row, 7].Value = item.readtime?.ToString("yyyy-MM-dd HH:mm:ss");
                        sheet.Cells[row, 8].Value = item.writetime?.ToString("yyyy-MM-dd HH:mm:ss");
                        sheet.Cells[row, 9].Value = item.writestatus;
                        sheet.Cells[row, 10].Value = item.serialno;

                        row++;
                    }

                    // 自动列宽
                    sheet.Cells[sheet.Dimension.Address].AutoFitColumns();

                    // 冻结首行
                    sheet.View.FreezePanes(2, 1);

                    // 保存文件
                    File.WriteAllBytes(dialog.FileName, package.GetAsByteArray());
                }

                MessageBox.Show($"导出成功！{dialog.FileName}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}");
            }
        }


        private ComboBoxItem _QueryIsCheck = new ComboBoxItem() { Content = "" };
        public ComboBoxItem QueryIsCheck
        {
            get { return _QueryIsCheck; }
            set 
            {
                _QueryIsCheck = value;
                if (_QueryIsCheck != value)
                {
                    SetProperty(ref _QueryIsCheck, value);
                }
            }
        }
        private DateTime _BeginDate;
        public DateTime BeginDate
        {
            get { return _BeginDate; }
            set
            {
                if (_BeginDate != value)
                {
                    _BeginDate = value;
                    if (_BeginDate != value)
                    {
                        SetProperty(ref _BeginDate, value);
                    }
                }
            }
        }
        private DateTime _EndDate;
        public DateTime EndDate
        {
            get { return _EndDate; }
            set
            {

                _EndDate = value;
                if (_EndDate != value)
                {
                    SetProperty(ref _EndDate, value);
                }

            }
        }
        private string _MesOrderNo = "";

        public string MesOrderNo
        {
            get { return _MesOrderNo; }
            set
            {
                if (_MesOrderNo != value)
                {
                    SetProperty(ref _MesOrderNo, value);
                }
            }
        }
        private string _RfidCount = "";

        public string RfidCount
        {
            get { return _RfidCount; }
            set
            {
                if (_RfidCount != value)
                {
                    SetProperty(ref _RfidCount, value);
                }
            }
        }


        private ObservableCollection<real_readdata> _realreaddata = new ObservableCollection<real_readdata>();
        public ObservableCollection<real_readdata> realreaddata
        {
            get => _realreaddata;
            set => SetProperty(ref _realreaddata, value);
        }

    }
}
