using Autofac.Core;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Models;
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.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 TouchSocket.Sockets;

namespace SlnMesnac.WPF.ViewModel.IndexPage
{
    [RegisterAsSingletonAttribute]
    public partial class ChangeTypeViewModel : ObservableObject
    {
        private AppConfig appConfig;
        private ISqlSugarClient? sqlSugarClient;
        string lineno = string.Empty;
        private readonly SerilogHelper _logger;
        public List<RfidAbsractFactory> rfidList;
        public ObservableCollection<string> Items { get; set; }
        public ChangeTypeViewModel()
        {
            _logger = App.ServiceProvider.GetService<SerilogHelper>();
            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));
            sqlSugarClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            rfidList = App.ServiceProvider.GetRequiredService<List<RfidAbsractFactory>>();

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

        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;
            }
            // 假设你的行模型叫 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)}");

            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();

            var res = rfidList.FirstOrDefault(x => x.deviceid == DeviceInfos[0].Deviceid).Set_StopIdentify().GetAwaiter().GetResult();
            if (res)
            {
                MessageBox.Show("停止盘点成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("停止盘点失败!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        /// <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);
            List<MesOrderInfo> mesOrderInfos = new List<MesOrderInfo>();
            string response = "{\"code\":200,\"msg\":\"success\",\"data\":[{\"OrderNo\":\"SS075\",\"ProductCode\":\"4030502500100006\",\"ProductType\":\"钢丝带-ST-井下阻燃钢丝带\",\"ProductName\":\"输送带-井下阻燃钢丝带-ST\",\"ProductSpec\":\"1400mm；ST/S2500*1；8+8；MT/MT；D7.2；P15；N89\",\"PlanQty\":130.00,\"NextProductNo\":1}]}\r\n";
            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 (response != null)
                    {
                        ChangeTypePanel.Clear();
                        foreach (var item in responsejson.Data)
                        {
                            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);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public RelayCommand<object> UpdateCommand { get; set; }
        public RelayCommand<object> UpdateCommand1 { 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);
        }

      
    }
}
