using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SlnMesnac.Common;
using SlnMesnac.Config;
using SlnMesnac.Model.dto;
using SlnMesnac.Model.Enum;
using SlnMesnac.Rfid;
using SlnMesnac.Rfid.Enum;
using SlnMesnac.Rfid.Factory;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.Extensions
* 唯一标识：007aaf92-2adf-42a1-8b64-4e02925e3d5b
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-04-12 17:08:27
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Extensions
{
    public static class RfidFactorySetup
    {
        public static readonly Dictionary<string, Type> _rfidFactoryTypeMap = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase)
        {
            { "RFly_I160", typeof(RflyFactory) },          // 原有的Rfly工厂
            { "Fuchs", typeof(FuchsFactory) },    // 新增的HF读卡器工厂
           
                                                  // 可扩展更多工厂类型
        };
        private static StringChange _StringChange;



        public static void AddRfidFactorySetup(this IServiceCollection services)
        {
            services.AddSingleton<List<RfidAbsractFactory>>(x =>
            {
                AppConfig appConfig = x.GetService<AppConfig>();
                _StringChange = x.GetService<StringChange>();

                List<DeviceInfoConfig> baseRfidInfos = appConfig.deviceInfoConfig.Where(x => x.Collectid == appConfig.StationCode).ToList();
                //sensor_Infos = sqlSugarClient.Queryable<Base_sensor_info>().Where(x => x.Deleteflag == 0).ToList();
                List<RfidAbsractFactory> absractFactories = new List<RfidAbsractFactory>();

                try
                {
                    foreach (var item in baseRfidInfos)
                    {
                        if (item.Deleteflag == 0)
                        {
                            // 3.2 校验工厂类型
                            if (string.IsNullOrEmpty(item.Devicetype))
                            {
                                Log.Error($"设备{item.Deviceid}的工厂类型无效");
                                continue;
                            }
                            // 3.3 动态获取对应工厂实例（核心：替换硬编码的RflyFactory）
                            Type factoryType = _rfidFactoryTypeMap[item.Devicetype];
                            RfidAbsractFactory _rfid = x.GetService(factoryType) as RfidAbsractFactory;
                            if (_rfid == null)
                            {
                                Log.Error($"无法解析工厂实例：{factoryType.FullName}，请确认已注册到DI容器");
                                continue;
                            }
                            int colonIndex = item.Connectstr.IndexOf(":");
                            string IP = colonIndex != -1 ? item.Connectstr.Substring(0, colonIndex) : item.Connectstr;
                            string Port = colonIndex != -1 ? item.Connectstr.Substring(colonIndex + 1) : item.Connectstr;
                            //RfidAbsractFactory _rfid = x.GetService<RflyFactory>();
                            _rfid.deviceid = item.Deviceid;
                            _rfid.ip = IP;
                            _rfid.port = int.Parse(Port);
                            _rfid.ConfigKey = item.Deviceid;
                            _rfid.FilterData = item.Name;
                            //_rfid.FilterData = sensor_Infos.Find(x => x.Deviceid == item.Deviceid).Mapid;
                            //bool connectResult = _rfid.Connect(IP, int.Parse(Port));
                            //_rfid._Action += RecvIdentifyData_Instance;
                            bool connectResult = false;
                            if (connectResult)
                            {
                                //Log.Information($"RFID：{item.Connectstr};连接成功，时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                                //_rfid.ConfigKey = item.equipKey;

                                if (absractFactories.Contains(_rfid))
                                {
                                    absractFactories.Remove(_rfid);
                                }
                                absractFactories.Add(_rfid);
                            }
                            else
                            {
                                //Log.Information($"RFID：{item.Connectstr};连接失败，时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                                if (absractFactories.Contains(_rfid))
                                {
                                    absractFactories.Remove(_rfid);
                                }
                                absractFactories.Add(_rfid);
                            }
                        }
                    }

                }
                catch (Exception e)
                {
                    Log.Error($"RFID初始化连接异常：{e.Message}");
                }

                return absractFactories;
            });
        }

        private static ushort GetMESCallback(int id)
        {
            var sensorInfo = "1";
            if (sensorInfo == null)
            {
                return 1;
            }
            return (ushort)_StringChange.ParseToInt("1");
        }


    }
}
