using Coravel.Events.Interfaces;
using InfluxData.Net.Common.Enums;
using InfluxData.Net.InfluxDb;
using InitQ.Cache;
using Microsoft.Extensions.DependencyInjection;
using Quartz.Impl.AdoJobStore.Common;
using Ropin.Core.Common;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Ropin.Environmentally.WebScada.Subscribe
{
    public class DevRunEventListener : IListener<DevEvent>
    {
        private readonly ICacheService _redisService;

        public DevRunEventListener(ICacheService redisService) {
            _redisService = redisService;
        }
        private InfluxDbClient clientDb;
        public async Task HandleAsync(DevEvent broadcasted)
        {
            var msg = broadcasted.Message;
            if(msg == "devrunstart")
            {
                Console.WriteLine($"WriteMessageToConsoleListener receive this message from DevEvent: ${msg}");
                IniInflux();


            }
            if (msg == "devrunend")
            {
                Console.WriteLine($"WriteMessageToConsoleListener receive this message from DevEvent: ${msg}");
                IniInflux();
                DateTime startTime = await _redisService.GetAsync<DateTime>("fanyibox_devStartRun_" + broadcasted.DevId);
                DateTime endTime = await _redisService.GetAsync<DateTime>("fanyibox_devEndRun_" + broadcasted.DevId);



            }

            await Task.CompletedTask;
        }
        private void IniInflux()
        {
            //连接InfluxDb的API地址、账号、密码

            var infuxUrl = "http://localhost:8086/";

            var infuxUser = "admin";

            var infuxPwd = "admin";

            //创建InfluxDbClient实例

            clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest);

        }
        public async Task GetMeanData(string id,DateTime start, DateTime end)
        {

            //传入查询命令,支持多条
            var queries = new[]
            {
                "SELECT mean(Val) FROM fanyidev where (Id ='224873679711261516') and time >"+start+" and time < " + end
            };

            var dbName = "fanyidb";



            //从指定库中查询数据

            var response = await clientDb.Client.QueryAsync(queries, dbName);

            //得到Serie集合对象(返回执行多个查询的结果)

            var series = response.ToList();

            //取出第一条命令的查询结果,是一个集合

            var list = series[0].Values;

            //从集合中取出第一条数据

            var info_model = list.FirstOrDefault();

        }
    }
}