using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HslCommunication.Enthernet;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using SlnMesnac.Business;
using SlnMesnac.Common;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Plc;
using SlnMesnac.Repository.service;
using SlnMesnac.TouchSocket;
using SlnMesnac.WPF.Views;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using static System.Net.Mime.MediaTypeNames;

namespace SlnMesnac.WPF.ViewModel
{
    public partial class IndexViewModel: ObservableObject
    {
        private ILogoIdentifyService logoIdentifyService;
        private GunHelper gunHelper = GunHelper.Instance;
        public RelayCommand ConfirmCommand { get; set;}
        public RelayCommand PassCommand { get; set;}

        private LogoBusiness logoBusiness = null;
        private LightHelper lightHelper = LightHelper.Instance;

        private readonly ILogger<LogoBusiness> _logger2;
        private IBaseMaterialService? baseMaterialService;
        private ILogoIdentifyService? ocrVerfiyService;
        private ILogoConfigService? logoConfigService;
       
        private TcpServer? tcpServer;
        private PlcPool plcPool = null;
      

        public IndexViewModel()
        {
            logoIdentifyService = App.ServiceProvider.GetService<ILogoIdentifyService>();
            LogoBusiness.RefreshMessageEvent += RefreshMessage;
            LogoBusiness.RefreshBoxInfoEvent += RefreshBoxInfo;
            LogoBusiness.RefreshPictureEvent += RefreshPicture;
            LogoBusiness.RefreshDataGridEvent += RefreshDataGrid;
            LightHelper.RefreshMessageEvent += RefreshMessage;
            ConfirmCommand = new RelayCommand(Confirm);
            PassCommand = new RelayCommand(Pass);
            RefreshDataGrid();
           
            plcPool = App.ServiceProvider.GetService<PlcPool>();
            tcpServer = App.ServiceProvider.GetService<TcpServer>();
            ocrVerfiyService = App.ServiceProvider.GetService<ILogoIdentifyService>();
            baseMaterialService = App.ServiceProvider.GetService<IBaseMaterialService>();
            logoConfigService = App.ServiceProvider.GetService<ILogoConfigService>();
           
            _logger2 = App.ServiceProvider.GetService<ILogger<LogoBusiness>>();
            logoBusiness = LogoBusiness.GetInstance(_logger2, logoConfigService, baseMaterialService, ocrVerfiyService, plcPool, tcpServer);

            //程序启动，打开绿色指示灯
             gunHelper.SendData("OK");
             OKIsVis = Visibility.Hidden;
             NGIsVis = Visibility.Hidden;
        }



        /// <summary>
        /// 人工确认方法
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Confirm()
        {
           bool result =   logoIdentifyService.ChangeResult();
            if (result)
            {
                
                RefreshMessage("人工确认结果成功", false);
            }
            else
            {
              
                RefreshMessage("人工确认结果成功", true);
            }
            RefreshDataGrid();
        }



        /// <summary>
        /// 放行方法
        /// 复位PLC放行，复位报警灯
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Pass()
        {
            Message = "";
            logoBusiness.Pass();

            lightHelper.SendData("CLOSE");
        }


         
        public async void RefreshDataGrid()
        {

            try
            {
                await Task.Run(async() =>
                {
                    // 查询条件初始化
                   DateTime BeginDate = DateTime.Now.Date;  // 当天的 0:00:00
                   DateTime EndDate = DateTime.Now.Date.AddDays(2).AddSeconds(-1);  // 当天的 23:59:59

                    List<LogoIdentify> list = await logoIdentifyService.QueryAllByTime(BeginDate,EndDate);
                    if (list == null || list.Count == 0) return;

                    #region 计算通过率
                    int totalCount = list.Count;
                    int passCount = list.Where(x => x.isChecked == 1).Count();
                    ScanCount = totalCount.ToString();
                    PassCount = passCount.ToString();
                    int NeedCheckPassCount = list.Where(x => x.isChecked == 1 && x.Result == 1).Count();
                    // 计算通过率并保留两位小数，添加百分号
                    double passRate = totalCount == 0 ? 0 : (double)NeedCheckPassCount / passCount * 100;
                    PassRate = passRate.ToString("F2") + "%";
                    #endregion
                    await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        LogoIdentifyDataGrid.Clear();

                        LogoIdentifyDataGrid.Clear();
                        list = list.OrderByDescending(x => x.RecordTime).ToList();
                        foreach (LogoIdentify verify in list)
                        {
                            LogoIdentifyDataGrid.Add(verify);
                        }
                    }));
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        #region  界面刷新
       

        /// <summary>
        /// 刷新界面箱体信息
        /// </summary>
        /// <param name="boxCode"></param>
        /// <param name="boxTime"></param>
        /// <param name="model"></param>
        /// <param name="imageData"></param>
        public void RefreshBoxInfo(string boxCode,string boxTime,string model,bool isSuccess,bool isNeedCheck)
        {
            BoxCode = boxCode; 
            BoxTime = boxTime;
            ProductModel = model;
            RefreshResultColor(isSuccess,isNeedCheck);
            if (!isSuccess)
            {
                ImageData = null;
            }
        }

        /// <summary>
        /// 刷新界面照片
        /// </summary>
        /// <param name="boxCode"></param>
        /// <param name="boxTime"></param>
        /// <param name="model"></param>
        /// <param name="imageData"></param>
        public void RefreshPicture(byte[] imageData)
        {
            
            ImageData = imageData;
            

        }


        /// <summary>
        /// 刷新界面提示信息
        /// </summary>
        /// <param name="message"></param>
        public void RefreshMessage(string message,bool isWarning = false)
        {
           
            if (isWarning)
            {
              MsgColor = System.Windows.Media.Brushes.Red;
            }
            else
            {
              MsgColor = System.Windows.Media.Brushes.White;
            }
            Message = $"{DateTime.Now.ToString("HH:mm:ss")}:{message}";
        }
        #endregion


        #region 界面参数定义

        #region 初始化datagrid
        private ObservableCollection<LogoIdentify> _LogoIdentifyDataGrid = new ObservableCollection<LogoIdentify>();
        public ObservableCollection<LogoIdentify> LogoIdentifyDataGrid
        {
            get { return _LogoIdentifyDataGrid; }
            set
            {
                _LogoIdentifyDataGrid = value;
                RaisePropertyChanged();//属性通知
            }
        }
        #endregion


        #region 扫码数
        private string _ScanCount;
        public string ScanCount
        {
            get { return _ScanCount; }
            set { _ScanCount = value; RaisePropertyChanged(nameof(ScanCount)); }
        }
        #endregion

        #region 通过数
        private string _PassCount;
        public string PassCount
        {
            get { return _PassCount; }
            set { _PassCount = value; RaisePropertyChanged(nameof(PassCount)); }
        }
        #endregion

        #region 通过率
        private string _PassRate;
        public string PassRate
        {
            get { return _PassRate; }
            set { _PassRate = value; RaisePropertyChanged(nameof(PassRate)); }
        }
        #endregion

        #region 箱体码
        private string _BoxCode;
        public string BoxCode
        {
            get { return _BoxCode; }
            set { _BoxCode = value; RaisePropertyChanged(nameof(BoxCode)); }
        }
        #endregion

        #region 箱体码扫描时间
        private string _BoxTime;
        public string BoxTime
        {
            get { return _BoxTime; }
            set { _BoxTime = value; RaisePropertyChanged(nameof(BoxTime)); }
        }
        #endregion

        #region 产品型号
        private string _ProductModel;
        public string ProductModel
        {
            get { return _ProductModel; }
            set { _ProductModel = value; RaisePropertyChanged(nameof(ProductModel)); }
        }
        #endregion

        #region 提示信息
        private string _Message;
        public string Message
        {
            get { return _Message; }
            set { _Message = value; RaisePropertyChanged(nameof(Message)); }
        }

        private System.Windows.Media.Brush _msgColor;
        public System.Windows.Media.Brush MsgColor
        {
            get { return _msgColor; }
            set
            {
                _msgColor = value;
                RaisePropertyChanged(nameof(MsgColor));
            }
        }

        #endregion


        #region Logo照片
        private byte[] _imageData;
        public byte[] ImageData
        {
            get => _imageData;
            set
            {
                _imageData = value;
                RaisePropertyChanged(nameof(ImageData)); // 属性改变时触发通知
            }
        }

        #endregion


        #region Logo识别结果
        //private string _resultTxt;
        //public string ResultTxt
        //{
        //    get { return _resultTxt; }
        //    set
        //    {
        //        _resultTxt = value;
        //        RaisePropertyChanged(nameof(ResultTxt));
        //    }
        //}

        //private System.Windows.Media.Brush _resultColor;
        //public System.Windows.Media.Brush ResultColor
        //{
        //    get { return _resultColor; }
        //    set
        //    {
        //        _resultColor = value;
        //        RaisePropertyChanged(nameof(ResultColor));
        //    }
        //}

        #region  识别结果ok\ng展示
        private Visibility _OKIsVis;
        public Visibility OKIsVis
        {
            get { return _OKIsVis; }
            set
            {
                _OKIsVis = value;
                RaisePropertyChanged(nameof(OKIsVis));
            }
        }

     

        private Visibility _NGIsVis;
        public Visibility NGIsVis
        {
            get { return _NGIsVis; }
            set
            {
                _NGIsVis = value;
                RaisePropertyChanged(nameof(NGIsVis));
            }
        }

        private Visibility _NOIsVis;
        public Visibility NOIsVis
        {
            get { return _NOIsVis; }
            set
            {
                _NOIsVis = value;
                RaisePropertyChanged(nameof(NOIsVis));
            }
        }
        #endregion
        public void RefreshResultColor(bool isSuccess, bool isNeedCheck)
        {
            if (!isNeedCheck)
            {
                NOIsVis = Visibility.Visible;
                OKIsVis = Visibility.Collapsed;
                NGIsVis = Visibility.Collapsed;
            }
            else
            {
                if (isSuccess)
                {
                    OKIsVis = Visibility.Visible;
                    NGIsVis = Visibility.Collapsed;
                    NOIsVis = Visibility.Collapsed;

                }
                else
                {
                    OKIsVis = Visibility.Collapsed;
                    NOIsVis = Visibility.Collapsed;
                    NGIsVis = Visibility.Visible;
                   
                }
            }
           
        }
        #endregion


        #endregion
    }
}
