using FreeRedis;
using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Common.Models;
using JiShe.CollectBus.Protocol.Contracts.Interfaces;
using Microsoft.Extensions.Logging;
using JiShe.CollectBus.Protocol.Contracts.Models;
using Volo.Abp.Domain.Repositories;
using JiShe.CollectBus.Common.BuildSendDatas;
using JiShe.CollectBus.Protocol.Contracts.AnalysisData;
using Microsoft.Extensions.DependencyInjection;
using JiShe.CollectBus.IotSystems.MessageReceiveds;
using JiShe.CollectBus.IotSystems.Protocols;
using JiShe.CollectBus.Kafka.Producer;
using JiShe.CollectBus.Common.Consts;
using JiShe.CollectBus.FreeRedis;

namespace JiShe.CollectBus.Protocol.Contracts.Abstracts
{
    public abstract class BaseProtocolPlugin_bak   //: IProtocolPlugin
    {
        private readonly IProducerService  _producerService;
        private readonly ILogger<BaseProtocolPlugin_bak> _logger;
        private readonly IRepository<ProtocolInfo, Guid> _protocolInfoRepository;
        private readonly IFreeRedisProvider _redisProvider;

        //头部字节长度
        public const int hearderLen = 6;

        public const int tPLen = 6;

        public const string errorData = "EE";

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseProtocolPlugin_bak"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        protected BaseProtocolPlugin_bak(IServiceProvider serviceProvider)
        {

            _logger = serviceProvider.GetRequiredService<ILogger<BaseProtocolPlugin_bak>>();
            _protocolInfoRepository = serviceProvider.GetRequiredService<IRepository<ProtocolInfo, Guid>>();
            _producerService = serviceProvider.GetRequiredService<IProducerService>();
            _redisProvider = serviceProvider.GetRequiredService<IFreeRedisProvider>();
        }

        public abstract ProtocolInfo Info { get; }

        public virtual async Task<ProtocolInfo> GetAsync() => await Task.FromResult(Info);

        public virtual async Task LoadAsync()
        {
            if (Info == null)
            {
                throw new ArgumentNullException(nameof(Info));
            }

            await _protocolInfoRepository.DeleteDirectAsync(a => a.Name == Info.Name);
            await _protocolInfoRepository.InsertAsync(Info);
            await _redisProvider.Instance.HDelAsync($"{RedisConst.ProtocolKey}", Info.Name);
            await _redisProvider.Instance.HSetAsync($"{RedisConst.ProtocolKey}", Info.Name, Info);
        }

        public abstract Task<T> AnalyzeAsync<T>(MessageReceived messageReceived, Action<byte[]>? sendAction = null) where T : TB3761;

        /// <summary>
        /// 登录帧解析
        /// </summary>
        /// <param name="messageReceived">报文</param>
        /// <returns></returns>
        public virtual async Task LoginAsync(MessageReceivedLogin messageReceived)
        {
            var hexStringList = messageReceived.MessageHexString.StringToPairs();
            var aTuple = (Tuple<string, int>)hexStringList.GetAnalyzeValue(CommandChunkEnum.A);
            var seq = (Seq)hexStringList.GetAnalyzeValue(CommandChunkEnum.SEQ);
            var reqParam = new ReqParameter2
            {
                AFN = AFN.确认或否认,
                FunCode = (int)CFromStationFunCode.链路数据,
                PRM = PRM.从动站报文,
                A = aTuple.Item1,
                Seq = new Seq()
                {
                    TpV = TpV.附加信息域中无时间标签,
                    FIRFIN = FIRFIN.单帧,
                    CON = CON.需要对该帧进行确认,
                    PRSEQ = seq.PRSEQ
                },
                MSA = aTuple.Item2,
                Pn = 0,
                Fn = 1
            };
            var bytes = Build3761SendData.BuildSendCommandBytes(reqParam);
            //await _producerBus.PublishAsync(ProtocolConst.SubscriberLoginIssuedEventName, new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Login, MessageId = messageReceived.MessageId });

            await _producerService.ProduceAsync(ProtocolConst.SubscriberLoginIssuedEventName, new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Login, MessageId = messageReceived.MessageId });
            //await _producerBus.Publish(new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Login, MessageId = messageReceived.MessageId });
        }

        /// <summary>
        /// 心跳帧解析
        /// </summary>
        /// <param name="messageReceived">报文</param>
        /// <returns></returns>
        public virtual async Task HeartbeatAsync(MessageReceivedHeartbeat messageReceived)
        {
            var hexStringList = messageReceived.MessageHexString.StringToPairs();
            var aTuple = (Tuple<string, int>)hexStringList.GetAnalyzeValue(CommandChunkEnum.A);
            var seq = (Seq)hexStringList.GetAnalyzeValue(CommandChunkEnum.SEQ);
            if (seq.TpV == TpV.附加信息域中带时间标签)
            {
                //解析

            }
            if (seq.CON == CON.需要对该帧进行确认)
            {
                var reqParam = new ReqParameter2()
                {
                    AFN = AFN.确认或否认,
                    FunCode = (int)CFromStationFunCode.链路数据,
                    PRM = PRM.从动站报文,
                    A = aTuple.Item1,
                    Seq = new Seq()
                    {
                        TpV = TpV.附加信息域中无时间标签,
                        FIRFIN = FIRFIN.单帧,
                        CON = CON.不需要对该帧进行确认,
                        PRSEQ = seq.PRSEQ,
                    },
                    MSA = aTuple.Item2,
                    Pn = 0,
                    Fn = 1
                };
                var bytes = Build3761SendData.BuildSendCommandBytes(reqParam);
                //await _producerBus.PublishAsync(ProtocolConst.SubscriberHeartbeatIssuedEventName, new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Heartbeat, MessageId = messageReceived.MessageId });

                await _producerService.ProduceAsync(ProtocolConst.SubscriberHeartbeatIssuedEventName, new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Heartbeat, MessageId = messageReceived.MessageId });

                //await _producerBus.Publish(new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Heartbeat, MessageId = messageReceived.MessageId });
            }
        }

        /// <summary>
        /// 解析确认或否认数据
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>
        public virtual async Task AnalyzeAnswerDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexStringList = messageReceived.MessageHexString.StringToPairs();
            var fn = hexStringList.GetAnalyzeValue(CommandChunkEnum.FN);
            //1:全部确认
            //2:全部否认
            //3:按数据单元表示确认和否认
            //4 硬件安全认证错误应答
        }

        /// <summary>
        /// 解析电表档案读取数据
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>
        public virtual List<AmmeterParameter> AnalyzeAmmeterParameterReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexData = GetHexData(messageReceived.MessageHexString);

            var meterList = new List<AmmeterParameter>();
            var count = (hexData[1] + hexData[0]).HexToDec();
            //if (2 + count * 27 != hexDatas.Count - pWLen - tPLen - 2)
            //    return;
            var index = 2;//数量
            for (int i = 1; i <= count; i++)
            {
                var meterNumber = $"{hexData[index + 1]}{hexData[index]}".HexToDec();
                index += 2;

                var pn = $"{hexData[index + 1]}{hexData[index]}".HexToDec();
                index += 2;

                var baudRateAndPortBin = hexData[index].HexToBin().PadLeft(8, '0');
                var baudRate = baudRateAndPortBin.Substring(0, 3).BinToDec();
                var port = baudRateAndPortBin.Substring(3, 5).BinToDec();
                index += 1;

                var protocolType = (CommunicationProtocolType)hexData[index].HexToDec();
                index += 1;

                var addressHexList = hexData.Skip(index).Take(6).ToList();
                addressHexList.Reverse();
                var address = string.Join("", addressHexList);
                index += 6;

                var pwdHexList = hexData.Skip(index).Take(6).ToList();
                pwdHexList.Reverse();
                var password = string.Join("", pwdHexList.Take(3).ToList());
                index += 6;

                var rateNumberBin = hexData[index].HexToBin().PadLeft(8, '0');
                var rateNumber = rateNumberBin.Substring(4).BinToDec();
                index += 1;

                var intBitAndDecBitNumberBin = hexData[index].HexToBin().PadLeft(8, '0');
                var intBitNumber = intBitAndDecBitNumberBin.Substring(4, 2).BinToDec() + 4;
                var decBitNumber = intBitAndDecBitNumberBin.Substring(6, 2).BinToDec() + 1;
                index += 1;

                // hexDatas.GetRange()
                var collectorAddressHexList = hexData.Skip(index).Take(6).ToList();
                collectorAddressHexList.Reverse();
                var collectorAddress = string.Join("", collectorAddressHexList);
                index += 6;

                var userClassNumberBin = hexData[index].HexToBin().PadLeft(8, '0');
                var userClass = userClassNumberBin.Substring(0, 4).BinToDec();
                var userSubClass = userClassNumberBin.Substring(4, 4).BinToDec();
                index += 1;

                meterList.Add(new AmmeterParameter()
                {
                    Pn = pn,
                    BaudRate = baudRate,
                    Port = port,
                    ProtocolType = (int)protocolType,
                    Address = address,
                    Password = password,
                    RateNumber = rateNumber,
                    IntegerBitNumber = intBitNumber,
                    DecimalBitNumber = decBitNumber,
                    CollectorAddress = collectorAddress,
                    UserCategoryNumber = userClass,
                    UserSubclassNumber = userSubClass,
                });
            }

            return meterList;
        }

        /// <summary>
        /// 解析当前正向有功电能示值抄读数据
        /// </summary>
        /// <param name="messageReceived">报文</param>
        /// <param name="sendAction">发送委托</param>
        /// <returns></returns>
        public virtual CurrentPositiveActiveEnergyAnalyze AnalyzeActivePowerIndicationReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexData = GetHexData(messageReceived.MessageHexString);

            var minute = Convert.ToInt32(hexData[0]); // 获取当前分钟数
            var hour = Convert.ToInt32(hexData[1]); // 获取当前小时数
            var day = Convert.ToInt32(hexData[2]); // 获取当前日期的日数
            var month = Convert.ToInt32(hexData[3]); // 获取当前月份
            var year = Convert.ToInt32(hexData[4]); // 获取当前日期的年份
            var dateTime = new DateTime(year, month, day, hour, minute, 0);
            // 转换为本地时间
            var localDateTime = dateTime.ToLocalTime();

            var rateNumber = Convert.ToInt32(hexData[5]);
            var kwhTotal = hexData.Skip(5).Take(5).ToList();
            var kwhList = new List<PositiveActiveEnergyItem>();
            var index = 11;
            for (int i = 0; i < rateNumber; i++)
            {
                var kwhHexList = hexData.Skip(index).Take(5).ToList();
                kwhHexList.Reverse();
                var integerStr = $"{kwhHexList.Take(0)}{kwhHexList.Take(1)}{kwhHexList.Take(2)}";
                var decimalValStr = $"{kwhHexList[3]}{kwhHexList[4]}";
                var val = decimal.Parse($"{integerStr}{decimalValStr}");
                kwhList.Add(new PositiveActiveEnergyItem()
                {
                    Name = $"费率{i + 1}正向有功总电能示值",
                    Value = val
                });
                index += 5;
            }

            return new CurrentPositiveActiveEnergyAnalyze()
            {
                ReadingTime = localDateTime,
                RateNumber = rateNumber,
                Items = kwhList
            };
        }

        /// <summary>
        /// 解析日冻结正向有功电能示值抄读数据
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>
        public virtual void AnalyzeDailyFrozenReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexData = GetHexData(messageReceived.MessageHexString);
            //附录A.20 日月年
            var td_dHex = hexData.Take(3).ToList();
            //附录A.15 分时日月年
            var readingTimeHex = hexData.Skip(3).Take(5).ToList();
            var rateNumberHex = hexData.Skip(8).Take(1).FirstOrDefault().HexToDec();

            var datas = new List<decimal>();
            //附录A.14 kWh 5字节
            for (int i = 0; i < rateNumberHex; i++)
            {
                var skipCount = 9 + i * 5;
                var dataHexs = hexData.Skip(skipCount).Take(5).ToList();
                var data = AnalyzeDataAccordingToA14(dataHexs[0], dataHexs[1], dataHexs[2], dataHexs[3], dataHexs[4]);
                datas.Add(data);
            }

        }

        //接收<2024/11/7 17:34:42>: 68 3E 01 3E 01 68
        //控制域 88
        //地址域 20 32 90 26 1A
        //AFN 0C
        //Seq 62
        //pn 01 01
        //fn 01 03

        //F0 16         

        //报文解析:计量点1数据
        //++++++++  F25:当前三相及总有/无功功率功率因数 三相电压电流 零序电流 ++++++++
        //终端抄表时间:2024年11月07日17时34分        34 17 07 11 24
        //当前总有功功率:-0.0028 kW                 28 00 80
        //当前A相有功功率:0 kW                      00 00 80
        //当前B相有功功率:0 kW                      00 00 80
        //当前C相有功功率:-0.0027 kW                27 00 80
        //当前总无功功率:-0.0047 kW                 47 00 80
        //当前A相无功功率:0 kW                      00 00 00
        //当前B相无功功率:0 kW                      00 00 00
        //当前C相无功功率:-0.0047 kW                47 00 80
        //当前总功率因数:-51.8 %                    18 85
        //当前A相功率因数:0 %                       00 80
        //当前B相功率因数:0 %                       00 80
        //当前C相功率因数:-50 %                     00 85
        //当前A相电压:0.1 V                        01 00
        //当前B相电压:0.2 V                        02 00
        //当前C相电压:239 V                        90 23
        //当前A相电流:0 A                          00 00 80
        //当前B相电流:0 A                          00 00 80
        //当前C相电流:-0.024 A                     24 00 80
        //当前零序电流:Error: 数据不符合BCD码格式 A   EE EE EE
        //当前总视在功率:Error: 数据不符合BCD码格式 kVA EE EE EE
        //当前A相视在功率:Error: 数据不符合BCD码格式 kVA  EE EE EE
        //当前B相视在功率:Error: 数据不符合BCD码格式 kVA  EE EE EE
        //当前C相视在功率:Error: 数据不符合BCD码格式 kVA  EE EE EE
        //++++++++++++++++++++++++++++++++++++
        /// <summary>
        /// 当前三相及总有/无功功率、功率因数、三相电压、电流、零序电流、视在功率
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>//F25ReadingAnalyze
        public virtual Analyze3761Data AnalyzeF25ReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexData = GetHexData(messageReceived.MessageHexString);
            //A.15 分时日月年
            var readingTimeHex = hexData.Take(5).ToList();
            var readingTime = AnalyzeDataAccordingToA15(readingTimeHex[0], readingTimeHex[1], readingTimeHex[2], readingTimeHex[3], readingTimeHex[4]);

            //A.9 kW
            var crntTotalActivePowerHexs = hexData.Skip((int)F25DataItemEnum.CrntTotalActivePower).Take(3).ToList();
            var crntTotalActivePower = AnalyzeDataAccordingToA09(crntTotalActivePowerHexs[0], crntTotalActivePowerHexs[1], crntTotalActivePowerHexs[2]);

            var crntActivePowerOfAHexs = hexData.Skip((int)F25DataItemEnum.CrntActivePowerOfA).Take(3).ToList();
            var crntActivePowerOfA = AnalyzeDataAccordingToA09(crntActivePowerOfAHexs[0], crntActivePowerOfAHexs[1], crntActivePowerOfAHexs[2]);

            var crntActivePowerOfBHexs = hexData.Skip((int)F25DataItemEnum.CrntActivePowerOfB).Take(3).ToList();
            var crntActivePowerOfB = AnalyzeDataAccordingToA09(crntActivePowerOfBHexs[0], crntActivePowerOfBHexs[1], crntActivePowerOfBHexs[2]);

            var crntActivePowerOfCHexs = hexData.Skip((int)F25DataItemEnum.CrntActivePowerOfC).Take(3).ToList();
            var crntActivePowerOfC = AnalyzeDataAccordingToA09(crntActivePowerOfCHexs[0], crntActivePowerOfCHexs[1], crntActivePowerOfCHexs[2]);

            var crntTotalReactivePowerHexs = hexData.Skip((int)F25DataItemEnum.CrntTotalReactivePower).Take(3).ToList();
            var crntTotalReactivePower = AnalyzeDataAccordingToA09(crntTotalReactivePowerHexs[0], crntTotalReactivePowerHexs[1], crntTotalReactivePowerHexs[2]);

            var crntReactivePowerOfAHexs = hexData.Skip((int)F25DataItemEnum.CrntReactivePowerOfA).Take(3).ToList();
            var crntReactivePowerOfA = AnalyzeDataAccordingToA09(crntReactivePowerOfAHexs[0], crntReactivePowerOfAHexs[1], crntReactivePowerOfAHexs[2]);

            var crntReactivePowerOfBHexs = hexData.Skip((int)F25DataItemEnum.CrntReactivePowerOfB).Take(3).ToList();
            var crntReactivePowerOfB = AnalyzeDataAccordingToA09(crntReactivePowerOfBHexs[0], crntReactivePowerOfBHexs[1], crntReactivePowerOfBHexs[2]);

            var crntReactivePowerOfCHexs = hexData.Skip((int)F25DataItemEnum.CrntReactivePowerOfC).Take(2).ToList();
            var crntReactivePowerOfC = AnalyzeDataAccordingToA09(crntReactivePowerOfCHexs[0], crntReactivePowerOfCHexs[1], crntReactivePowerOfCHexs[2]);

            //A.5 %
            var crntTotalPowerFactorHexs = hexData.Skip((int)F25DataItemEnum.CrntTotalPowerFactor).Take(2).ToList();
            var crntTotalPowerFactor = AnalyzeDataAccordingToA05(crntTotalPowerFactorHexs[0], crntTotalPowerFactorHexs[1]);

            var crntPowerFactorOfAHexs = hexData.Skip((int)F25DataItemEnum.CrntPowerFactorOfA).Take(2).ToList();
            var crntPowerFactorOfA = AnalyzeDataAccordingToA05(crntPowerFactorOfAHexs[0], crntPowerFactorOfAHexs[1]);

            var crntPowerFactorOfBHexs = hexData.Skip((int)F25DataItemEnum.CrntPowerFactorOfB).Take(2).ToList();
            var crntPowerFactorOfB = AnalyzeDataAccordingToA05(crntPowerFactorOfBHexs[0], crntPowerFactorOfBHexs[1]);

            var crntPowerFactorOfCHexs = hexData.Skip((int)F25DataItemEnum.CrntPowerFactorOfC).Take(2).ToList();
            var crntPowerFactorOfC = AnalyzeDataAccordingToA05(crntPowerFactorOfCHexs[0], crntPowerFactorOfCHexs[1]);

            //A.7 V
            var crntVoltageOfAHexs = hexData.Skip((int)F25DataItemEnum.CrntVoltageOfA).Take(2).ToList();
            var crntVoltageOfA = AnalyzeDataAccordingToA07(crntVoltageOfAHexs[0], crntVoltageOfAHexs[1]);

            var crntVoltageOfBHexs = hexData.Skip((int)F25DataItemEnum.CrntVoltageOfB).Take(2).ToList();
            var crntVoltageOfB = AnalyzeDataAccordingToA07(crntVoltageOfBHexs[0], crntVoltageOfBHexs[1]);

            var crntVoltageOfCHexs = hexData.Skip((int)F25DataItemEnum.CrntVoltageOfC).Take(2).ToList();
            var crntVoltageOfC = AnalyzeDataAccordingToA07(crntVoltageOfCHexs[0], crntVoltageOfCHexs[1]);

            //A.25 A
            var crntCurrentOfAHexs = hexData.Skip((int)F25DataItemEnum.CrntCurrentOfA).Take(3).ToList();
            var crntCurrentOfA = AnalyzeDataAccordingToA25(crntCurrentOfAHexs[0], crntCurrentOfAHexs[1], crntCurrentOfAHexs[2]);

            var crntCurrentOfBHexs = hexData.Skip((int)F25DataItemEnum.CrntCurrentOfB).Take(3).ToList();
            var crntCurrentOfB = AnalyzeDataAccordingToA25(crntCurrentOfBHexs[0], crntCurrentOfBHexs[1], crntCurrentOfBHexs[2]);

            var crntCurrentOfCHexs = hexData.Skip((int)F25DataItemEnum.CrntCurrentOfC).Take(3).ToList();
            var crntCurrentOfC = AnalyzeDataAccordingToA25(crntCurrentOfCHexs[0], crntCurrentOfCHexs[1], crntCurrentOfCHexs[2]);

            var crntZeroSequenceCurrentHexs = hexData.Skip((int)F25DataItemEnum.CrntZeroSequenceCurrent).Take(3).ToList();
            var crntZeroSequenceCurrent = AnalyzeDataAccordingToA25(crntZeroSequenceCurrentHexs[0], crntZeroSequenceCurrentHexs[1], crntZeroSequenceCurrentHexs[2]);

            //A.9 kVA
            var crntTotalApparentPowerHexs = hexData.Skip((int)F25DataItemEnum.CrntTotalApparentPower).Take(3).ToList();
            var crntTotalApparentPower = AnalyzeDataAccordingToA09(crntTotalApparentPowerHexs[0], crntTotalApparentPowerHexs[1], crntTotalApparentPowerHexs[2]);

            var crntApparentPowerOfAHexs = hexData.Skip((int)F25DataItemEnum.CrntApparentPowerOfA).Take(3).ToList();
            var crntApparentPowerOfA = AnalyzeDataAccordingToA09(crntApparentPowerOfAHexs[0], crntApparentPowerOfAHexs[1], crntApparentPowerOfAHexs[2]);

            var crntApparentPowerOfBHexs = hexData.Skip((int)F25DataItemEnum.CrntApparentPowerOfB).Take(3).ToList();
            var crntApparentPowerOfB = AnalyzeDataAccordingToA09(crntApparentPowerOfBHexs[0], crntApparentPowerOfBHexs[1], crntApparentPowerOfBHexs[2]);

            var crntApparentPowerOfCHexs = hexData.Skip((int)F25DataItemEnum.CrntApparentPowerOfC).Take(3).ToList();
            var crntApparentPowerOfC = AnalyzeDataAccordingToA09(crntApparentPowerOfCHexs[0], crntApparentPowerOfCHexs[1], crntApparentPowerOfCHexs[2]);

            return new Analyze3761Data()
            {
                AFN = 12,
                FN = 25,
                Text = "当前三相及总有/无功功率功率因数",
                DataUpChilds = new List<Analyze3761DataUpChild>()
                {
                    new Analyze3761DataUpChild(1,"终端抄表时间",readingTime.ToString(),1),
                    new Analyze3761DataUpChild(2,"当前总有功功率",crntTotalActivePower.ToString(),2),
                    new Analyze3761DataUpChild(3,"当前A相有功功率",crntActivePowerOfA.ToString(),3),
                    new Analyze3761DataUpChild(4,"当前B相有功功率",crntActivePowerOfB.ToString(),4),
                    new Analyze3761DataUpChild(5,"当前C相有功功率",crntActivePowerOfC.ToString(),5),
                    new Analyze3761DataUpChild(6,"当前总无功功率",crntTotalReactivePower.ToString(),6),
                    new Analyze3761DataUpChild(7,"当前A相无功功率",crntReactivePowerOfA.ToString(),7),
                    new Analyze3761DataUpChild(8,"当前B相无功功率",crntReactivePowerOfB.ToString(),8),
                    new Analyze3761DataUpChild(9,"当前C相无功功率",crntReactivePowerOfC.ToString(),9),
                    new Analyze3761DataUpChild(10,"当前总功率因数",crntTotalPowerFactor.ToString(),10),
                    new Analyze3761DataUpChild(11,"当前A相功率因数",crntPowerFactorOfA.ToString(),11),
                    new Analyze3761DataUpChild(12,"当前B相功率因数",crntPowerFactorOfB.ToString(),12),
                    new Analyze3761DataUpChild(13,"当前C相功率因数",crntPowerFactorOfC.ToString(),13),
                    new Analyze3761DataUpChild(14,"当前A相电压",crntVoltageOfA.ToString(),14),
                    new Analyze3761DataUpChild(15,"当前B相电压",crntVoltageOfB.ToString(),15),
                    new Analyze3761DataUpChild(16,"当前C相电压",crntVoltageOfC.ToString(),16),
                    new Analyze3761DataUpChild(17,"当前A相电流",crntCurrentOfA.ToString(),17),
                    new Analyze3761DataUpChild(18,"当前B相电流",crntCurrentOfB.ToString(),18),
                    new Analyze3761DataUpChild(19,"当前C相电流",crntCurrentOfC.ToString(),19),
                    new Analyze3761DataUpChild(20,"当前零序电流",crntZeroSequenceCurrent.ToString(),20),
                    new Analyze3761DataUpChild(21,"当前总视在功率",crntTotalApparentPower.ToString(),21),
                    new Analyze3761DataUpChild(22,"当前A相视在功率",crntApparentPowerOfA.ToString(),22),
                    new Analyze3761DataUpChild(23,"当前B相视在功率",crntApparentPowerOfB.ToString(),23),
                    new Analyze3761DataUpChild(24,"当前C相视在功率",crntApparentPowerOfC.ToString(),24),
                }
            };

            //var f25ReadingAnalyze = new F25ReadingAnalyze()
            //{
            //    ReadingTime = readingTime.ToLocalTime(),
            //    CrntTotalActivePower = crntTotalActivePower,
            //    CrntActivePowerOfA = crntActivePowerOfA,
            //    CrntActivePowerOfB = crntActivePowerOfB,
            //    CrntActivePowerOfC = crntActivePowerOfC,
            //    CrntTotalReactivePower = crntTotalReactivePower,
            //    CrntReactivePowerOfA = crntReactivePowerOfA,
            //    CrntReactivePowerOfB = crntReactivePowerOfB,
            //    CrntReactivePowerOfC = crntReactivePowerOfC,
            //    CrntTotalPowerFactor = crntTotalPowerFactor,
            //    CrntPowerFactorOfA = crntPowerFactorOfA,
            //    CrntPowerFactorOfB = crntPowerFactorOfB,
            //    CrntPowerFactorOfC = crntPowerFactorOfC,
            //    CrntVoltageOfA = crntVoltageOfA,
            //    CrntVoltageOfB = crntVoltageOfB,
            //    CrntVoltageOfC = crntVoltageOfC,
            //    CrntCurrentOfA = crntCurrentOfA,
            //    CrntCurrentOfB = crntCurrentOfB,
            //    CrntCurrentOfC = crntCurrentOfC,
            //    CrntZeroSequenceCurrent = crntZeroSequenceCurrent,
            //    CrntTotalApparentPower = crntTotalApparentPower,
            //    CrntApparentPowerOfA = crntApparentPowerOfA,
            //    CrntApparentPowerOfB = crntApparentPowerOfB,
            //    CrntApparentPowerOfC = crntApparentPowerOfC
            //};

            //return f25ReadingAnalyze;

        }

        /// <summary>
        /// 解析终端版本信息抄读
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>//TerminalVersionInfoAnalyze
        public virtual Analyze3761Data AnalyzeTerminalVersionInfoReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexData = GetHexData(messageReceived.MessageHexString);
           
            var makerNo = string.Join("",hexData.Take(4).Select(s => (char)s.HexToDec()));//厂商代码
            var deviceNo = string.Join("", hexData.Skip((int)TerminalVersionInfoEnum.DeviceNo).Take(8).Select(s => (char)s.HexToDec()));//设备编号
            var softwareVersionNo = string.Join("", hexData.Skip((int)TerminalVersionInfoEnum.SoftwareVersionNo).Take(4).Select(s => (char)s.HexToDec()));//软件版本号
            var softwareReleaseDateList = hexData.Skip((int)TerminalVersionInfoEnum.SoftwareReleaseDate).Take(3).ToList();
            var softwareReleaseDate = $"20{AnalyzeDataAccordingToA20(softwareReleaseDateList[0], softwareReleaseDateList[1], softwareReleaseDateList[2])}";//软件发布日期
            var capacityInformationCode = string.Join("", hexData.Skip((int)TerminalVersionInfoEnum.CapacityInformationCode).Take(11).Select(s => (char)s.HexToDec()));//容量信息码
            var protocolVersionNo = string.Join("", hexData.Skip((int)TerminalVersionInfoEnum.ProtocolVersionNo).Take(4).Select(s => (char)s.HexToDec()));//通信协议编号
            var hardwareVersionNo = string.Join("", hexData.Skip((int)TerminalVersionInfoEnum.HardwareVersionNo).Take(4).Select(s => (char)s.HexToDec()));//硬件版本号
            var hardwareReleaseDateList = hexData.Skip((int)TerminalVersionInfoEnum.HardwareReleaseDate).Take(3).ToList();
            var hardwareReleaseDate = $"20{AnalyzeDataAccordingToA20(hardwareReleaseDateList[0], hardwareReleaseDateList[1], hardwareReleaseDateList[2])}";//软件发布日期
           
            return new Analyze3761Data()
            {
                AFN = 09,
                FN = 1,
                Text = "终端版本信息",
                DataUpChilds = new List<Analyze3761DataUpChild>()
                {
                    new Analyze3761DataUpChild(1,"厂商代码",makerNo.ToString(),1),
                    new Analyze3761DataUpChild(2,"设备编号",deviceNo.ToString(),2),
                    new Analyze3761DataUpChild(3,"软件版本号",softwareVersionNo.ToString(),3),
                    new Analyze3761DataUpChild(4,"软件发布日期",softwareReleaseDate.ToString(),4),
                    new Analyze3761DataUpChild(5,"容量信息码",capacityInformationCode.ToString(),5),
                    new Analyze3761DataUpChild(6,"通信协议编号",protocolVersionNo.ToString(),6),
                    new Analyze3761DataUpChild(7,"硬件版本号",hardwareVersionNo.ToString(),7),
                    new Analyze3761DataUpChild(8,"软件发布日期",hardwareReleaseDate.ToString(),8),
                }
            };
            //return new TerminalVersionInfoAnalyze()
            //{
            //    MakerNo = makerNo,
            //    DeviceNo = deviceNo,
            //    SoftwareVersionNo = softwareVersionNo,
            //    SoftwareReleaseDate = DateTime.Parse(softwareReleaseDate).ToLocalTime(),
            //    CapacityInformationCode = capacityInformationCode,
            //    ProtocolVersionNo = protocolVersionNo,
            //    HardwareVersionNo = hardwareVersionNo,
            //    HardwareReleaseDate = DateTime.Parse(hardwareReleaseDate).ToLocalTime()
            //};
        }

        /// <summary>
        /// 解析相位角
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>
        public virtual Analyze3761Data AnalyzeATypeOfDataItems49ReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexData = GetHexData(messageReceived.MessageHexString);
           
            var uabUaList = hexData.Take(2).ToList();
            var uabUa = AnalyzeDataAccordingToA05(uabUaList[0], uabUaList[1]); //单位 度

            var ubList = hexData.Skip((int)ATypeOfDataItems49.Ub).Take(2).ToList();
            var ub = AnalyzeDataAccordingToA05(ubList[0], ubList[1]);

            var ucbUcList = hexData.Skip((int)ATypeOfDataItems49.UcbUc).Take(2).ToList();
            var ucbUc = AnalyzeDataAccordingToA05(ucbUcList[0], ucbUcList[1]);

            var iaList = hexData.Skip((int)ATypeOfDataItems49.Ia).Take(2).ToList();
            var ia = AnalyzeDataAccordingToA05(iaList[0], iaList[1]);

            var ibList = hexData.Skip((int)ATypeOfDataItems49.Ib).Take(2).ToList();
            var ib = AnalyzeDataAccordingToA05(ibList[0], ibList[1]);

            var icList = hexData.Skip((int)ATypeOfDataItems49.Ic).Take(2).ToList();
            var ic = AnalyzeDataAccordingToA05(icList[0], icList[1]);

            return new Analyze3761Data()
            {
                AFN = 12,
                FN = 49,
                Text = "相位角",
                DataUpChilds =
                [
                    new Analyze3761DataUpChild(1, "UabUa相位角", uabUa.ToString(), 1),
                    new Analyze3761DataUpChild(2, "Ub相位角", ub.ToString(), 2),
                    new Analyze3761DataUpChild(3, "UcbUc相位角", ucbUc.ToString(), 3),
                    new Analyze3761DataUpChild(4, "Ia相位角", ia.ToString(), 4),
                    new Analyze3761DataUpChild(5, "Ib相位角", ib.ToString(), 5),
                    new Analyze3761DataUpChild(6, "Ic相位角", ic.ToString(), 6)
                ]
            };
        }

        /// <summary>
        /// 解析终端时间抄读
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>

        public virtual void AnalyzeTerminalTimeReadingDataAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexDatas = GetHexData(messageReceived.MessageHexString);
            var time = Appendix.Appendix_A1(hexDatas.Take(6).ToList());
        }

        ///// <summary>
        ///// 通用解析
        ///// </summary>
        ///// <param name="messageReceived"></param>
        ///// <param name="sendAction"></param>
        ///// <returns></returns>
        //public virtual TB3761 AnalyzeReadingDataAsync(MessageReceived messageReceived,
        //    Action<byte[]>? sendAction = null)
        //{
        //    var hexStringList = messageReceived.MessageHexString.StringToPairs();
        //    var afn = (AFN)hexStringList.GetAnalyzeValue(CommandChunkEnum.AFN);
        //    var fn = (int)hexStringList.GetAnalyzeValue(CommandChunkEnum.FN);
           
        //    var tb3761 = QGDW3761Config.CommandList.FirstOrDefault(it => it.Afn == afn);
        //    if (tb3761 == null) return null;

        //    var tb3761Fn = tb3761.FnList.FirstOrDefault(it => it.Fn == fn);
        //    if (tb3761Fn == null) return null;

        //    var analyzeValue = (List<string>)hexStringList.GetAnalyzeValue(CommandChunkEnum.Data);
           
        //    var m = 0;
        //    var rateNumberUpSort = -1;
        //    var rateNumberUp = tb3761Fn.UpList.FirstOrDefault(it => it.Name.Contains("费率数M"));
        //    if (rateNumberUp != null)
        //    {
        //        var rateNumber = analyzeValue.Skip(rateNumberUp.DataIndex).Take(rateNumberUp.DataCount).FirstOrDefault();
        //        m = Convert.ToInt32(rateNumber);
        //        rateNumberUpSort = rateNumberUp.Sort;
        //    }
          
        //    foreach (var up in tb3761Fn.UpList)
        //    {
        //        var dataIndex = up.DataIndex;
        //        if (dataIndex == 0 && up.Sort > rateNumberUpSort)
        //        {
        //            var sum1 = tb3761Fn.UpList.Where(it => it.Sort < up.Sort)
        //                .Sum(it => it.DataCount);
        //            var sum2 = tb3761Fn.UpList.Where(it => it.Sort < up.Sort && it.Tb3761UpChildlList.Count > 0)
        //                .Sum(it => it.Tb3761UpChildlList.Sum(c=> m * c.DataCount));
        //            dataIndex = sum1 + sum2;
        //        }

        //        var value = AnalyzeDataAccordingDataType(analyzeValue, dataIndex, up.DataCount, up.DataType);
        //        if (value != null)
        //        {
        //            up.Value = value.ToString();
        //        }
        //        if (up.Tb3761UpChildlList.Count > 0) //复费率根据费率数来解析
        //        {
        //            var repeatCount = m;
        //            foreach (var upChild in up.Tb3761UpChildlList)
        //            {
        //                for (var j = 0; j < repeatCount; j++)
        //                {
        //                    var val = AnalyzeDataAccordingDataType(analyzeValue, dataIndex, upChild.DataCount, upChild.DataType);
        //                    if (val != null)
        //                    {
        //                        upChild.Name = string.Format(upChild.Name, j + 1);
        //                        upChild.Value = val.ToString();
        //                    }
        //                    dataIndex += upChild.DataCount;
        //                }
        //            }

        //        }
        //    }

        //    return tb3761;
        //}

        ///// <summary>
        ///// 通用解析 日冻结曲线类
        ///// </summary>
        ///// <param name="messageReceived"></param>
        ///// <param name="sendAction"></param>
        ///// <returns></returns>
        //public virtual TB3761 AnalyzeReadingTdcDataAsync(MessageReceived messageReceived,
        //    Action<byte[]>? sendAction = null)
        //{

        //    var hexStringList = messageReceived.MessageHexString.StringToPairs();
        //    var afn = (AFN)hexStringList.GetAnalyzeValue(CommandChunkEnum.AFN);
        //    var fn = (int)hexStringList.GetAnalyzeValue(CommandChunkEnum.FN);

        //    var tb3761 = QGDW3761Config.CommandTdcList.FirstOrDefault(it => it.Afn == afn);
        //    if (tb3761 == null) return null;

        //    var tb3761Fn = tb3761.FnList.FirstOrDefault(it => it.Fn == fn);
        //    if (tb3761Fn == null) return null;

        //    var analyzeValue = (List<string>)hexStringList.GetAnalyzeValue(CommandChunkEnum.Data);
           
        //    foreach (var up in tb3761Fn.UpList)
        //    {
        //        var value = AnalyzeDataAccordingDataType(analyzeValue, up.DataIndex, up.DataCount, up.DataType);
        //        if (value != null)
        //        {
        //            up.Value = value.ToString();

        //            if (up.Tb3761UpChildlList.Count > 0) 
        //            {
        //                var dataIndex = up.DataIndex;
        //                var repeatCount = (int)value;
        //                foreach (var upChild in up.Tb3761UpChildlList)
        //                {
        //                    for (var j = 0; j < repeatCount; j++)
        //                    {
        //                        var val = AnalyzeDataAccordingDataType(analyzeValue, dataIndex, upChild.DataCount, upChild.DataType);
        //                        if (val != null)
        //                        {
        //                            upChild.Value = val.ToString();
        //                            upChild.Name = string.Format(upChild.Name, j + 1);
        //                        }
        //                        dataIndex += upChild.DataCount;
        //                    }
        //                }
        //            }
        //        }
        //    }

        //    return tb3761;
        //    //var freezeDensity = (FreezeDensity)Convert.ToInt32(hexDatas.Skip(5).Take(1));
        //    //var addMinute = 0;
        //    //switch (freezeDensity)
        //    //{
        //    //     case FreezeDensity.No:break;
        //    //     case FreezeDensity.Min15:
        //    //         addMinute = 15;
        //    //         break;
        //    //     case FreezeDensity.Min30:
        //    //         addMinute = 30;
        //    //         break;
        //    //     case FreezeDensity.Min60:
        //    //         addMinute = 60;
        //    //         break;
        //    //     case FreezeDensity.Min5: break;
        //    //         addMinute = 5;
        //    //     case FreezeDensity.Min1:
        //    //         addMinute = 1;
        //    //         break;
        //    // }
        //}

        private object? AnalyzeDataAccordingDataType(List<string> analyzeValue, int dataIndex,int dataCount,string dataType)
        {
            var valueList = analyzeValue.Skip(dataIndex).Take(dataCount).ToList();
            object? value = null;
            switch (dataType)
            {
                case "BIN":
                    value = Convert.ToInt32(valueList[0]);
                    break;
                case "A05":
                    if (valueList.Count == 2)
                    {
                        value = AnalyzeDataAccordingToA05(valueList[0], valueList[1]);
                    }
                    break;
                case "A09":
                    if (valueList.Count == 3)
                    {
                        value = AnalyzeDataAccordingToA09(valueList[0], valueList[1], valueList[2]);
                    }
                    break;
                case "A14":
                    if (valueList.Count == 5)
                    {
                        value = AnalyzeDataAccordingToA15(valueList[0], valueList[1], valueList[2], valueList[3], valueList[4]);
                    }
                    break;
                case "A15":
                    if (valueList.Count == 5)
                    {
                        //var minutes = Convert.ToInt32(analyzeValue[0]); // 获取当前分钟数
                        //var hours = Convert.ToInt32(analyzeValue[1]); // 获取当前小时数
                        //var day = Convert.ToInt32(analyzeValue[2]); // 获取当前日期的日数
                        //var month = Convert.ToInt32(analyzeValue[3]); // 获取当前月份
                        //var year = Convert.ToInt32(analyzeValue[4]); // 获取当前日期的年份
                        value = AnalyzeDataAccordingToA15(valueList[0], valueList[1], valueList[2], valueList[3], valueList[4]);
                    }
                    break;
                case "ATd_d":
                    var day = valueList[0];
                    var month = valueList[1];
                    var year = valueList[2];
                    break;
                case "ATd_m":
                    var tdmMonth = valueList[0];
                    var tdmYear = valueList[1];
                    break;
            }

            return value;
        }

        /// <summary>
        /// 解析透明转发 应答
        /// </summary>
        /// <param name="messageReceivedEvent"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>
        public virtual async Task AnalyzeTransparentForwardingAnswerAsync(MessageReceived messageReceivedEvent, Action<byte[]>? sendAction = null)
        {
            var hexDatas = GetHexData(messageReceivedEvent.MessageHexString);

            var port = hexDatas[0].HexToDec();

            var count = hexDatas[1].HexToDec();

            var dataList = hexDatas.Skip(2).Take(count).ToList();

            //645
            if (dataList[0].IsStartStr() && dataList[hearderLen - 1].IsStartStr())
            {

            }
            else if (dataList[0].IsStartStr())//188 水表只有开头是68
            {
                AnalyzeWaterMeterReadData(dataList);
            }
        }

        /// <summary>
        /// 解析透明转发 应答结果
        /// </summary>
        /// <param name="messageReceived"></param>
        /// <param name="sendAction"></param>
        /// <returns></returns>
        public virtual async Task AnalyzeTransparentForwardingAnswerResultAsync(MessageReceived messageReceived, Action<byte[]>? sendAction = null)
        {
            var hexDatas = GetHexData(messageReceived.MessageHexString);

            var port = hexDatas[0].HexToDec();

            //A.12
            var a = hexDatas.Skip(1).Take(6).ToList();

            var result = hexDatas.Skip(7).Take(1).FirstOrDefault().HexToDec();
            var transparentForwardingFlag = (TransparentForwardingFlagEnum)result;
        }

        /// <summary>
        /// 获取命令数据单元-数据体
        /// </summary>
        /// <param name="messageHexString"></param>
        /// <returns></returns>
        public static List<string> GetHexData(string messageHexString)
        {
            var hexStringList = messageHexString.StringToPairs();
            var analyzeValue = (List<string>)hexStringList.GetAnalyzeValue(CommandChunkEnum.Data);
            return analyzeValue;
        }

        /// <summary>
        /// 解析时间标签
        /// </summary>
        /// <param name="hexData"></param>
        public void AnalysisTp(List<string> hexData)
        {
            var pFC = hexData[0].HexToDec();//启动帧帧序号计数器
            var seconds = Convert.ToInt32(hexData[1]); // 获取当前秒数
            var minutes = Convert.ToInt32(hexData[2]); // 获取当前分钟数
            var hours = Convert.ToInt32(hexData[3]); // 获取当前小时数
            var day = Convert.ToInt32(hexData[4]); // 获取当前日期的日数
            var delayTime = hexData[5].HexToDec();//延迟时间 min
        }

        #region 报文指定的数据格式

        /// <summary>
        /// 根据A05解析数据
        /// </summary>
        /// <param name="singleDigitNumberAndDeciles">个位和十分位</param>
        /// <param name="hundredDigitNumbersAndTenDigitNumber">百位和十位</param>
        /// <returns></returns>
        public decimal AnalyzeDataAccordingToA05(string singleDigitNumberAndDeciles, string hundredDigitNumbersAndTenDigitNumber)
        {
            if (singleDigitNumberAndDeciles.IsErrorData() && hundredDigitNumbersAndTenDigitNumber.IsErrorData())
            {
                return 0;
            }
            var bin1 = hundredDigitNumbersAndTenDigitNumber.HexToBin().PadLeft(8, '0');
            var hundredDigitNumbers = bin1.Substring(1, 3).BinToDec();//百位
            var tenDigitNumber = bin1.Substring(4).BinToDec();//十位

            var bin2 = singleDigitNumberAndDeciles.HexToBin().PadLeft(8, '0');
            var singleDigitNumber = bin1.Substring(0, 4).BinToDec();//个位
            var deciles = bin1.Substring(4).BinToDec();//十分位

            var value = decimal.Parse($"{hundredDigitNumbers}{tenDigitNumber}{singleDigitNumber}.{deciles}");
            return value;
        }

        /// <summary>
        /// 数据格式07
        /// </summary>
        /// <param name="singleDigitNumberAndDeciles">个位、十分位</param>
        /// <param name="hundredDigitNumbersAndTenDigitNumber">百位、十位</param>
        /// <returns></returns>
        public decimal AnalyzeDataAccordingToA07(string singleDigitNumberAndDeciles, string hundredDigitNumbersAndTenDigitNumber)
        {
            if (singleDigitNumberAndDeciles.IsErrorData() && hundredDigitNumbersAndTenDigitNumber.IsErrorData())
            {
                return 0;
            }
            var bin1 = hundredDigitNumbersAndTenDigitNumber.HexToBin().PadLeft(8, '0');
            var hundredDigitNumbers = bin1.Substring(1, 3).BinToDec();//百位
            var tenDigitNumber = bin1.Substring(4).BinToDec();//十位

            var bin2 = singleDigitNumberAndDeciles.HexToBin().PadLeft(8, '0');
            var singleDigitNumber = bin2.Substring(0, 4).BinToDec();//个位
            var deciles = bin2.Substring(4).BinToDec();//十分位

            var value = decimal.Parse($"{hundredDigitNumbers}{tenDigitNumber}{singleDigitNumber}.{deciles}");
            return value;
        }

        /// <summary>
        ///  数据格式09
        /// </summary>
        /// <param name="thousandthPercentileAndTenThousandPositions">千分位和万分位</param>
        /// <param name="decilesAndPercentile">十分位和百分位</param>
        /// <param name="tenAndSingleDigit">十位和个位</param>
        /// <returns></returns>
        public decimal AnalyzeDataAccordingToA09(string thousandthPercentileAndTenThousandPositions, string decilesAndPercentile, string tenAndSingleDigit)
        {
            if (thousandthPercentileAndTenThousandPositions.IsErrorData() && decilesAndPercentile.IsErrorData() && tenAndSingleDigit.IsErrorData())
            {
                return 0;
            }

            var bin3 = tenAndSingleDigit.HexToBin().PadLeft(8, '0');
            var tenDigitNumber = bin3.Substring(1, 3).BinToDec();//十位
            var singleDigitNumber = bin3.Substring(4).BinToDec();//个位

            var value = decimal.Parse($"{tenDigitNumber}{singleDigitNumber}.{decilesAndPercentile}{thousandthPercentileAndTenThousandPositions}");
            return value;

            //var bin3 = hex3.HexToBin().PadLeft(8, '0');
            //var thousandthPercentile = bin3.Substring(0, 4).BinToDec();//千分位
            //var tenThousandPositions = bin3.Substring(4).BinToDec();//万分位

            //var bin2 = hex2.HexToBin().PadLeft(8, '0');
            //var deciles = bin2.Substring(0, 4).BinToDec();//十分位
            //var percentile = bin2.Substring(4).BinToDec();//百分位


        }

        /// <summary>
        /// 数据格式12
        /// </summary>
        /// <param name="tenDigitAndSingleDigitNumber">十位 个位</param>
        /// <param name="thousandAndHundredsOfPosition">千位 百位</param>
        /// <param name="hundredThousandAndTenThousandOfPosition">十万位 万位</param>
        /// <param name="millionsAndMillionOfPosition">千万位 百万位</param>
        /// <param name="hundredMillionAndBillionOfPosition">十亿位 亿位</param>
        /// <param name="hundredBillionsAndBillionsOfPosition">千亿位 百亿位</param>
        /// <returns></returns>
        public string AnalyzeDataAccordingToA12(string tenDigitAndSingleDigitNumber, string thousandAndHundredsOfPosition, string hundredThousandAndTenThousandOfPosition,
            string millionsAndMillionOfPosition, string hundredMillionAndBillionOfPosition, string hundredBillionsAndBillionsOfPosition)
        {
            var value = $"{hundredBillionsAndBillionsOfPosition}{hundredMillionAndBillionOfPosition}{millionsAndMillionOfPosition}" +
                $"{hundredThousandAndTenThousandOfPosition}{thousandAndHundredsOfPosition}{tenDigitAndSingleDigitNumber}";

            return value;
        }

        /// <summary>
        /// 数据格式14
        /// </summary>
        /// <param name="tenThousandPositionsAndThousandthPercentile">千分，万分</param>
        /// <param name="decilesAndPercentile">十分、百分</param>
        /// <param name="tenDigitNumberAndSingleDigitNumber">十位、个位</param>
        /// <param name="thousandAndHundredsOfPosition">千位、百位</param>
        /// <param name="hundredThousandAndTenThousandOfPosition">十万位、万位</param>
        /// <returns></returns>
        public decimal AnalyzeDataAccordingToA14(string tenThousandPositionsAndThousandthPercentile, string decilesAndPercentile,
            string tenDigitNumberAndSingleDigitNumber, string thousandAndHundredsOfPosition, string hundredThousandAndTenThousandOfPosition)
        {
            if (tenThousandPositionsAndThousandthPercentile.IsErrorData() && decilesAndPercentile.IsErrorData() && tenDigitNumberAndSingleDigitNumber.IsErrorData()
                 && thousandAndHundredsOfPosition.IsErrorData() && hundredThousandAndTenThousandOfPosition.IsErrorData())
                return 0;

            var value = decimal.Parse($"{hundredThousandAndTenThousandOfPosition}{thousandAndHundredsOfPosition}" +
                $"{tenDigitNumberAndSingleDigitNumber}.{decilesAndPercentile}{tenThousandPositionsAndThousandthPercentile}");

            return value;
        }

        /// <summary>
        /// 数据格式A.15
        /// </summary>
        /// <param name="minuteHex"></param>
        /// <param name="hourHex"></param>
        /// <param name="dayHex"></param>
        /// <param name="monthHex"></param>
        /// <param name="yearHex"></param>
        /// <returns></returns>
        public DateTime AnalyzeDataAccordingToA15(string minuteHex, string hourHex, string dayHex, string monthHex, string yearHex)
        {
            var centuryString = (DateTime.Now.Year / 100).ToString();
            var time = DateTime.Parse($"{centuryString}{yearHex}-{monthHex}-{dayHex} {hourHex}:{minuteHex}:00");
            return time;
            //正常转换方式
            //var bin1 = hex1.HexToBin().PadLeft(8, '0');
            //var tenDigitNumberOfMinute = bin1.Substring(0, 4).BinToDec();//十位
            //var singleDigitNumberOfMinute = bin1.Substring(4).BinToDec();//个位
            //var minute = Convert.ToInt32($"{tenDigitNumberOfMinute}{singleDigitNumberOfMinute}");

            //var bin2 = hex2.HexToBin().PadLeft(8, '0');
            //var tenDigitNumberOfHour = bin2.Substring(0, 4).BinToDec();//十位
            //var singleDigitNumberOfHour = bin2.Substring(4).BinToDec();//个位

            //var bin3 = hex3.HexToBin().PadLeft(8, '0');
            //var tenDigitNumberOfDay = bin3.Substring(0, 4).BinToDec();//十位
            //var singleDigitNumberOfDay = bin3.Substring(4).BinToDec();//个位

            //var bin4 = hex4.HexToBin().PadLeft(8, '0');
            //var tenDigitNumberOfMonth = bin4.Substring(0, 4).BinToDec();//十位
            //var singleDigitNumberOfMonth = bin4.Substring(4).BinToDec();//个位

            //var bin5 = hex5.HexToBin().PadLeft(8, '0');
            //var tenDigitNumberOfYear = bin5.Substring(0, 4).BinToDec();//十位
            //var singleDigitNumberOfYear = bin5.Substring(4).BinToDec();//个位
        }


        /// <summary>
        /// 数据格式20
        /// </summary>
        /// <param name="dayHex"></param>
        /// <param name="monthHex"></param>
        /// <param name="yearHex"></param>
        /// <returns></returns>
        public DateTime AnalyzeDataAccordingToA20(string dayHex, string monthHex, string yearHex)
        {
            var centuryString = (DateTime.Now.Year / 100).ToString();
            var time = DateTime.Parse($"{centuryString}{yearHex}-{monthHex}-{dayHex}");
            return time;

        }

        /// <summary>
        /// 数据格式25
        /// </summary>
        /// <param name="percentileAndThousandthPercentile">百分、千分位</param>
        /// <param name="singleDigitNumberAndDeciles">个位、十分位</param>
        /// <param name="hundredDigitNumbersAndTenDigitNumber">百位、十位</param>
        /// <returns></returns>

        public decimal AnalyzeDataAccordingToA25(string percentileAndThousandthPercentile, string singleDigitNumberAndDeciles, string hundredDigitNumbersAndTenDigitNumber)
        {
            if (percentileAndThousandthPercentile.IsErrorData() && singleDigitNumberAndDeciles.IsErrorData() && hundredDigitNumbersAndTenDigitNumber.IsErrorData())
                return 0;

            var bin1 = hundredDigitNumbersAndTenDigitNumber.HexToBin().PadLeft(8, '0');
            var hundredDigitNumbers = bin1.Substring(1, 3).BinToDec();//百位
            var tenDigitNumber = bin1.Substring(4).BinToDec();//十位

            var bin2 = singleDigitNumberAndDeciles.HexToBin().PadLeft(8, '0');
            var singleDigitNumber = bin2.Substring(0, 4).BinToDec();//个位
            var deciles = bin1.Substring(4).BinToDec();//十分位

            var value = decimal.Parse($"{hundredDigitNumbers}{tenDigitNumber}{singleDigitNumber}.{deciles}{percentileAndThousandthPercentile}");
            return value;
        }

        #endregion

        #region 645
        /// <summary>
        /// 解析读取表地址
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public List<string> AnalyzeAmmeterReadMeterAddress_10_105(List<string> dataList)
        {
            var values = new List<string>();
            //表地址
            var addressList = dataList.GetRange(1, 6);
            addressList.Reverse();
            var address = string.Join("", addressList);
            values.Add(address);
            //控制码
            var controlCode = dataList.GetRange(8, 1)[0];
            values.Add(controlCode);
            //长度
            var len = dataList.GetRange(9, 1)[0].HexToDec();
            //values.Add(len.ToString());
            //数据域
            var dataField = dataList.GetRange(10, len);
            if (dataField.Count > 0)
            {
                string dataMark = string.Join("", dataField.GetRange(0, 4).AddHex33());
                values.Add(dataMark);//数据标识
                var readValue = dataField.GetRange(4, len - 4).ReduceHex33();//值
                readValue.Reverse();
                //var valueData = GetValue<List<string>>(readValue, (AppendixEnums)Enum.Parse(typeof(AppendixEnums), dataMark));
                values.AddRange(readValue);
            }
            return values;
        }


        public void AnalyzeAmmeterReadMeterAddress_10_103(List<string> dataList)
        {
            var data = AnalyzeAmmeterReadMeterAddress_10_105(dataList);
            var validData = data[2].Equals("94") ? true : false;
            var remark = validData ? "成功" : "失败";
        }

        public void AnalyzeAutoUpSwtichRead_0A_68(List<string> dataList)
        {
            var isOpen = dataList[4].Equals("55");
        }

        #endregion

        #region 188

        public void AnalyzeWaterMeter188Data(List<string> dataList)
        {
            var waterMeterType = dataList[(int)WaterMeterReadEnum.Type];
            var addressList = dataList.Skip((int)WaterMeterReadEnum.Address).Take(6).ToList();
            addressList.Reverse();
            var address = string.Join("", addressList);
            address = address.Substring(address.Length - 12);
            var controlCode = dataList[(int)WaterMeterReadEnum.ControlCode];
            switch (controlCode)
            {
                case "81":
                    AnalyzeWaterMeterReadData(dataList);
                    break;
                case "84":
                    AnalyzeWaterMeterValueResult(dataList);
                    break;
            }

        }

        /// <summary>
        /// 解析水表读数据
        /// </summary>
        /// <param name="dataList"></param>
        public void AnalyzeWaterMeterReadData(List<string> dataList)
        {
            var accumulativeWaterflowList = dataList.Skip((int)WaterMeterReadEnum.AccumulativeWaterflow).Take(5).ToList();
            //xxxxxx.xx 
            var accumulativeWaterflow = decimal.Parse(
                $"{accumulativeWaterflowList[3]}{accumulativeWaterflowList[2]}{accumulativeWaterflowList[1]}." +
                $"{accumulativeWaterflowList[0]}");
        }

        /// <summary>
        /// 解析水表阀控结果
        /// </summary>
        /// <param name="dataList"></param>
        public bool AnalyzeWaterMeterValueResult(List<string> dataList)
        {
            return true;
        }

        #endregion
    }
}
