using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Protocol.Dto;
using JiShe.CollectBus.Protocol.Interfaces;
using JiShe.CollectBus.Protocol3761;
using Microsoft.Extensions.Logging;

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0EH
{
    /// <summary>
    /// 请求重要事件
    /// Item1=停电事件
    /// Item2=上电事件
    /// </summary>
    public class AFN14_F1_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN14_F1_Analysis> _logger;

        public AFN14_F1_Analysis(ILogger<AFN14_F1_Analysis> logger)
        {
            _logger = logger;
        }

        public Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(nameof(input));
                ArgumentNullException.ThrowIfNull(nameof(input.UnitData.HexMessageList));
                int erc = input.UnitData.HexMessageList![8].HexToDec();
                bool isOnOffPower = erc.Equals(14) ? true : false;
                if (!isOnOffPower)
                {
                    throw new Exception($"ERC{erc}非上掉电事件");
                }
                UnitDataAnalysis<Tuple<string, string>> dto = new UnitDataAnalysis<Tuple<string, string>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = AnalysisDataUnit(input.UnitData.HexMessageList),
                    HexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime
                };
                //  meterData.DataType = "0E_1";
                result?.Invoke(dto);
                return Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0E_1解析失败:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString},{ex.Message}");
            }
            return Task.FromResult(false);
        }

        private Tuple<string, string> AnalysisDataUnit(List<string> hexMessageList)
        {
            /// Item1=停电事件
            /// Item2=上电事件
            return Tuple.Create(HandlerTime(hexMessageList.GetRange(10, 5)), HandlerTime(hexMessageList.GetRange(15, 5)));
        }
        /// <summary>
        /// /解析时间
        /// </summary>
        /// <param name="times"></param>
        /// <param name="isSetCurTime">时间验证失败是否默认为当前时间</param>
        /// <returns></returns>
        private string HandlerTime(List<string> times)
        {
            var time = string.Empty;
            try
            {
                times.Reverse();
                time = $"{DateTime.Now.ToString("yyyy").Substring(0, 2)}{times[0]}-{times[1]}-{times[2]} {times[3]}:{times[4]}:00";

            }
            catch { }
            return time;
        }
    }
}

