using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Protocol;
using JiShe.CollectBus.Protocol.Dto;
using JiShe.CollectBus.Protocol.Interfaces;
using JiShe.CollectBus.Protocol.T37612012.AnalysisData;
using JiShe.CollectBus.Protocol3761;
using Microsoft.Extensions.Logging;

namespace GatherService.WattMeter.AnalysisData.AFN_10H
{
    /// <summary>
    /// 透明转发---跳合闸
    /// </summary>
    public class AFN16_F98_Analysis : IAnalysisStrategy<TB3761>
    {

        private readonly ILogger<AFN16_F98_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;
        private readonly DataStorage _dataStorage;
        public AFN16_F98_Analysis(ILogger<AFN16_F98_Analysis> logger, AnalysisStrategyContext analysisStrategyContext, DataStorage dataStorage)
        {
            _logger = logger;
            _analysisStrategyContext = analysisStrategyContext;
            _dataStorage = dataStorage;
        }

        public async Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(input);
                ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList);

                List<string> datas = AnalysisDataUnit(input.UnitData.HexMessageList);
              
                // 查询电表信息
                //AmmeterInfo ammeterInfo = await _dataStorage.GetMeterInfoAsync(data.MeterType.ToString(), "15");
                //if (ammeterInfo != null)
                //{
                //    data.ProjectId = ammeterInfo.ProjectID;
                //    data.MeterId = ammeterInfo.MeterId;
                //    data.DatabaseBusiID = ammeterInfo.DatabaseBusiID;
                //    data.MeterAddress = ammeterInfo.AmmerterAddress;
                //}
                UnitDataAnalysis<bool> unitDataAnalysis = new UnitDataAnalysis<bool>
                {
                    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,
                    Data = (datas[2].Equals("9C") || datas[2].Equals("94")) ? true : false,
                    HexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    TimeDensity = 1,//密度-间隔分钟数,
                    DensityUnit = DensityUnit.Second,
                    ReceivedTime = input.ReceivedTime
                };
                //await _dataStorage.SaveDataToIotDbAsync<decimal>(unitDataAnalysis);
                result?.Invoke(unitDataAnalysis);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"10_98跳合闸解析失败:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString},{ex.Message}");

            }
            return await Task.FromResult(false);
        }

        private List<string> AnalysisDataUnit(List<string> hexMessageList)
        {
            List<string> values = new List<string>();
            values.Add(hexMessageList.GetRange(4, 1)[0].HexToDec().ToString());//端口号
            var contentLengthArr = hexMessageList.GetRange(5, 2);
            contentLengthArr.Reverse();
            int contentLength = string.Join("", contentLengthArr).HexToDec();
            //TODO:转发内容
            List<string> contentArr = hexMessageList.GetRange(7, contentLength);
            //TODO:表地址
            var addressList = contentArr.GetRange(1, 6);
            addressList.Reverse();
            var address = string.Join("", addressList);
            values.Add(address);
            //TODO:控制码
            var controlCode = contentArr.GetRange(8, 1)[0];
            values.Add(controlCode);
            //TODO：长度
            //var len = contentArr.GetRange(9, 1)[0].DataConvert(16);
            //values.Add(len.ToString());
            //TODO:数据域
            //var dataField = contentArr.GetRange(10, len);
            //if (dataField.Count > 0)
            //{
            //    string dataMark = string.Join("", CalculateErrControl(dataField.GetRange(0, 4)));
            //    values.Add(dataMark);//数据标识
            //    var readValue = CalculateErrControl(dataField.GetRange(4, len - 4));//值
            //    var valueData = GetValue<List<string>>(readValue, (AppendixEnums)Enum.Parse(typeof(AppendixEnums), dataMark));
            //    values.AddRange(valueData);
            //}

            return values;
        }
    }
}
