using JiShe.CollectBus.Common.Consts;
using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Common.Helpers;
using JiShe.CollectBus.IotSystems.Ammeters;
using JiShe.CollectBus.IotSystems.Devices;
using JiShe.CollectBus.Protocol.Contracts.Protocol.Dto;
using JiShe.CollectBus.Protocol.Dto;
using JiShe.CollectBus.Protocol.Interfaces;
using JiShe.CollectBus.Protocol.T37612012.AnalysisData;
using JiShe.CollectBus.Protocol.T37612012.Appendix;
using JiShe.CollectBus.Protocol3761;
using Microsoft.Extensions.Logging;
using YamlDotNet.Core.Tokens;

namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH
{
    /// <summary>
    /// 5.12.2.4.46 F49：当前电压、电流相位角
    /// </summary>
    public class AFN12_F49_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN12_F49_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;
        private readonly DataStorage _dataStorage;
        public AFN12_F49_Analysis(ILogger<AFN12_F49_Analysis> logger, AnalysisStrategyContext analysisStrategyContext,  DataStorage dataStorage)
        {
            _logger = logger;
            _analysisStrategyContext = analysisStrategyContext;
            _dataStorage = dataStorage;
        }

        public  List<string> ItemType { get; set; } = new List<string>() { "Uab_Ua", "Ub", "Ucb_Uc", "Ia", "Ib", "Ic" };

        public async Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(input);
                ArgumentNullException.ThrowIfNull(input.A.Code);
                List<string> data = await AnalysisDataUnitAsync(input.UnitData?.HexMessageList!);
                List<string> remarks = new List<string>() { "Uab/Ua 相位角", "Ub 相位角", "Ucb/Uc 相位角", "Ia 相位角", "Ib 相位角", "Ic 相位角" };
                List<AnalysisBaseDto<decimal?>> list = new List<AnalysisBaseDto<decimal?>>();
                for (int i = 0; i < data.Count; i++)
                {
                    AnalysisBaseDto<decimal?> dto = new AnalysisBaseDto<decimal?>
                    {
                        DeviceType = MeterTypeEnum.Ammeter
                    };
                    var errorCodeInfo = data[i].CheckErrorCode();
                    if (errorCodeInfo != null)
                    {
                        dto.ValidData = false;
                        dto.ErrorCodeMsg = errorCodeInfo.Item2;
                    }
                    else
                    {
                        if(decimal.TryParse(data[i], out decimal value))
                            dto.DataValue = value;
                    }
                    dto.ItemType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}_{ItemType[i]}";
                    dto.FiledName = dto.ItemType.GetDataFieldByGatherDataType() ?? string.Empty;
                    dto.FiledDesc= remarks[i];
                    list.Add(dto);
                }
                if (list.Count > 0)
                {
                    // 查询设备信息
                    DeviceCacheInfo? deviceInfo = await _dataStorage.GetDeviceInfoAsync(input.A.Code, input.DA.Pn);
                    if (deviceInfo != null)
                    {
                        list.ForEach(item =>
                        {
                            item.ProjectId = deviceInfo.ProjectId;
                            item.DeviceId = deviceInfo.MeterId;
                            item.DatabaseBusiID = deviceInfo.DatabaseBusiID;
                            item.DeviceAddress = deviceInfo.MeterAddress;
                            item.FocusId = deviceInfo.FocusId;
                        });
                    }
                }
                UnitDataAnalysis<List<AnalysisBaseDto<decimal?>>> unitDataAnalysis = new UnitDataAnalysis<List<AnalysisBaseDto<decimal?>>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data= list,
                    ReceivedHexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime,
                    DensityUnit = DensityUnit.Second,
                    TimeDensity = 0,
                    DataType = IOTDBDataTypeConst.Data,
                };
                result?.Invoke(unitDataAnalysis);
                await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0C_49解析失败:{input.A.Code}-{input.DT.Fn}-{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>();
            for (int i = 0; i < 6; i++)
            {
                var arr = hexMessageList.GetRange(4 + (i * 2), 2);
                var errorCode = arr.CheckErrorCode();
                if (errorCode!=null)
                    values.Add(errorCode.Item1);
                else
                {
                    await _analysisStrategyContext.ExecuteAsync<List<string>>(nameof(Appendix_A5), arr, (value) =>
                    {
                        values.Add(value.ToString());
                    });
                }
                   
            }
            return values;
        }

 
       
    }
}
