using Autofac.Core;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Nancy;
using Nancy.Json;
using Serilog;
using SlnMesnac.Common;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Repository;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository.service.Impl;
using SlnMesnac.Rfid;
using SlnMesnac.Serilog;
using SlnMesnac.TouchSocket;
using SlnMesnac.WPF.Attribute;
using SlnMesnac.WPF.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Threading;
using TouchSocket.Sockets;

namespace SlnMesnac.WPF.ViewModel.IndexPage
{
    [RegisterAsSingletonAttribute]
    public partial class ChangeTypeViewModel : ObservableObject
    {
        private AppConfig appConfig;
        //private ISqlSugarClient? sqlSugarClient;
        string lineno = string.Empty;
        private MeshttpClient _httpclient;
        private readonly SerilogHelper _logger;
        public List<RfidAbsractFactory> rfidList;
        public ObservableCollection<string> Items { get; set; }

        private MesOrderInfoImpl databaseService = MesOrderInfoImpl.Instance;

        private DispatcherTimer? _autoRefreshTimer;
        private string _currentLineName = string.Empty;
        private bool _isPaused;

        public ChangeTypeViewModel()
        {
            _logger = App.ServiceProvider.GetService<SerilogHelper>();
            _httpclient = App.ServiceProvider.GetService<MeshttpClient>();
            appConfig = App.ServiceProvider.GetService<AppConfig>();
            BeginDate = DateTime.Now.Date;  // 当天的 0:00:00
            UpdateCommand = new RelayCommand<object>(t => Update(t));
            StopReadingCommand = new RelayCommand<object>(t => StopRead(t));
            GetOrderInfoCommand = new RelayCommand<object>(t => RefreshData(t));
            ClearData = new RelayCommand<object>(t => ClearAllData());
            //sqlSugarClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            rfidList = App.ServiceProvider.GetRequiredService<List<RfidAbsractFactory>>();

            //注册订单刷新暂停/恢复消息
            WeakReferenceMessenger.Default.Register<string, string>(this, "PauseOrderRefresh", (_, __) => PauseAutoRefreshTimer());
            WeakReferenceMessenger.Default.Register<string, string>(this, "ResumeOrderRefresh", (_, __) => ResumeAutoRefreshTimer());

            Items = new ObservableCollection<string>();
            foreach (var rfid in rfidList)
            {
                Items.Add(rfid.FilterData);
            }

            var items = databaseService._helper.QueryAll();
            items.Reverse();
            ChangeTypePanel.Clear();
            foreach (var item in items)
            {
                ChangeTypePanel.Add(item);
            }

        }

        private string _QueryIsCheck = "";
        public string QueryIsCheck
        {
            get { return _QueryIsCheck; }
            set
            {
                _QueryIsCheck = value;
                if (_QueryIsCheck != value)
                {
                    SetProperty(ref _QueryIsCheck, value);
                }
            }
        }
        public RelayCommand<object> GetOrderInfoCommand { get; set; }

        public RelayCommand<object> StopReadingCommand { get; set; }

        private void Update(object parameter)
        {
            if (parameter == null)
            {
                return;
            }
            //获取设备编号
            if (string.IsNullOrEmpty(QueryIsCheck.ToString().Trim()))
            {
                MessageBox.Show("请选择产线!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            // 假设你的行模型叫 DictModel
            var model = parameter as MesOrderInfo;

            var label = model.OrderNo;
            var ProductCode = model.ProductCode;
            var ProductName = model.ProductName;
            var ProductType = model.ProductType;
            var PlanQty = model.PlanQty;
            var NextProductNo = model.NextProductNo;

            List<DeviceInfoConfig> DeviceInfos = appConfig.deviceInfoConfig.Where(x => x.Collectid == appConfig.StationCode && x.Name == QueryIsCheck.ToString().Trim() && x.Deleteflag == 0).ToList();
            string mesOrderNo = MesOrderNo;
            string rfidCount = RfidCount;
            Real_DataInfo real_Data = new Real_DataInfo()
            {
                OrderNo = model.OrderNo,
                Deviceid = DeviceInfos[0].Deviceid,
                LineName = QueryIsCheck.ToString().Trim(),
                LineNo = DeviceInfos[0].Addr,
                ProductType = model.ProductType,
                RfidCount = model.PlanQty.ToString(),
                NextProductNo = model.NextProductNo.ToString("D3")
            };
            WeakReferenceMessenger.Default.Send(real_Data);
            MessageBox.Show("MES订单切换成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Log.Information($"{mesOrderNo}MES订单切换成功{JsonSerializer.Serialize(real_Data)}");

            //记录当前产线并启动自动刷新
            _currentLineName = QueryIsCheck.ToString().Trim();
            StartAutoRefreshTimer();

            MainWindowViewModel.ReturnHomeAction?.Invoke();
        }

        /// <summary>
        /// 停止读取RFID数据
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [RelayCommand]
        private async Task StopRead(object parameter)
        {

            //获取设备编号
            if (string.IsNullOrEmpty(QueryIsCheck.ToString().Trim()))
            {
                MessageBox.Show("请选择产线!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            List<DeviceInfoConfig> DeviceInfos = appConfig.deviceInfoConfig.Where(x => x.Collectid == appConfig.StationCode && x.Name == QueryIsCheck.ToString().Trim() && x.Deleteflag == 0).ToList();
            WeakReferenceMessenger.Default.Send(DeviceInfos[0].Deviceid, "Cancel");

            //同时停止订单自动刷新
            StopAutoRefreshTimer();

        }


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

            //获取设备编号
            if (string.IsNullOrEmpty(QueryIsCheck.ToString().Trim()))
            {
                MessageBox.Show("请选择产线!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                List<DeviceInfoConfig> DeviceInfos = appConfig.deviceInfoConfig.Where(x => x.Collectid == appConfig.StationCode && x.Name == QueryIsCheck.ToString().Trim() && x.Deleteflag == 0).ToList();
                lineno = DeviceInfos[0].Addr;
            }
            Console.WriteLine("调用MES获取订单接口");
            //调用MES接口获取生产订单信息
            //MessageBox.Show("MES订单获取成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //string response = "{\"code\":200,\"msg\":\"success\",\"data\":[{\"OrderNo\":\"SS074\",\"ProductCode\":\"4030502500100006\",\"ProductType\":\"钢丝带-ST-井下阻燃钢丝带\",\"ProductName\":\"输送带-井下阻燃钢丝带-ST\",\"ProductSpec\":\"1400mm；ST/S2500*1；8+8；MT/MT；D7.2；P15；N89\",\"PlanQty\":130.00,\"NextProductNo\":1,\"PlanState\":\"7\",\"PlanStateName\":\"终止\"},{\"OrderNo\":\"SZ091\",\"ProductCode\":\"4030502000100017\",\"ProductType\":\"钢丝带-ST-井下阻燃钢丝带\",\"ProductName\":\"输送带-井下阻燃钢丝带-ST；\",\"ProductSpec\":\"1200mm；ST/S2000*1；8+6；MT/MT；D6；P12；N94\",\"PlanQty\":5.00,\"NextProductNo\":2,\"PlanState\":\"7\",\"PlanStateName\":\"终止\"},{\"OrderNo\":\"SS074\",\"ProductCode\":\"4031502500100003\",\"ProductType\":\"钢丝带-ST-井下阻燃钢网防撕裂钢丝带\",\"ProductName\":\"输送带-井下阻燃钢网防撕裂-ST\",\"ProductSpec\":\"1400mm；ST/S2500*1；8S+8；MT/MT；D7.2；P15；N89\",\"PlanQty\":160.00,\"NextProductNo\":14,\"PlanState\":\"7\",\"PlanStateName\":\"终止\"},{\"OrderNo\":\"SS074\",\"ProductCode\":\"4031502500100003\",\"ProductType\":\"钢丝带-ST-井下阻燃钢网防撕裂钢丝带\",\"ProductName\":\"输送带-井下阻燃钢网防撕裂-ST\",\"ProductSpec\":\"1400mm；ST/S2500*1；8S+8；MT/MT；D7.2；P15；N89\",\"PlanQty\":280.00,\"NextProductNo\":14,\"PlanState\":\"7\",\"PlanStateName\":\"终止\"}]}";
            //调试用：从配置文件MockMesResponse读取模拟数据
            //string response = appConfig.MockMesResponse;
            string response = await _httpclient.GetMesOrderInfo(lineno, BeginDate.ToString("yyyy-MM-dd"));
            Console.WriteLine("接收MES接口返回:" + response);
            // 反序列化
            try
            {
                var responsejson = JsonSerializer.Deserialize<MesApiResponse<MesOrderInfo>>(response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                if (responsejson?.Data != null)
                {
                    if (responsejson.Code != 200)
                    {
                        MessageBox.Show("MES订单获取失败!" + responsejson.Code + responsejson.Msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Log.Information($"MES订单获取失败{JsonSerializer.Serialize(responsejson)}");
                        return;
                    }
                    //Console.WriteLine("序列化:" + responsejson.Code);

                    if (responsejson.Data == null || responsejson.Data.Count == 0)
                    {
                        MessageBox.Show("今天无订单", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    if (response != null)
                    {
                        //先删除所有订单数据
                        DateTime twoDaysAgo = DateTime.Now.AddDays(-2);
                        databaseService._helper.Delete(x => true);
                        //直接插入新的订单数据
                        foreach (var item in responsejson.Data)
                        {
                            item.ID = Guid.NewGuid().ToString();
                            item.InsertDate = DateTime.Now;
                            databaseService._helper.Insert(item);
                        }
                        //查询出来所有数据，反向之后刷新界面
                        var items = databaseService._helper.QueryAll();
                        items.Reverse();
                        ChangeTypePanel.Clear();
                        foreach (var item in items)
                        {
                            ChangeTypePanel.Add(item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Information($"JSON解析失败: {ex.Message}");
                Log.Information($"原始内容: {response}");
                MessageBox.Show("MES订单获取失败");
            }
        }

        private DateTime _BeginDate;
        public DateTime BeginDate
        {
            get { return _BeginDate; }
            set
            {
                if (_BeginDate != value)
                {
                    _BeginDate = value;
                    if (_BeginDate != value)
                    {
                        SetProperty(ref _BeginDate, 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 void ClearAllData()
        {
            var result = MessageBox.Show("确定要清除所有订单记录吗？", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                databaseService._helper.DeleteAll();
                ChangeTypePanel.Clear();
            }
        }

        /// <summary>
        ///
        /// </summary>
        public RelayCommand<object> UpdateCommand { get; set; }
        public RelayCommand<object> UpdateCommand1 { get; set; }
        public RelayCommand<object> ClearData { get; set; }
        private string _ProductType;
        public string ProductType
        {
            get => _ProductType;
            set
            {
                if (_ProductType != value)
                {
                    SetProperty(ref _ProductType, value);
                }
            }
        }
        private string _KTProductType;
        public string KTProductType
        {
            get => _KTProductType;
            set
            {
                if (_KTProductType != value)
                {
                    SetProperty(ref _KTProductType, value);
                }
            }
        }

        private ObservableCollection<MesOrderInfo> _ChangeTypePanel = new ObservableCollection<MesOrderInfo>();
        public ObservableCollection<MesOrderInfo> ChangeTypePanel
        {
            get => _ChangeTypePanel;
            set => SetProperty(ref _ChangeTypePanel, value);
        }

        #region 订单自动刷新

        /// <summary>
        /// 启动订单自动刷新定时器
        /// </summary>
        private void StartAutoRefreshTimer()
        {
            if (!appConfig.AutoOrderRefresh)
                return;

            if (_autoRefreshTimer != null)
                return;

            var intervalSeconds = appConfig.OrderRefreshInterval > 0 ? appConfig.OrderRefreshInterval : 60;

            _autoRefreshTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(intervalSeconds)
            };
            _autoRefreshTimer.Tick += AutoRefreshTimerTick;
            _autoRefreshTimer.Start();
            _isPaused = false;

            Log.Information($"订单自动刷新已启动，间隔 {intervalSeconds} 秒");
        }

        /// <summary>
        /// 暂停订单自动刷新（写入标签时调用）
        /// </summary>
        private void PauseAutoRefreshTimer()
        {
            if (_autoRefreshTimer == null || _isPaused)
                return;

            _autoRefreshTimer.Stop();
            _isPaused = true;
            Log.Information("订单自动刷新已暂停（正在写入标签）");
        }

        /// <summary>
        /// 恢复订单自动刷新（写入完成/失败后调用）
        /// </summary>
        private void ResumeAutoRefreshTimer()
        {
            if (_autoRefreshTimer == null || !_isPaused)
                return;

            _autoRefreshTimer.Start();
            _isPaused = false;
            Log.Information("订单自动刷新已恢复");
        }

        /// <summary>
        /// 停止订单自动刷新定时器
        /// </summary>
        public void StopAutoRefreshTimer()
        {
            if (_autoRefreshTimer != null)
            {
                _autoRefreshTimer.Stop();
                _autoRefreshTimer = null;
                _isPaused = false;
                Log.Information("订单自动刷新已停止");
            }
        }

        /// <summary>
        /// 自动刷新定时器回调：从MES获取最新订单，发现新订单时自动执行
        /// </summary>
        private async void AutoRefreshTimerTick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(_currentLineName))
                    return;

                //获取产线编号
                var deviceInfos = appConfig.deviceInfoConfig
                    .Where(x => x.Collectid == appConfig.StationCode && x.Name == _currentLineName && x.Deleteflag == 0)
                    .ToList();
                if (deviceInfos.Count == 0)
                    return;

                var lineno = deviceInfos[0].Addr;

                //从MES获取订单
                //调试用：从配置文件MockMesResponse读取模拟数据
                //var response = appConfig.MockMesResponse;
                var response = await _httpclient.GetMesOrderInfo(lineno, DateTime.Now.ToString("yyyy-MM-dd"));
                Log.Information($"自动刷新获取订单，产线:{_currentLineName}，返回:{response}");

                var responsejson = JsonSerializer.Deserialize<MesApiResponse<MesOrderInfo>>(
                    response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                if (responsejson?.Code != 200 || responsejson.Data == null || responsejson.Data.Count == 0)
                    return;

                //查找新订单（数据库中不存在的）
                var newOrders = new List<MesOrderInfo>();
                foreach (var item in responsejson.Data)
                {
                    var existing = databaseService._helper.Query(x => x.OrderNo == item.OrderNo && x.ProductCode == item.ProductCode);
                    if (existing == null || existing.Count == 0)
                    {
                        newOrders.Add(item);
                    }
                }

                if (newOrders.Count == 0)
                    return;

                //插入新订单到数据库并刷新界面
                foreach (var item in newOrders)
                {
                    item.ID = Guid.NewGuid().ToString();
                    item.InsertDate = DateTime.Now;
                    databaseService._helper.Insert(item);
                    Log.Information($"自动刷新发现新订单:{item.OrderNo}，物料:{item.ProductCode}，自动执行");
                }

                //刷新界面显示
                var items = databaseService._helper.QueryAll();
                items.Reverse();
                ChangeTypePanel.Clear();
                foreach (var item in items)
                {
                    ChangeTypePanel.Add(item);
                }

                //自动执行第一个新订单
                var firstNewOrder = newOrders[0];
                var deviceInfo = appConfig.deviceInfoConfig
                    .Where(x => x.Collectid == appConfig.StationCode && x.Name == _currentLineName && x.Deleteflag == 0)
                    .ToList();

                if (deviceInfo.Count > 0)
                {
                    var realData = new Real_DataInfo()
                    {
                        OrderNo = firstNewOrder.OrderNo,
                        Deviceid = deviceInfo[0].Deviceid,
                        LineName = _currentLineName,
                        LineNo = deviceInfo[0].Addr,
                        ProductType = firstNewOrder.ProductType,
                        RfidCount = firstNewOrder.PlanQty.ToString(),
                        NextProductNo = firstNewOrder.NextProductNo.ToString("D3")
                    };
                    WeakReferenceMessenger.Default.Send(realData);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"订单自动刷新异常:{ex.Message}");
            }
        }

        #endregion


    }
}



//0, 新建
//1, 已审核
//2, 已下发
//3, 已接收
//4, 执行中
//5, 已完成
//6, 暂停
//7, 终止
//8, 预执行