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.Protocol3761;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0EH
{
    /// <summary>
    /// 请求重要事件
    /// Item1=停电事件
    /// Item2=上电事件
    /// </summary>
    public class AFN14_F1_Analysis : IAnalysisStrategy<TB3761>
    {
        private readonly ILogger<AFN14_F1_Analysis> _logger;
        private readonly DataStorage _dataStorage;
        public AFN14_F1_Analysis(ILogger<AFN14_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);
                int erc = input.UnitData.HexMessageList![8].HexToDec();
                bool isOnOffPower = erc.Equals(14) ? true : false;
                if (!isOnOffPower)
                {
                    // TODO：非终端停/上电事件直接确认
                    _logger.LogWarning($"0E_1解析ERC{erc}非终端停/上电事件:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString}");
                    return await Task.FromResult(true);
                }

                List<AnalysisBaseDto<string>> list = AnalysisDataUnit(input.UnitData.HexMessageList);
                if (list.Count > 0)
                {
                    // 查询设备信息
                    DeviceInfo? deviceInfo = await _dataStorage.GetDeviceInfoAsync(input.A.Code);
                    if (deviceInfo != null)
                    {
                        list.ForEach(item =>
                        {
                            item.ProjectId = deviceInfo.ProjectID;
                            item.DeviceId = deviceInfo.MeterId;
                            item.DatabaseBusiID = deviceInfo.DatabaseBusiID;
                            item.DeviceAddress = deviceInfo.MeterAddress;
                            item.DeviceType = MeterTypeEnum.Focus;
                            item.FocusId = deviceInfo.FocusId;
                        });
                    }
                }
                UnitDataAnalysis<List<AnalysisBaseDto<string>>> dto = new UnitDataAnalysis<List<AnalysisBaseDto<string>>>
                {
                    Code = input.A.Code!,
                    AFN = input.AFN_FC.AFN,
                    Fn = input.DT.Fn,
                    Pn = input.DA.Pn,
                    Data = list,
                    ReceivedHexMessage = input.BaseHexMessage.HexMessageString,
                    MessageId = input.MessageId,
                    ReceivedTime = input.ReceivedTime,
                    DensityUnit = DensityUnit.None,
                    TimeDensity = -1,
                    DataType = IOTDBDataTypeConst.Event,
                };
                //  meterData.DataType = "0E_1";
                result?.Invoke(dto);
                await _dataStorage.SaveMultipleStatusToIotDbAsync<string>(dto);
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"0E_1解析失败:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString},{ex.Message}");
            }
            return await Task.FromResult(false);
        }

        private List<AnalysisBaseDto<string>> AnalysisDataUnit(List<string> hexMessageList)
        {
            /// Item1=停电事件
            /// Item2=上电事件
            List <AnalysisBaseDto<string>> values = new List<AnalysisBaseDto<string>>
            {
                new AnalysisBaseDto<string>
                {
                    FiledDesc = "停电事件",
                    FiledName = "Type",
                    DataValue = "PowerDownEvent",
                    TimeSpan=HandlerTime(hexMessageList.GetRange(10, 5))
                },
                new AnalysisBaseDto<string>
                {
                    FiledDesc = "上电事件",
                    FiledName = "Type",
                    DataValue = "PowerOnEvent",
                    TimeSpan=HandlerTime(hexMessageList.GetRange(15, 5))
                }
            };
            return values;
        }
        /// <summary>
        /// /解析时间
        /// </summary>
        /// <param name="times"></param>
        /// <returns></returns>
        private DateTime? HandlerTime(List<string> times)
        {
            try
            {
                times.Reverse();
                string time = $"{DateTime.Now.ToString("yyyy").Substring(0, 2)}{times[0]}-{times[1]}-{times[2]} {times[3]}:{times[4]}:00";
                DateTime.TryParse(time, out DateTime dateTime);
                return dateTime;
            }
            catch { }
            return null;
        }
    }
}

