using JiShe.CollectBus.IoTDB.Interface;
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_0CH
{
    /// <summary>
    /// 5.12.2.4.85 F129：当前正向有功电能示值（总、费率1～M）
    /// </summary>
    public class AFN12_F129_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN12_F129_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;
        private readonly IIoTDbProvider _dbProvider;

        public AFN12_F129_Analysis(ILogger<AFN12_F129_Analysis> logger, AnalysisStrategyContext analysisStrategyContext, IIoTDbProvider dbProvider)
        {
            _logger = logger;
            _analysisStrategyContext = analysisStrategyContext;
            _dbProvider= dbProvider;
        }

        public async Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(input);
                ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList);
                ArgumentNullException.ThrowIfNull(input.A.A3?.D1_D7);
                UnitDataAnalysis<List<AFN12_F129_AnalysisDto>> unitDataAnalysis = new UnitDataAnalysis<List<AFN12_F129_AnalysisDto>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    MSA= input.A.A3.D1_D7,
                    PSEQ= input.SEQ.PSEQ,
                    HexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime
                };
                List<string> datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList);
                List<AFN12_F129_AnalysisDto> list = GenerateFinalResult(2, datas, "正向有功电能示值", input.AFN_FC.AFN, input.DT.Fn);
                unitDataAnalysis.Data= list;
                result?.Invoke(unitDataAnalysis);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0C_129解析失败:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString},{ex.Message}");
            
            }
            return await Task.FromResult(false);
        }

        #region 单元数据值解析
        /// <summary>
        /// 单元数据值解析
        /// </summary>
        /// <returns></returns>
        private async Task<List<string>> AnalysisDataUnitAsync(List<string> hexMessageList)
        {
            List<string> values = new List<string>();
            values.Add(hexMessageList.GetReadTime(4, 5));
            int rationgCount = hexMessageList.GetRatingCount(9, 1);
            values.Add(rationgCount.ToString());
            for (int i = 0; i < rationgCount + 1; i++)
            {
                var arr = hexMessageList.GetRange(10 + (i * 5), 5);
                var errorCode = arr.CheckErrorCode();
                if (errorCode != null)
                    values.Add(errorCode.Item1);
                else
                {
                    await _analysisStrategyContext.ExecuteAsync<List<string>>(nameof(Appendix_A14), arr, (value) =>
                    {
                        values.Add(value.ToString());
                    }); //从第10个开始，每加5个字节为下一个值的开始
                }
            }
            return values;
        }
        #endregion

        public  List<AFN12_F129_AnalysisDto> GenerateFinalResult(int index, List<string> data, string remark = "", int afn = 0, int fn = 0)
        {
            List<AFN12_F129_AnalysisDto> list = new List<AFN12_F129_AnalysisDto>();
            for (int i = index; i < data.Count; i++)
            {
                AFN12_F129_AnalysisDto meter = new AFN12_F129_AnalysisDto();

                decimal value = 0;
                var errorCode = data[i].CheckErrorCode();
                if (errorCode != null)
                    meter.ValidData = false;
                else
                    decimal.TryParse(data[i], out value);
                meter.DataValue = value;

                meter.DataType = $"{afn.ToString().PadLeft(2, '0')}_{fn}_{i - index}";
                meter.ReadTime = Convert.ToDateTime($"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00");
                list.Add(meter);
            }
            return list;
        }
    }
}
