using JiShe.CollectBus.Common.Consts;
using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Common.Helpers;
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.AFN_10H.Ammeter;
using JiShe.CollectBus.Protocol3761;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H.Watermeter
{
    /// <summary>
    /// ES_190DC 4G水表读数解析
    /// </summary>
    public class ES190DC_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<ES190DC_Analysis> _logger;
        private readonly DataStorage _dataStorage;
        public ES190DC_Analysis(ILogger<ES190DC_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);

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

                };
                result?.Invoke(unitDataAnalysis);
                await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis);

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

        private List<AnalysisBaseDto<decimal?>> GenerateFinalResult(List<string> hexMessageList)
        {
            List<AnalysisBaseDto<decimal?>> list = new List<AnalysisBaseDto<decimal?>>();
            string address = string.Join("", hexMessageList.Skip(12).Take(7).Reverse());
            if (hexMessageList[19].Contains("81"))
            {
                int count = Convert.ToInt32(hexMessageList[36].HexToDec());
                DateTime startTime = Convert.ToDateTime($"{DateTime.Now.Year.ToString().Substring(0, 2)}{hexMessageList[41]}-{hexMessageList[40]}-{hexMessageList[39]} {hexMessageList[38]}:{hexMessageList[37]}:00");

                List<string> valueArr = hexMessageList.GetRange(42, count * 4);
                int nextIndex = 0;
                for (int i = 1; i <= count; i++)
                {
                    AnalysisBaseDto<decimal?> meter = new AnalysisBaseDto<decimal?>();
                    meter.DeviceType = MeterTypeEnum.WaterMeter;
                    meter.DeviceAddress = address;
                    var arr = valueArr.GetRange(nextIndex, 4);
                    var errorCode = arr[4].CheckErrorCode();
                    if (errorCode != null)
                    {
                        meter.ValidData = false;
                        meter.ErrorCodeMsg = errorCode.Item2;
                    }
                    else
                    {
                        string val = $"{arr[3]}{arr[2]}{arr[1]}.{arr[0]}";
                        if (decimal.TryParse(val, out decimal value))
                            meter.DataValue = value;
                    }
                    string timeSpan = startTime.AddHours(i - 1).ToString("yyyy-MM-dd HH:mm:ss");
                    if (DateTime.TryParse(timeSpan, out DateTime readingDate))
                    {
                        meter.TimeSpan = readingDate;
                    }
                    meter.ItemType = "10_250";
                    meter.FiledDesc = "当前累积流量";
                    meter.FiledName = meter.ItemType.GetDataFieldByGatherDataType() ?? string.Empty;
                    nextIndex += 4;
                }
            }
            return list;
        }
    }
}
