using System.Text;
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;

namespace JiShe.CollectBus.Protocol.AnalysisData.AFN_09H
{
    /// <summary>
    /// 5.9.1.2 F1:终端版本信息 
    /// </summary>
    public class AFN9_F1_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN9_F1_Analysis> _logger;

        private readonly DataStorage _dataStorage;

        public AFN9_F1_Analysis(ILogger<AFN9_F1_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 version = AnalysisDataUnit(input.UnitData.HexMessageList);
                version.AreaCode = input.A.Code?.Substring(0, 4);
                version.Address = input.A.Code?.Substring(4, 5);
                var data = new AnalysisBaseDto<AFN9_F1_AnalysisDto?>()
                {
                    FiledDesc = "终端版本信息",
                    DataValue = version,
                    ItemType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"
                };
                // 查询设备信息
                DeviceInfo? deviceInfo = await _dataStorage.GetDeviceInfoAsync(input.A.Code);
                if (deviceInfo != null)
                {
                    data.ProjectId = deviceInfo.ProjectID;
                    data.DeviceId = deviceInfo.FocusId;
                    data.DatabaseBusiID = deviceInfo.DatabaseBusiID;
                    data.DeviceAddress = deviceInfo.FocusAddress;
                    data.DeviceType = MeterTypeEnum.Focus;
                    data.FocusId = deviceInfo.FocusId;
                }
                UnitDataAnalysis<AnalysisBaseDto<AFN9_F1_AnalysisDto?>> dto = new UnitDataAnalysis<AnalysisBaseDto<AFN9_F1_AnalysisDto?>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = data,
                    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, $"09_1解析失败:{input.A?.Code}-{input.DT?.Fn ?? 0}-{input?.BaseHexMessage?.HexMessageString},{ex.Message}");
            }
            return await Task.FromResult(false);
        }

        private AFN9_F1_AnalysisDto AnalysisDataUnit(List<string> hexMessageList)
        {
            AFN9_F1_AnalysisDto version = new AFN9_F1_AnalysisDto();
            version.MakerNo = Encoding.ASCII.GetString(string.Join("", hexMessageList.Skip(4).Take(4).ToList()).HexToByte());//厂商代号
            version.DeviceNo = Encoding.ASCII.GetString(string.Join("", hexMessageList.Skip(8).Take(8).ToList()).HexToByte()).Replace("\0", "");//设备编号
            version.SoftwareVersion = Encoding.ASCII.GetString(string.Join("", hexMessageList.Skip(16).Take(4).ToList()).HexToByte());//终端软件版本号
            version.HardwareVersion = Encoding.ASCII.GetString(string.Join("", hexMessageList.Skip(38).Take(4).ToList()).HexToByte());//终端硬件版本号
            version.AddDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var dateArr = hexMessageList.Skip(20).Take(3).ToList();
            var dateArr2 = hexMessageList.Skip(42).Take(3).ToList();
            dateArr.Reverse();
            dateArr2.Reverse();
            version.SoftwareReleaseDate = $"{DateTime.Now.Year.ToString().Substring(0, 2)}{string.Join("-", dateArr)}";//终端软件发布日期：日月年
            version.HardwareReleaseDate = $"{DateTime.Now.Year.ToString().Substring(0, 2)}{string.Join("-", dateArr2)}";//终端硬件发布日期：日月年
            return version;
        }
    }
}
