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.Protocol3761;
using Microsoft.Extensions.Logging;

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0AH
{
    /// <summary>
    /// 5.10.1.3.1 F10：终端电能表/交流采样装置配置参数
    /// </summary>
    internal class AFN10_F10_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN10_F10_Analysis> _logger;

        public AFN10_F10_Analysis(ILogger<AFN10_F10_Analysis> logger)
        {
            _logger = logger;
        }
        public Task<bool> ExecuteAsync(TB3761 input, Action<dynamic>? result = null)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(input);
                ArgumentNullException.ThrowIfNull(input.UnitData.HexMessageList);
                Tuple<int, List<AFN10F10Entity>> tuple = AFN10F10EntityAnalysis(input.UnitData.HexMessageList);
                UnitDataAnalysis<AFN10_F10_AnalysisDto> dto = new UnitDataAnalysis<AFN10_F10_AnalysisDto>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = new AFN10_F10_AnalysisDto()
                    {
                        AFN10F10Entitys = tuple.Item2,
                        ConfigNum = tuple.Item1
                    },
                    HexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime
                };
                result?.Invoke(dto);
                return Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0A_10解析失败:{input.A?.Code}-{input.DT?.Fn ?? 0}-{input?.BaseHexMessage?.HexMessageString},{ex.Message}");
            }
            return Task.FromResult(false);
        }

        public Tuple<int, List<AFN10F10Entity>> AFN10F10EntityAnalysis(List<string> hexMessageList)
        {
            List<Dictionary<string, string>> meterList = new List<Dictionary<string, string>>();
            int total = $"{hexMessageList[5]}{hexMessageList[4]}".HexToDec();
            List<AFN10F10Entity> aFN10F10Entitys = new List<AFN10F10Entity>();
            for (int i = 0; i < total; i++)
            {
                List<string> sArray = hexMessageList.GetRange(6 + 27 * i, 27);
                AFN10F10Entity aFN10F10Entity = new AFN10F10Entity()
                {
                    SerialNum = $"{sArray[1]}{sArray[0]}".HexToDec(),
                    Point = $"{sArray[3]}{sArray[2]}".HexToDec(),
                    RuleType= GetProtocol(sArray[5]),
                    ComAddress= $"{sArray[11]}{sArray[10]}{sArray[9]}{sArray[8]}{sArray[7]}{sArray[6]}",
                    ComPwd= $"{sArray[17]}{sArray[16]}{sArray[15]}{sArray[14]}{sArray[13]}{sArray[12]}".Substring(6, 6),
                    ElectricityRatesNum= sArray[18].HexToBin().Substring(2, 6).BinToDec(),
                    CollectorAddress = $"{sArray[25]}{sArray[24]}{sArray[23]}{sArray[22]}{sArray[21]}{sArray[20]}",

                };

                string baudPort = sArray[4].HexToBin().PadLeft(8, '0'); //波特率和端口号放在一个字节内
                aFN10F10Entity.BaudRate = GetBaudrate(baudPort.Substring(0, 3));
                aFN10F10Entity.Port = baudPort.Substring(3, 5).BinToDec();

                string dataDigit = sArray[19].HexToBin().PadLeft(8, '0'); //有功电能示值整数位及小数位个数
                aFN10F10Entity.IntegerBitsNum = dataDigit.Substring(4, 2).BinToDec() + 4;
                aFN10F10Entity.DecimalPlacesNum = dataDigit.Substring(6, 2).BinToDec() + 1;

                string classNo = sArray[26].HexToBin().PadLeft(8, '0');//用户大类号及用户小类号
                aFN10F10Entity.UserCategoryNum = classNo.Substring(0, 4).BinToDec() + 1;
                aFN10F10Entity.UserCategoryNum = classNo.Substring(4, 4).BinToDec() + 1;
                aFN10F10Entitys.Add(aFN10F10Entity);
            }
            return Tuple.Create(total, aFN10F10Entitys);
        }

        /// <summary>
        /// 获取波特率
        /// </summary>
        /// <param name="binBaud"></param>
        /// <returns></returns>
        private int GetBaudrate(string binBaud)
        {
            int baudRate = 0;
            switch (binBaud)
            {
                case "001":
                    baudRate = 600;
                    break;
                case "010":
                    baudRate = 1200;
                    break;
                case "011":
                    baudRate = 2400;
                    break;
                case "100":
                    baudRate = 4800;
                    break;
                case "101":
                    baudRate = 7200;
                    break;
                case "110":
                    baudRate = 9600;
                    break;
                case "111":
                    baudRate = 19200;
                    break;
                default:
                    baudRate = 0;
                    break;
            }
            return baudRate;
        }

        /// <summary>
        /// 获取通信协议文本说明
        /// </summary>
        /// <param name="protocol"></param>
        /// <returns></returns>
        private string GetProtocol(string protocol)
        {
            int dataUnit = protocol.HexToDec();

            if (dataUnit == 1)
            {
                return "DL/T 645—1997";
            }
            if (dataUnit == 2)
            {
                return "交流采样装置通信协议";
            }
            if (dataUnit == 30)
            {
                return "DL/T 645—2007";
            }
            if (dataUnit == 31)
            {
                return "串行接口连接窄带低压载波通信模块";
            }
            if (dataUnit == 32)
            {
                return "CJ/T 188—2018协议";
            }
            return "其他协议";
        }

        
    }
}
