using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.Plc;
using SlnMesnac.Repository.service;
using SlnMesnac.Rfid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.Business.base
* 唯一标识：ed6470dd-80bf-4a9b-bfae-3c3a46af4c38
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-04-08 17:18:05
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business.@base
{
    /// <summary>
    /// 业务基类
    /// </summary>
    public class BaseBusiness
    {
        public readonly ILogger<BaseBusiness> _logger;

        /// <summary>
        /// 参数配置
        /// </summary>
        public readonly AppConfig _appConfig;

        /// <summary>
        /// PLC工厂
        /// </summary>
        public readonly List<PlcAbsractFactory> _plcFactories;

        /// <summary>
        /// RFID工厂
        /// </summary>
        public readonly List<RfidAbsractFactory> _rfidFactories;

        /// <summary>
        /// 容器
        /// </summary>
        private IServiceProvider _serviceProvider;

        #region 本地缓存信息
      
     
        private List<BaseConfigInfo> baseConfigInfos;

       
        #endregion


        /// <summary>
        /// 刷新日志信息
        /// </summary>
        /// <param name="msg"></param>
        public delegate void PrintMessageToListBox(string msg);
        public event PrintMessageToListBox? PrintMessageToListBoxEvent;

        public BaseBusiness(ILogger<BaseBusiness> logger, AppConfig appConfig, List<PlcAbsractFactory> plcFactories, List<RfidAbsractFactory> rfidFactories, IServiceProvider serviceProvider)
        {
            _logger = logger;
            _appConfig = appConfig;
            _plcFactories = plcFactories;
            _rfidFactories = rfidFactories;
            _serviceProvider = serviceProvider;

            using (var scope = _serviceProvider.CreateScope()) //
            {
                baseConfigInfos = scope.ServiceProvider.GetRequiredService<List<BaseConfigInfo>>();
               
               
            }
        }

        /// <summary>
        /// 刷新日志
        /// </summary>
        /// <param name="msg"></param>
        public void RefreshMessage(string msg)
        {
            _logger.LogInformation(msg);
            PrintMessageToListBoxEvent?.Invoke(msg);
        }

        /// <summary>
        /// 根据Key获取PLC连接信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public PlcAbsractFactory GetPlcByKey(string key)
        {
            if (_plcFactories == null)
            {
                throw new ArgumentNullException($"根据Key获取PLC连接信息异常:PLC 连接信息为空");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("根据Key获取PLC连接信息异常:设备Key参数为空");
            }

            try
            {
                var info = _plcFactories.Where(x => x.ConfigKey == key).FirstOrDefault();

                return info;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"根据Key获取PLC连接信息异常:{ex.Message}");
            }
        }


        /// <summary>
        /// 根据Key获取Rfid连接信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public RfidAbsractFactory GetRfidByKey(string key)
        {
            if (_rfidFactories == null)
            {
                throw new ArgumentNullException($"根据Key获取RFID连接信息异常:PLC 连接信息为空");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("根据Key获取RFID连接信息异常:设备Key参数为空");
            }

            try
            {
                var info = _rfidFactories.Where(x => x.ConfigKey == key).FirstOrDefault();

                return info;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"根据Key获取RFID连接信息异常:{ex.Message}");
            }
        }



        /// <summary>
        /// 根据RFID Key读取RFID信息
        /// </summary>
        /// <param name="rfidKey"></param>
        /// <param name="epcStr"></param>
        /// <exception cref="InvalidOperationException"></exception>
        public void ReadEpcStrByRfidKey(string rfidKey, out string epcStr)
        {
            try
            {
                var rfidEquip = GetRfidByKey(rfidKey);
                List<TagInfo> tagInfoList = rfidEquip.TimePeriodRead();
                epcStr = tagInfoList.OrderByDescending(x => x.Count).First().EPCstring;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"根据RFID Key读取RFID信息异常:{ex.Message}");
            }
        }


        /// <summary>
        /// 使用---根据RFID Key读取RFID信息
        /// </summary>
        /// <param name="rfidKey"></param>
        /// <param name="epcStr"></param>
        /// <exception cref="InvalidOperationException"></exception>
        public async Task<string> ReadEpcStrByRfidKeyAsync(string rfidKey)
        {
            try
            {
                string epcStr = string.Empty;
                var rfidEquip = GetRfidByKey(rfidKey);
                if(rfidEquip == null)
                {
                    return null;
                }
                List<TagInfo> tagInfoList =await rfidEquip.GetRFIDAsync();
                epcStr = tagInfoList.OrderByDescending(x => x.Count).First().EPCstring;
                return epcStr;
            }
            catch (Exception ex)
            {
                // throw new InvalidOperationException($"根据RFID Key读取RFID信息异常:{ex.Message}");
                return null;
            }
        }


      
        /// <summary>
        /// 根据configKey获取PLC地址
        /// </summary>
        /// <param name="configKey"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public string GetPlcAddressByConfigKey(string configKey)
        {
            try
            {

                if (baseConfigInfos.Count == 0)
                {
                    throw new ArgumentNullException("根据Key获取PLC地址异常:配置集合为空");
                }

                var result = baseConfigInfos.Where(x => x.ConfigKey == configKey).First().ConfigValue;
                return result;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"根据Key获取PLC地址异常{configKey}:{ex.Message}");
            }
        }

      

    }
}
