using Sln.Iot.Business.Entity;
using Sln.Iot.Repository.service;
using Sln.Iot.Serilog;
using SQLitePCL;
using System.Reflection;
using System.Text.Json;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace Sln.Iot.Business
{
    /// <summary>
    /// TCPRFID信息绑定
    /// </summary>
    public class TCPRFIDBinding
    {
        private static readonly Lazy<TCPRFIDBinding> lazy = new Lazy<TCPRFIDBinding>(() => new TCPRFIDBinding());

        public static TCPRFIDBinding Instance
        {
            get
            {
                return lazy.Value;
            }
        }

        public static Action<string>? GetNewMessage = new Action<string>((message) => { });

        private readonly SerilogHelper _log = SerilogHelper.Instance;

        private readonly TrayBindingService _trayBinding = TrayBindingService.Instance;

        public TCPRFIDBinding()
        {
            GetNewMessage += StoreBindingMessage;
        }

        private static readonly PropertyInfo[] _snProperties =
            typeof(TCPRFIDBindingEntity).GetProperties()
                .Where(p => p.Name.StartsWith("Sn", StringComparison.OrdinalIgnoreCase))
                .ToArray();


        /// <summary>
        /// 数据绑定到数据库
        /// </summary>
        public void StoreBindingMessage(string message)
        {
            var entity = ParseMessage(message);
            if (entity == null || string.IsNullOrWhiteSpace(entity.Rfid)) return;

            var prodCodes = _snProperties
                .Select(p => p.GetValue(entity) as string)
                .Where(v => !string.IsNullOrWhiteSpace(v))
                .ToArray();

            if (prodCodes.Length == 0) return;
            entity.Rfid = entity.Rfid.Replace("?", "");
            entity.Rfid = entity.Rfid.Replace("\0", ""); 
            entity.Rfid.Trim();
            var res = _trayBinding.TrayBindingRefresh(Guid.NewGuid(), entity.Rfid, prodCodes!);
            if (res)
            {
                _log.Info($"插入数据库成功{entity.Rfid}");
                foreach(string re in prodCodes!)
                {
                    _log.Info($"产品{re}进入");
                }
            }
        }

        private static TCPRFIDBindingEntity? ParseMessage(string message)
        {
            if (string.IsNullOrWhiteSpace(message)) return null;

            return JsonSerializer.Deserialize<TCPRFIDBindingEntity>(message);
        }
    }
}
