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.AFN_0CH
{
    /// <summary>
    /// 5.12.2.4.30 F33：当前正向有/无功电能示值、一/四象限无功电能示值（总、费率 1～M，1≤M≤12）
    /// </summary>
    public class AFN12_F33_Analysis : IAnalysisStrategy<TB3761>
    {
        private List<string> DataUnitHexList { get; set; }=new List<string>();
        private readonly ILogger<AFN12_F33_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;

        public AFN12_F33_Analysis(ILogger<AFN12_F33_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);
                int rationgCount = input.UnitData.HexMessageList!.GetRatingCount(23, 1);

                DataUnitHexList = input.UnitData.HexMessageList.GetRange(24, (5 * (rationgCount + 1)) + (4 * (rationgCount + 1)) * 3);
                GetDataUnitHexString(input.UnitData.HexMessageList, rationgCount);
                UnitDataAnalysis<AFN12_F33_AnalysisDto> unitDataAnalysis = new UnitDataAnalysis<AFN12_F33_AnalysisDto>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = await AnalysisDataUnit(input.UnitData.HexMessageList, rationgCount),
                    HexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime
                };
                result?.Invoke(unitDataAnalysis);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0C_33解析失败:{input.A?.Code}-{input.DT?.Fn ?? 0}-{input?.BaseHexMessage?.HexMessageString},{ex.Message}");

            }
            return await Task.FromResult(false);
        }

        #region 获取当前正向有/无功电能示值数据单元格式  private void GetDataUnitHexString(int rationgCount)
        private void GetDataUnitHexString(List<string> hexMessageList, int rationgCount)
        {
            //(5*(x+1))+(4*(x+1))*3
            var lenght = (5 * (rationgCount + 1)) + (4 * (rationgCount + 1)) * 3;//(rationgCount * 5 + 5) + (4 * 3) + (rationgCount * 4) * 2;//费率数(R)：4 公式：5+5+（费率数*5）+ （4+（费率数*4））*2
            DataUnitHexList = hexMessageList.GetRange(24, lenght);
        }
        #endregion

        #region 单元数据值解析 private F33Entity AnalysisDataUnit()
        private async Task<AFN12_F33_AnalysisDto> AnalysisDataUnit(List<string> hexMessageList, int rationgCount)
        {
            AFN12_F33_AnalysisDto f33Entity = new AFN12_F33_AnalysisDto();
            f33Entity.ReadTime = hexMessageList.GetReadTime(18, 5); // 终端抄表时间
            f33Entity.RatingCount = hexMessageList.GetRatingCount(23, 1); // 费率数 M（1≤M≤12）
            f33Entity.F_A_Kwh = await GetDataAsync(f33Entity.RatingCount, 0, 5, nameof(Appendix_A14));//当前正向有功总电能示值
            f33Entity.R_R_Kvarh = await GetDataAsync(f33Entity.RatingCount, 25, 4, nameof(Appendix_A11));//当前正向无功（组合无功1）总电能示值 0+5*5
            f33Entity.Q1_R_Kvarh = await GetDataAsync(f33Entity.RatingCount, 45, 4, nameof(Appendix_A11));//当前一象限无功总电能示值 25+4*5
            f33Entity.Q4_R_Kvarh = await GetDataAsync(f33Entity.RatingCount, 65, 4, nameof(Appendix_A11));//当前四象限无功总电能示值 45+4*5
            return f33Entity;
        }
        #region 有功/无功、费率总电能示值
        /// <summary>
        /// 有功/无功、费率总电能示值
        /// </summary>
        /// <param name="ratingCount">费率数</param>
        /// <param name="startIndex">开始位置</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        private async Task<ParentNodes> GetDataAsync(int ratingCount, int startIndex, int len, string appendxName)
        {
            ParentNodes parent = new ParentNodes();
            var arr = DataUnitHexList.GetRange(startIndex, len);
            await _analysisStrategyContext.ExecuteAsync<List<string>>(appendxName, arr, (value) =>
            {
                parent.Total_Value = value;
            });
            parent.childNodes = await GetChildDataAsync(ratingCount, startIndex, len, appendxName);
            return parent;
        }

        /// <summary>
        /// 费率总电能示值
        /// </summary>
        /// <param name="RatingCount"></param>
        /// <param name="startIndex"></param>
        /// <param name="len"></param>
        /// <param name="appendix"></param>
        /// <returns></returns>
        private async Task<List<ChildNodes>> GetChildDataAsync(int RatingCount, int startIndex, int len, string appendxName)
        {
            List<ChildNodes> children = new List<ChildNodes>();
            for (int i = 0; i < RatingCount; i++)
            {
                var arr = DataUnitHexList.GetRange((i * len) + (startIndex + len), len);
                await _analysisStrategyContext.ExecuteAsync<List<string>>(appendxName, arr, (value) =>
                {
                    ChildNodes model = new ChildNodes()
                    {
                        Value = value //29,4 33,4 37,4 41,4
                    };
                    children.Add(model);
                });
            }
            return children;
        }


        #endregion


        #endregion

    }
}
