using DTO;
using HKCardOUT.Helper;
using HKCardOUT.Logic.Model;
using HKCardOUT.Logic.Service;
using HKCardOUT.Views;
using NStandard;
using Stylet;
using StyletIoC;
using System;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using UHFHelper;
using XExten.Advance.LinqFramework;

namespace HKCardOUT.ViewModels
{
    public class RootViewModel : Conductor<IScreen>
    {
        public delegate void ReadCardFunc(DKoutput? input);
        public event ReadCardFunc ReadFunc;
        private readonly object locker = new object();
        private IContainer Container;
        private Thread thread1;
        readonly System.Timers.Timer timer1 = new();
        public RootViewModel(IContainer Container)
        {
            this.Container = Container;


            this.Activated += RootViewModel_Activated;
            this.Closed += RootViewModel_Closed;

            MainThread();
        }
        /// <summary>
        /// 关闭页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RootViewModel_Closed(object sender, CloseEventArgs e)
        {
            if (timer1 != null)
            {
                timer1.Stop();
                timer1.Dispose();
            }
            UHF_RS485_Helper.GetInstance().Close();
        }


        private void RootViewModel_Activated(object sender, ActivationEventArgs e)
        {
            ReadFunc -= ReadCard;
            ReadFunc += ReadCard;

            ThreadManage.GetInstance().Start(new Action(() =>
            {
                while (!SerialPort.GetPortNames().Contains(DataBus.COM))
                {
                    Thread.Sleep(1000);
                }

                UHF_RS485_Helper.GetInstance().DisConnect = new Action(() =>
                {
                    ThreadManage.GetInstance().StopTask("串口监听");
                });

                UHF_RS485_Helper.GetInstance().OpenOk = new Action(() =>
                {
                    ThreadManage.GetInstance().StartLong(new Action(() =>
                    {
                        if (UHF_RS485_Helper.GetInstance().GetSerialPortState())
                        {
                            DataBus.StoreInfo.Devices.ForEach(item =>
                            {
                                var res = UHF_RS485_Helper.GetInstance().ReadCard(item.Address.AsInt());

                                if (res != null)
                                {
                                    if (!res.ResData.IsMatch(new Regex("0{20}")))
                                        ReadFunc?.Invoke(res);
                                }
                            });
                        }

                        //if (!UHF_RS485_Helper.GetInstance().GetSerialPortState())
                        //{
                        //    HandyControl.Controls.Growl.InfoGlobal("串口打开失败");
                        //    //timer1.Stop();
                        //    return;
                        //}
                        //else
                        //{

                        //}
                        Thread.Sleep(10);
                    }), "串口监听");
                });

                // 打开串口
                UHF_RS485_Helper.GetInstance().Open(new SerialParam
                {
                    PortName = DataBus.COM,
                    BaudRate = 57600,
                    DataBits = 8
                });
                if (!UHF_RS485_Helper.GetInstance().GetSerialPortState())
                {
                    HandyControl.Controls.Growl.InfoGlobal("串口打开失败");

                }


            }), "打开串口");





            //thread1 = new(new ThreadStart(GetData))
            //{
            //    IsBackground = true
            //};
            //thread1.Start();
        }
        /// <summary>
        /// 读取信息
        /// </summary>
        public void GetData()
        {
            //开启循环监听数据
            timer1.Interval = 500;
            timer1.Elapsed += (o, a) =>
            {
                if (!UHF_RS485_Helper.GetInstance().GetSerialPortState())
                {
                    HandyControl.Controls.Growl.InfoGlobal("串口打开失败");
                    timer1.Stop();
                    return;
                }
                else
                {
                    DataBus.StoreInfo.Devices.ForEach(item =>
                    {
                        var res = UHF_RS485_Helper.GetInstance().ReadCard(item.Address.AsInt());

                        if (res != null)
                        {
                            if (!res.ResData.IsMatch(new Regex("0{20}")))
                                ReadFunc?.Invoke(res);
                        }
                    });
                }
            };
            timer1.Start();
        }
        protected override void OnViewLoaded()
        {
            //广告初始化
            var Init = DataBus.StoreInfo?.Devices.Join(DataBus.StoreInfo?.Stalls, t => t.GateId, x => x.Id, (t, x) => new AdDTO
            {
                Ad = x.Remaek,
                IsActive = false,
                Device = t.Name,
                Stalls = x.Name
            }).ToList();
            if (Init != null)
            {
                Ad = new ObservableCollection<AdDTO>(Init);
                AdOpen();
            }
        }

        #region 属性
        public RootView Main { get; set; }
        ObservableCollection<SaleLog> _Result;
        public ObservableCollection<SaleLog> Result
        {
            get => _Result;
            set => SetAndNotify(ref _Result, value);
        }
        ObservableCollection<AdDTO> _Ad;
        public ObservableCollection<AdDTO> Ad
        {
            get => _Ad;
            set => SetAndNotify(ref _Ad, value);
        }
        #endregion

        #region 网络检查
        private void MainThread()
        {

            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                try
                {
                    //1.检测网络上下线
                    bool network = HKHelpers.GetInstance().GetNetworkState();
                    if (network != DataBus.NetWordState)
                    {
                        if (network) HandyControl.Controls.Growl.InfoGlobal("网络连接成功");
                        else HandyControl.Controls.Growl.InfoGlobal("系统已离线,请连接网络!!!");
                        DataBus.NetWordState = network;
                    }
                    Thread.Sleep(3000);
                }
                catch (Exception ex)
                {
                    HandyControl.Controls.Growl.InfoGlobal(ex.Message);
                }
            }), "循环状态监测线程", false);
        }


        private void AdOpen()
        {
            try
            {
                var SC = System.Windows.Forms.Screen.AllScreens.Count();

                for (int i = 0; i < SC; i++)
                {
                    var win = new AdWindow(Ad[i].Ad);
                    var rectangle = System.Windows.Forms.Screen.AllScreens[i].WorkingArea;
                    win.Height = rectangle.Height;
                    win.Width = rectangle.Width;
                    win.Top = 0;
                    win.Left = rectangle.Left;
                    win.Owner = this.Main;
                    win.Show();
                }
            }
            catch
            {
                var win = new AdWindow("暂无广告");
                var rectangle = System.Windows.Forms.Screen.AllScreens[0].WorkingArea;
                win.Height = rectangle.Height;
                win.Width = rectangle.Width;
                win.Top = 0;
                win.Left = rectangle.Left;
                win.Owner = this.Main;
                win.Show();
            }

        }

        #endregion

        #region 命令

        /// <summary>
        /// 广告位置
        /// </summary>
        /// <param name="input"></param>
        public void UpdateAction(AdDTO input)
        {
            input.IsActive = !input.IsActive;
            var SC = System.Windows.Forms.Screen.AllScreens.Count();
            if (SC >= 1)
            {
                if (input.IsActive)
                {
                    if (!DataBus.AdStatus.ContainsKey(input.Device))
                    {
                        var win = new Views.AdWindow(input.Ad);
                        win.Left = System.Windows.Forms.Screen.AllScreens[1].WorkingArea.Left;
                        DataBus.AdStatus.Add(input.Device, win);
                        win.Show();
                    }
                }
                else
                {
                    if (DataBus.AdStatus.ContainsKey(input.Device))
                    {
                        DataBus.AdStatus[input.Device].Close();
                        DataBus.AdStatus.Remove(input.Device);
                    }
                }
            }
        }
        public void ReadCard(DKoutput input)
        {
            lock (locker)
            {
                var Core = Container.Get<HKCore>();
                var AM = DataBus.AM.Split(",").Select(t => t.AsInt()).ToList();
                var PM = DataBus.PM.Split(",").Select(t => t.AsInt()).ToList();
                var AT = DataBus.AT.Split(",").Select(t => t.AsInt()).ToList();
                if (DateTime.Now.Hour >= AM[0] && DateTime.Now.Hour < AM[1])
                {
                    Core.DeviceSaleAM(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString()
                    });
                }
                if (DateTime.Now.Hour >= PM[0] && DateTime.Now.Hour < PM[1])
                {
                    Core.DeviceSalePM(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString()
                    });
                }
                if (DateTime.Now.Hour >= AT[0] && DateTime.Now.Hour < AT[1])
                {
                    Core.DeviceSaleAT(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString()
                    });
                }
                //Result = new ObservableCollection<SaleLog>(this.Container.Get<HKCore>().PullDaySaleLog());
            }
        }
        #endregion
    }
}
