using JiShe.CollectBus.Common.Consts;
using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Extensions;
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.Protocol3761;
using Microsoft.Extensions.Logging;
using System.Text;

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H.Ammeter
{
    /// <summary>
    /// 5.16.1.2.1 F1：透明转发 读取SIM卡信息
    /// </summary>
    public class AFN16_F101_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN16_F101_Analysis> _logger;
        private readonly DataStorage _dataStorage;
        public AFN16_F101_Analysis(ILogger<AFN16_F101_Analysis> logger, DataStorage dataStorage)
        {
            _logger = logger;
            _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);
                var data = new AnalysisBaseDto<string?>()
                {
                    FiledDesc = "透读取SIM卡信息",
                    DataValue = AnalysisDataUnit(input.UnitData.HexMessageList),
                    ItemType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"
                };
                // 查询设备信息
                DeviceCacheInfo? deviceInfo = await _dataStorage.GetDeviceInfoAsync(input.A.Code, input.DA.Pn);
                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<string?>> dto = new UnitDataAnalysis<AnalysisBaseDto<string?>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = data, //SIM卡
                    ReceivedHexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime,
                    DensityUnit = DensityUnit.None,
                    TimeDensity = -1,
                    DataType = IOTDBDataTypeConst.Data,
                };
                result?.Invoke(dto);
                await _dataStorage.SaveDataToIotDbAsync(dto);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"10_101解析失败:{input.A?.Code}-{input.DT?.Fn ?? 0}-{input?.BaseHexMessage?.HexMessageString},{ex.Message}");

            }
            return await Task.FromResult(false);
        }
        private string AnalysisDataUnit(List<string> hexMessageList)
        {
            //TODO:转发内容
            var dataArray = hexMessageList.Skip(18).ToList();
            var contentLengthArr = dataArray.Skip(1).Take(2).ToList();
            contentLengthArr.Reverse();
            int contentLength = string.Join("", contentLengthArr).HexToDec();
            var dataField = dataArray.Skip(3).Take(contentLength).ToList();
            var sim = string.Join("", dataField).TrimStart('0');
            return sim.Length != 20 ? "" : sim;
        }
    }
}
