using System;
using System.Collections.Generic;
using System.Linq;
using CNCSystem.Data.Entities;
using CNCSystem.Models.Device;

namespace CNCSystem.Data.Repositories
{
    public class DeviceRepository
    {
        private readonly CNCBusinessDbContext _context;

        public DeviceRepository(CNCBusinessDbContext context)
        {
            _context = context;
        }

        public List<CNCDevice> GetAllDevices()
        {
            return _context.Devices.ToList();
        }

        public CNCDevice GetDeviceById(int id)
        {
            return _context.Devices.Find(id);
        }

        public CNCDevice GetDeviceByCode(string deviceCode)
        {
            return _context.Devices.FirstOrDefault(d => d.DeviceCode == deviceCode);
        }

        public CNCDevice CreateDevice(CNCDevice device)
        {
            _context.Devices.Add(device);
            _context.SaveChanges();
            return device;
        }

        public CNCDevice UpdateDevice(CNCDevice device)
        {
            _context.Entry(device).State = System.Data.Entity.EntityState.Modified;
            _context.SaveChanges();
            return device;
        }

        public void DeleteDevice(int id)
        {
            var device = _context.Devices.Find(id);
            if (device != null)
            {
                _context.Devices.Remove(device);
                _context.SaveChanges();
            }
        }

        public List<CNCDevice> GetOnlineDevices()
        {
            return _context.Devices.Where(d => d.IsOnline).ToList();
        }

        public List<CNCDevice> GetAvailableDevices()
        {
            return _context.Devices.Where(d => d.IsAvailable).ToList();
        }

        public void UpdateDeviceStatus(int deviceId, bool isOnline)
        {
            var device = _context.Devices.Find(deviceId);
            if (device != null)
            {
                device.IsOnline = isOnline;
                device.UpdatedAt = DateTime.Now;
                _context.SaveChanges();
            }
        }

        public void UpdateLastCollectionTime(int deviceId, DateTime collectionTime)
        {
            var device = _context.Devices.Find(deviceId);
            if (device != null)
            {
                device.LastCollectionTime = collectionTime;
                device.UpdatedAt = DateTime.Now;
                _context.SaveChanges();
            }
        }
    }

    public class DeviceStatusRepository
    {
        private readonly CNCBusinessDbContext _context;

        public DeviceStatusRepository(CNCBusinessDbContext context)
        {
            _context = context;
        }

        public List<DeviceStatus> GetDeviceStatuses(int deviceId, DateTime? startTime = null, DateTime? endTime = null)
        {
            var query = _context.DeviceStatus.Where(ds => ds.DeviceId == deviceId);

            if (startTime.HasValue)
            {
                query = query.Where(ds => ds.RecordTime >= startTime.Value);
            }

            if (endTime.HasValue)
            {
                query = query.Where(ds => ds.RecordTime <= endTime.Value);
            }

            return query.OrderByDescending(ds => ds.RecordTime).ToList();
        }

        public DeviceStatus GetLatestDeviceStatus(int deviceId)
        {
            return _context.DeviceStatus
                .Where(ds => ds.DeviceId == deviceId)
                .OrderByDescending(ds => ds.RecordTime)
                .FirstOrDefault();
        }

        public DeviceStatus CreateDeviceStatus(DeviceStatus status)
        {
            _context.DeviceStatus.Add(status);
            _context.SaveChanges();
            return status;
        }

        public void DeleteOldDeviceStatuses(int deviceId, DateTime cutoffDate)
        {
            var oldStatuses = _context.DeviceStatus
                .Where(ds => ds.DeviceId == deviceId && ds.RecordTime < cutoffDate)
                .ToList();

            _context.DeviceStatus.RemoveRange(oldStatuses);
            _context.SaveChanges();
        }
    }

    public class DeviceCurrentStatusRepository
    {
        private readonly CNCBusinessDbContext _context;
        private readonly DeviceStatusRepository _statusRepository;

        public DeviceCurrentStatusRepository(CNCBusinessDbContext context)
        {
            _context = context;
            _statusRepository = new DeviceStatusRepository(context);
        }

        public DeviceCurrentStatus GetDeviceCurrentStatus(int deviceId)
        {
            var device = _context.Devices.Find(deviceId);
            if (device == null) return null;

            var latestStatus = _statusRepository.GetLatestDeviceStatus(deviceId);

            return new DeviceCurrentStatus
            {
                DeviceId = deviceId,
                IsOnline = device.IsOnline,
                IsAvailable = device.IsAvailable,
                Status = latestStatus?.Status ?? "未知",
                IsRunning = latestStatus?.IsRunning ?? false,
                NCProgram = latestStatus?.NCProgram,
                CumulativeCount = latestStatus?.CumulativeCount ?? 0,
                OperatingMode = latestStatus?.OperatingMode,
                RecordTime = latestStatus?.RecordTime ?? DateTime.Now,
                Tags = new List<TagData>() // 这里需要根据实际数据填充
            };
        }

        public List<DeviceCurrentStatus> GetAllDeviceCurrentStatuses()
        {
            var devices = _context.Devices.ToList();
            var statuses = new List<DeviceCurrentStatus>();

            foreach (var device in devices)
            {
                var status = GetDeviceCurrentStatus(device.Id);
                if (status != null)
                {
                    status.DeviceId = device.Id;
                    status.DeviceCode = device.DeviceCode;
                    status.DeviceName = device.DeviceName;
                    statuses.Add(status);
                }
            }

            return statuses;
        }
    }
}