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.AFN_0CH
{
    /// <summary>
    /// 5.12.2.4.22 F25：当前三相及总有/无功功率、功率因数，三相电压、电流、零序电流、视在功率
    /// </summary>
    public class AFN12_F25_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN12_F25_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;
     
        public AFN12_F25_Analysis(ILogger<AFN12_F25_Analysis> logger, AnalysisStrategyContext analysisStrategyContext)
        {
            _logger = logger;
            _analysisStrategyContext = analysisStrategyContext;
        }

        public List<string> DataType { get; set; } = new List<string>() { "YGGL", "YGGL_A", "YGGL_B", "YGGL_C", "WGGL", "WGGL_A", "WGGL_B", "WGGL_C", "GLYS", "GLYS_A", "GLYS_B", "GLYS_C", "DY_A", "DY_B", "DY_C", "DL_A", "DL_B", "DL_C", "LXDL", "SZGL", "SZGL_A", "SZGL_B", "SZGL_C" };

        public async Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(input);
                ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList);
                List<string> remarks = new List<string>() { "当前总有功功率", "当前A相有功功率", "当前B相有功功率", "当前C相有功功率", "当前总无功功率", "当前A相无功功率", "当前B相无功功率", "当前C相无功功率", "当前总功率因数", "当前A相功率因数", "当前B相功率因数", "当前C相功率因数", "当前A相电压", "当前B相电压", "当前C相电压", "当前A相电流", "当前C相电流", "当前 C相电流", "当前零序电流", "当前总视在功率", "当前A相视在功率", "当前B相视在功率", "当前C相视在功率" };
                List<AFN12_F25_AnalysisDto> list = new List<AFN12_F25_AnalysisDto>();
                List<string> data = await AnalysisDataUnitAsync(input.UnitData.HexMessageList);

                for (int i = 1; i < data.Count; i++)
                {
                    AFN12_F25_AnalysisDto dto = new AFN12_F25_AnalysisDto();
                    decimal value = 0;
                    var errorCodeInfo = data[i].CheckErrorCode();
                    if (errorCodeInfo != null)
                    {
                        dto.ValidData = false;
                        dto.ErrorCodeMsg = errorCodeInfo.Item2;
                    }
                    else
                        decimal.TryParse(data[i], out value);
                    dto.DataValue = value;
                    dto.DataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}_{DataType[i-1]}";
                    dto.FiledName = DataType[i - 1];
                    dto.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");
                    dto.FiledDesc = remarks[i - 1];
                    list.Add(dto);
                }
                UnitDataAnalysis<List<AFN12_F25_AnalysisDto>> unitDataAnalysis = new UnitDataAnalysis<List<AFN12_F25_AnalysisDto>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = list,
                    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_25解析失败:{input.A?.Code}-{input.DT?.Fn ?? 0}-{input?.BaseHexMessage?.HexMessageString},{ex.Message}");

            }
            return await Task.FromResult(false);
        }

        private async Task<List<string>> AnalysisDataUnitAsync(List<string> hexMessageList)
        { 
            List<string> values = new List<string>();
            values.Add(hexMessageList.GetReadTime(4, 5));
            values.AddRange(await CutOutAsync(9, 8, 3, nameof(Appendix_A9), hexMessageList));//解析 总/ABC相有功/无功功率
            values.AddRange(await CutOutAsync(33, 4, 2, nameof(Appendix_A5), hexMessageList));//解析 总/ABC相功率因数
            values.AddRange(await CutOutAsync(41, 3, 2, nameof(Appendix_A7), hexMessageList));//ABC相电压 
            values.AddRange(await CutOutAsync(47, 4, 3, nameof(Appendix_A25), hexMessageList));//ABC相/零序电流
            values.AddRange(await CutOutAsync(59, 4, 3, nameof(Appendix_A9), hexMessageList));//总视\ABC相视在功率
            return values;
        }
        /// <summary>
        /// 截取值
        /// </summary>
        /// <param name="Index">开始位置</param>
        /// <param name="count">总项数</param>
        /// <param name="byteCount">每项字节数</param>
        /// <param name="appendixName">解析方式</param>
        /// <param name="hexMessageList">解析数据</param>
        private async Task<List<string>> CutOutAsync(int Index, int count, int byteCount, string appendixName, List<string> hexMessageList)
        {
            List<string> values = new List<string>();
            var temp = hexMessageList.GetRange(Index, count * byteCount);//截取位置(9),解析项*截取字节数(8*3)
            for (int i = 0; i < count; i++)
            {
                var arr = temp.GetRange(i * byteCount, byteCount);
                var errorCode = arr.CheckErrorCode();
                if (errorCode!=null)
                    values.Add(errorCode.Item1);
                else
                {
                    await _analysisStrategyContext.ExecuteAsync<List<string>>(appendixName, arr, (value) =>
                    {
                        values.Add(value.ToString());
                    });
                }   
            }
            return values;
        }

    }
}
