using DeviceDetectorNET.Parser.Device;
using GatherService.WattMeter.AnalysisData.AFN_10H;
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.Appendix;
using JiShe.CollectBus.Protocol3761;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FreeSql.Internal.GlobalFilter;

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H
{
    /// <summary>
    /// 透抄 电网频率
    /// </summary>
    public class AFN16_F97_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN16_F97_Analysis> _logger;
        private readonly AnalysisStrategyContext _analysisStrategyContext;
        private readonly DataStorage _dataStorage;
        public AFN16_F97_Analysis(ILogger<AFN16_F97_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.A.Code);
                ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList);

                List<string> datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList);
                AnalysisBaseDto<decimal?> data = GenerateFinalResult(datas);

                // 查询设备信息
                DeviceInfo? deviceInfo = await _dataStorage.GetDeviceInfoAsync(input.A.Code, input.DA.Pn, datas[1]);
                if (deviceInfo != null)
                {
                    data.ProjectId = deviceInfo.ProjectID;
                    data.DeviceId = deviceInfo.MeterId;
                    data.DatabaseBusiID = deviceInfo.DatabaseBusiID;
                    data.DeviceAddress = deviceInfo.MeterAddress;
                    data.FocusId = deviceInfo.FocusId;
                }
                UnitDataAnalysis<AnalysisBaseDto<decimal?>> unitDataAnalysis = new UnitDataAnalysis<AnalysisBaseDto<decimal?>>
                {
                    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 = data,
                    ReceivedHexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    TimeDensity = 1,//密度-间隔,
                    DensityUnit = DensityUnit.Hour,
                    ReceivedTime = input.ReceivedTime,
                    DataType = IOTDBDataTypeConst.Data

                };
                result?.Invoke(unitDataAnalysis);
                await _dataStorage.SaveDataToIotDbAsync<decimal?>(unitDataAnalysis);

                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"10_97解析失败:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString},{ex.Message}");
                return await Task.FromResult(false);
            }
        }

        private AnalysisBaseDto<decimal?> GenerateFinalResult(List<string> data)
        {
            AnalysisBaseDto<decimal?> meter = new AnalysisBaseDto<decimal?>();
            meter.DeviceType = MeterTypeEnum.Ammeter;
            var errorCode = data[4].CheckErrorCode();
            if (errorCode != null)
            {
                meter.ValidData = false;
                meter.ErrorCodeMsg = errorCode.Item2;
            }
            else
            {
                if(decimal.TryParse(data[4], out decimal value))
                    meter.DataValue = value;
            }
             
            meter.ItemType = T37612012PacketItemCodeConst.AFN10HFN97H;
            meter.ValidData = data[2].Equals("91") || data[2].Equals("B1");
            meter.FiledDesc = "电网频率";//"电网频率";
            meter.FiledName = meter.ItemType.GetDataFieldByGatherDataType() ?? string.Empty;
            return meter;
        }
        private async Task<List<string>> AnalysisDataUnitAsync(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].HexToDec();
            //values.Add(len.ToString());
            //TODO:数据域
            var dataField = contentArr.GetRange(10, len);
            if (dataField.Count > 0)
            {
                string dataMark = string.Join("",dataField.GetRange(0, 4).ReduceHex33(true));
                values.Add(dataMark);//数据标识
                var readValue = dataField.GetRange(4, len - 4).ReduceHex33(true);//值
                await _analysisStrategyContext.ExecuteAsync<List<string>>($"Appendix_{dataMark}", readValue, (value) =>
                {
                    values.Add(value.ToString());
                });
            }
            return values;
        }
    }
}
