using System;
using System.Collections.Generic;
using CncModels.Dto.Dashboard;
using CncRepository.Interface;
using CncService.Interface;

namespace CncService.Impl
{
    /// <summary>
    /// 仪表盘实现
    /// </summary>
    public class DashboardService : IDashboardService
    {
        private readonly IDashboardRepository _dashboardRepository;
        private readonly ICollectorHeartbeatRepository _collectorHeartbeatRepository;
        private readonly IWindowsServiceChecker _serviceChecker;
        private readonly ISysConfigRepository _sysConfigRepository;

        public DashboardService(IDashboardRepository dashboardRepository,
            ICollectorHeartbeatRepository collectorHeartbeatRepository,
            ISysConfigRepository sysConfigRepository,
            IWindowsServiceChecker serviceChecker = null)
        {
            _dashboardRepository = dashboardRepository ?? throw new ArgumentNullException(nameof(dashboardRepository));
            _collectorHeartbeatRepository = collectorHeartbeatRepository ?? throw new ArgumentNullException(nameof(collectorHeartbeatRepository));
            _sysConfigRepository = sysConfigRepository ?? throw new ArgumentNullException(nameof(sysConfigRepository));
            _serviceChecker = serviceChecker;
        }

        /// <inheritdoc/>
        public DashboardSummaryResponse GetSummary()
        {
            return _dashboardRepository.GetSummary();
        }

        /// <inheritdoc/>
        public List<WorkshopProductionResponse> GetWorkshopProduction(DateTime? startDate, DateTime? endDate)
        {
            var s = startDate ?? DateTime.Today;
            var e = endDate ?? DateTime.Today;
            return _dashboardRepository.GetWorkshopProduction(s, e);
        }

        /// <inheritdoc/>
        public List<MachineRankResponse> GetMachineRank(DateTime? startDate, DateTime? endDate, int top = 10, string sortOrder = "desc")
        {
            var s = startDate ?? DateTime.Today;
            var e = endDate ?? DateTime.Today;
            return _dashboardRepository.GetMachineRank(s, e, top, sortOrder);
        }

        /// <inheritdoc/>
        public List<WorkerRankResponse> GetWorkerRank(DateTime? startDate, DateTime? endDate, int top = 10, string sortOrder = "desc")
        {
            var s = startDate ?? DateTime.Today;
            var e = endDate ?? DateTime.Today;
            return _dashboardRepository.GetWorkerRank(s, e, top, sortOrder);
        }

        /// <inheritdoc/>
        public object GetProductionTrend(int days = 7)
        {
            return _dashboardRepository.GetProductionTrend(days);
        }

        /// <inheritdoc/>
        public object GetMachineStatusDistribution()
        {
            return _dashboardRepository.GetMachineStatusDistribution();
        }

        /// <inheritdoc/>
        public List<AlertListItem> GetRecentAlerts(int count = 5)
        {
            return _dashboardRepository.GetRecentAlerts(count);
        }

        /// <summary>从sys_config读取heartbeat_interval，计算心跳超时阈值（间隔×3）</summary>
        private int GetHeartbeatTimeout()
        {
            var cfg = _sysConfigRepository.GetByKey("heartbeat_interval");
            if (cfg != null && int.TryParse(cfg.ConfigValue, out var val) && val > 0)
                return val * 3;
            return 30; // 默认10秒间隔 × 3 = 30秒
        }

        /// <inheritdoc/>
        public object GetCollectorStatus()
        {
            var latest = _collectorHeartbeatRepository.GetLatest("CncCollector");
            int heartbeatTimeoutSeconds = GetHeartbeatTimeout();

            bool heartbeatRunning = false;
            long heartbeatUptime = 0;
            DateTime? lastCollectTime = latest?.LastCollectTime;

            if (latest != null && latest.Status == "running")
            {
                var lastHeartbeat = latest.CreatedAt;
                var elapsed = (DateTime.Now - lastHeartbeat).TotalSeconds;
                heartbeatRunning = elapsed <= heartbeatTimeoutSeconds;
                if (heartbeatRunning)
                    heartbeatUptime = latest.UptimeSeconds ?? 0;
            }

            // 额外的 Windows 服务状态
            string serviceStatusText = "NotInstalled";
            if (_serviceChecker != null)
            {
                var svc = _serviceChecker.GetServiceStatus("CncCollector");
                serviceStatusText = svc.ToString();
            }

            // 组合状态：精确区分5种情况
            string status;
            if (serviceStatusText == "NotInstalled")
            {
                status = "not_installed";
            }
            else if (serviceStatusText == "Stopped" || serviceStatusText == "StartFailed")
            {
                status = "stopped";
            }
            else if (heartbeatRunning)
            {
                status = "running";
            }
            else if (latest != null && latest.Status == "stopped")
            {
                // 引擎主动停止（暂停），心跳status='stopped'
                status = "paused";
            }
            else
            {
                // 服务在运行但心跳超时
                status = "timeout";
            }

            return new {
                status,
                uptimeSeconds = heartbeatRunning ? heartbeatUptime : 0,
                lastCollectTime,
                serviceStatus = serviceStatusText,
                serviceName = "CncCollector",
                serviceMessage = (string)null
            };
        }
    }
}
