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.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Documents;
using UHFHelper;
using XExten.Advance.InternalFramework.Securities.Common;
using XExten.Advance.LinqFramework;
using XExten.Advance.StaticFramework;
using System.Diagnostics;
using System.Threading.Tasks;

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;
        public RootViewModel(IContainer Container)
        {
            this.Container = Container;
            this.Activated += RootViewModel_Activated;
            this.Closed += RootViewModel_Closed;

        }
        /// <summary>
        /// 关闭页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RootViewModel_Closed(object sender, CloseEventArgs e)
        {
            ThreadManage.GetInstance().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())
                        {
                            if (DataBus.StoreInfo != null)
                            {
                                DataBus.StoreInfo.Devices.ForEach(item =>
                                {
                                    var res = UHF_RS485_Helper.GetInstance().ReadCard(item.Address.AsInt());
                                    if (res != null)
                                    {
                                        Debug.WriteLine($"卡号地址：{res.Address}----------卡号数据：{res.ResData}");
                                        if (!res.ResData.IsMatch(new Regex("0{20}")))
                                            ReadFunc?.Invoke(res);
                                    }
                                });
                            }
                            else
                                HandyControl.Controls.Growl.InfoGlobal("系统已离线,请连接网络,并重启程序!");
                        }

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

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

                }


            }), "打开串口");

        }
        protected override void OnViewLoaded()
        {
            //广告初始化
            Task.Factory.StartNew(new Action(() =>
            {

                var Init = DataBus.StoreInfo?.Devices.Join(DataBus.StoreInfo?.Stalls, t => t.GateId, x => x.Id, (t, x) => new AdDTO
                {
                    Ad = x.Remaek,
                    Device = t.Name,
                    Stalls = x.Name
                }).ToList();
                if (Init != null)
                {
                    Ad = new ObservableCollection<AdDTO>(Init);
                    var route = SyncStatic.CreateFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AD.txt"));
                    SyncStatic.WriteFile(Encoding.UTF8.GetBytes(SyncStatic.Compress(Init.ToJson(), SecurityType.Base64)), route);
                    AdOpen();
                }
                else
                {
                    var jsons = SyncStatic.Decompress(SyncStatic.ReadFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AD.txt")), SecurityType.Base64);
                    Ad = new ObservableCollection<AdDTO>(jsons.ToModel<List<AdDTO>>());
                    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 AdOpen()
        {
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                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 (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    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 命令
        public void ReadCard(DKoutput input)
        {
            lock (locker)
            {
                var Core = Container.Get<HKCore>();
                var AM = DataBus.Times.AM.Split(",");
                var PM = DataBus.Times.PM.Split(",");
                var AT = DataBus.Times.AT.Split(",");
                if (DateTime.Now >= DateTime.Parse(AM[0]) && DateTime.Now < DateTime.Parse(AM[1]))
                {
                    Core.DeviceSaleAM(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString(),
                        IsSync = false
                    });
                }
                if (DateTime.Now >= DateTime.Parse(PM[0]) && DateTime.Now < DateTime.Parse(PM[1]))
                {
                    Core.DeviceSalePM(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString(),
                        IsSync = false
                    });
                }
                if (DateTime.Now >= DateTime.Parse(AT[0]) && DateTime.Now < DateTime.Parse(AT[1]))
                {
                    Core.DeviceSaleAT(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString(),
                        IsSync = false
                    });
                }
            }
        }
        #endregion
    }
}
