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

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0AH
{
    /// <summary>
    /// 5.5.1.3.53 F66：定时上报 2 类数据任务设置
    /// </summary>
    public class AFN10_F66_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN10_F66_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;

        public AFN10_F66_Analysis(ILogger<AFN10_F66_Analysis> logger, AnalysisStrategyContext analysisStrategyContext)
        {
            _logger = logger;
            _analysisStrategyContext= analysisStrategyContext;
        }

        public async Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(input);
                ArgumentNullException.ThrowIfNull(input.UnitData.HexMessageList);
                var data = await GenerateFinalResult(input.UnitData.HexMessageList);
                data.Pn = input.DA.Pn;
                UnitDataAnalysis<AFN10_F66_AnalysisDto> dto = new UnitDataAnalysis<AFN10_F66_AnalysisDto>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = data,
                    HexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime
                };
                result?.Invoke(dto);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0A_66解析失败:{input.A?.Code}-{input.DT?.Fn ?? 0}-{input?.BaseHexMessage?.HexMessageString},{ex.Message}");
            }
            return await Task.FromResult(false);
        }

        public async Task<AFN10_F66_AnalysisDto> GenerateFinalResult(List<string> hexMessageList)
        {
            AFN10_F66_AnalysisDto entity = new AFN10_F66_AnalysisDto();
            var cycleBin = hexMessageList[4].HexToBin().PadLeft(8, '0');
            var cycleUnitBin = cycleBin.Substring(0, 2);
            var cycleValueBin = cycleBin.Substring(2, 6);

            entity.Cycle = cycleValueBin.BinToDec();//定时发送周期
            entity.Unit = cycleUnitBin.BinToDec();//定时发送周期(单位)
            //TODO:发送基准时间
            var arrBaseTime = hexMessageList.GetRange(5, 6);

            await _analysisStrategyContext.ExecuteAsync<List<string>>(nameof(Appendix_A1), arrBaseTime, (value) =>
            {
                var baseTimeArrStr = (string)value;
                 var baseTimeArr = baseTimeArrStr.Split('_');
                //entity.BaseTime = DateTime.Parse($"{DateTime.Now.Year.ToString().Substring(0, 2)}{arrBaseTime[0]}-{arrBaseTime[1]}-{arrBaseTime[2]} {arrBaseTime[3]}:{arrBaseTime[4]}:{arrBaseTime[5]}");
                entity.BaseTime = Convert.ToDateTime(baseTimeArr[0]);
            });
           
            entity.CurveRatio = hexMessageList[11].HexToDec();
            var count = hexMessageList[12].HexToDec();
            var dataArr = hexMessageList.GetRange(13, 4 * count);
            for (int i = 0; i < count; i++)
            {
                var pnfnArr = dataArr.GetRange(0, 4);
                var tempPn = T37612012ProtocolPlugin.CalculatePn(pnfnArr[0], pnfnArr[1]);
                var tempFn = T37612012ProtocolPlugin.CalculateFn(pnfnArr[2], pnfnArr[3]);
                entity.Details.Add(new SetAutoItemCodeDetails() { Fn = tempFn, Pn = tempPn });
                dataArr.RemoveRange(0, 4);
            }

            return entity;
        }

    }
}
