using DTO;
using HKCardOUT.Helper;
using HKCardOUT.Logic.Model;
using HKCardOUT.Logic.Service;
using Stylet;
using StyletIoC;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Windows.Documents;
using UHFHelper;
using XExten.Advance.CacheFramework;
using XExten.Advance.CacheFramework.RunTimeCache;
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();
        IContainer Container;
        public RootViewModel(IContainer Container)
        {
            this.Container = Container;
            MainThread();
        }

        protected override void OnViewLoaded()
        {
            ThreadManage.GetInstance().Start(() =>
            {
                Result = new ObservableCollection<SaleLog>(this.Container.Get<HKCore>().PullDaySaleLog());
                Thread.Sleep(3000);
            }, "消费记录查询");
            //广告初始化
            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);
        }

        #region 属性
        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()
        {
            ReadFunc -= ReadCard;
            ReadFunc += ReadCard;
            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);
            // 初始化 串口
            UHF_RS485_Helper.GetInstance().Open(new SerialParam
            {
                PortName = DataBus.COM,
                BaudRate = 57600,
                DataBits = 8
            });

            if (!UHF_RS485_Helper.GetInstance().GetSerialPortState())
                HandyControl.Controls.Growl.InfoGlobal("串口打开失败");
            //读取读卡器
            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                DataBus.StoreInfo.Devices.ForEach(async item =>
                {
                    if (!UHF_RS485_Helper.GetInstance().GetSerialPortState())
                    {
                        HandyControl.Controls.Growl.InfoGlobal("串口未链接");
                    }
                    else
                    {
                        var x = await UHF_RS485_Helper.GetInstance().ReadCard(item.Address.AsInt());
                        if (x != null)
                            ReadFunc?.Invoke(x);
                    }
                });
                Thread.Sleep(500);
            }), "循环读取卡片内容", false);
        }
        #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);
                        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 key = input.Address + ":" + input.ResData;
                //没有超时第一是刷
                if (Caches.RunTimeCacheGet<DKoutput>(key) == null)
                {
                    Caches.RunTimeCacheSet(key, input, 10, true);
                    Container.Get<HKCore>().DeviceSale(new SaleLog
                    {
                        CardNo = input.ResData.Substring(1, input.ResData.Length - 1),
                        Location = input.Address.AsInt().ToString()

                    });
                }
            }
        }
        #endregion
    }
}
