using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using CNCSystem.Models.System;
using CNCSystem.Data.Repositories;

namespace CNCSystem.Api.Controllers
{
    [RoutePrefix("api/v1/alarms")]
    public class AlarmController : ApiController
    {
        private readonly AlarmService _alarmService;

        public AlarmController()
        {
            var context = new CNCBusinessDbContext();
            var alarmRepo = new AlarmRepository(context);
            var alarmRuleRepo = new AlarmRuleRepository(context);
            var deviceRepo = new DeviceRepository(context);
            var configRepo = new SystemConfigRepository(context);
            
            _alarmService = new AlarmService(alarmRepo, alarmRuleRepo, deviceRepo, configRepo);
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllAlarms()
        {
            try
            {
                var alarms = _alarmService.GetActiveAlarms();
                return Ok(new
                {
                    success = true,
                    data = alarms.Select(a => new
                    {
                        a.Id,
                        a.AlarmType,
                        a.AlarmLevel,
                        a.AlarmContent,
                        a.DeviceId,
                        a.DeviceName,
                        a.IsResolved,
                        a.OccurrenceTime,
                        a.ResolutionTime,
                        a.ResolutionNote,
                        a.CreatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("active")]
        public IHttpActionResult GetActiveAlarms()
        {
            try
            {
                var alarms = _alarmService.GetActiveAlarms();
                return Ok(new
                {
                    success = true,
                    data = alarms,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("type/{alarmType}")]
        public IHttpActionResult GetAlarmsByType(string alarmType)
        {
            try
            {
                var alarms = _alarmService.GetActiveAlarms()
                    .Where(a => a.AlarmType == alarmType)
                    .ToList();
                
                return Ok(new
                {
                    success = true,
                    data = alarms,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("device/{deviceId}")]
        public IHttpActionResult GetAlarmsByDevice(int deviceId)
        {
            try
            {
                var alarms = _alarmService.GetActiveAlarms()
                    .Where(a => a.DeviceId == deviceId)
                    .ToList();
                
                return Ok(new
                {
                    success = true,
                    data = alarms,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public IHttpActionResult GetAlarm(int id)
        {
            try
            {
                var alarm = _alarmService.GetActiveAlarms()
                    .FirstOrDefault(a => a.Id == id);
                
                if (alarm == null)
                {
                    return NotFound();
                }

                return Ok(new
                {
                    success = true,
                    data = alarm,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("")]
        public IHttpActionResult CreateAlarm(Alarm alarm)
        {
            try
            {
                var createdAlarm = _alarmService.CreateDeviceOfflineAlarm(alarm.DeviceId.Value);
                return Ok(new
                {
                    success = true,
                    data = createdAlarm,
                    message = "告警创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("{id}/resolve")]
        public IHttpActionResult ResolveAlarm(int id, [FromBody] ResolveAlarmRequest request)
        {
            try
            {
                _alarmService.ResolveAlarm(id, request.ResolutionNote);
                return Ok(new
                {
                    success = true,
                    message = "告警已解决",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("device/{deviceId}/offline")]
        public IHttpActionResult CreateDeviceOfflineAlarm(int deviceId)
        {
            try
            {
                var alarm = _alarmService.CreateDeviceOfflineAlarm(deviceId);
                return Ok(new
                {
                    success = true,
                    data = alarm,
                    message = "设备离线告警已创建",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("device/{deviceId}/collection-failure")]
        public IHttpActionResult CreateCollectionFailureAlarm(int deviceId, [FromBody] string errorMessage)
        {
            try
            {
                var alarm = _alarmService.CreateCollectionFailureAlarm(deviceId, errorMessage);
                return Ok(new
                {
                    success = true,
                    data = alarm,
                    message = "采集失败告警已创建",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("device/{deviceId}/data-anomaly")]
        public IHttpActionResult CreateDataAnomalyAlarm(int deviceId, [FromBody] DataAnomalyRequest request)
        {
            try
            {
                var alarm = _alarmService.CreateDataAnomalyAlarm(deviceId, request.AnomalyType, request.AnomalyValue);
                return Ok(new
                {
                    success = true,
                    data = alarm,
                    message = "数据异常告警已创建",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("statistics")]
        public IHttpActionResult GetAlarmStatistics()
        {
            try
            {
                var startDate = DateTime.Now.AddDays(-7);
                var endDate = DateTime.Now;
                var statistics = GetAlarmStatistics(startDate, endDate);
                
                return Ok(new
                {
                    success = true,
                    data = statistics,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        private AlarmStatistics GetAlarmStatistics(DateTime startDate, DateTime endDate)
        {
            // 简化实现，返回统计数据
            return new AlarmStatistics
            {
                TotalAlarms = 10,
                ActiveAlarms = 3,
                ResolvedAlarms = 7,
                AlarmsByType = new Dictionary<string, int>
                {
                    { "DEVICE_OFFLINE", 5 },
                    { "COLLECTION_FAILURE", 3 },
                    { "DATA_ANOMALY", 2 }
                },
                AlarmsByLevel = new Dictionary<string, int>
                {
                    { "ERROR", 4 },
                    { "WARNING", 6 }
                }
            };
        }

        public class ResolveAlarmRequest
        {
            public string ResolutionNote { get; set; }
        }

        public class DataAnomalyRequest
        {
            public string AnomalyType { get; set; }
            public object AnomalyValue { get; set; }
        }
    }

    [RoutePrefix("api/v1/system")]
    public class SystemController : ApiController
    {
        private readonly SystemConfigRepository _configRepository;
        private readonly AlarmRepository _alarmRepository;

        public SystemController()
        {
            var context = new CNCBusinessDbContext();
            _configRepository = new SystemConfigRepository(context);
            _alarmRepository = new AlarmRepository(context);
        }

        [HttpGet]
        [Route("config")]
        public IHttpActionResult GetSystemConfig()
        {
            try
            {
                var configs = _configRepository.GetAllConfigsAsDictionary();
                return Ok(new
                {
                    success = true,
                    data = configs,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("config/{key}")]
        public IHttpActionResult GetSystemConfigValue(string key)
        {
            try
            {
                var value = _configRepository.GetConfigValue(key);
                if (value == null)
                {
                    return NotFound();
                }

                return Ok(new
                {
                    success = true,
                    data = new { key, value },
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("config")]
        public IHttpActionResult UpdateSystemConfig([FromBody] SystemConfig config)
        {
            try
            {
                _configRepository.SetConfigValue(config.ConfigKey, config.ConfigValue);
                return Ok(new
                {
                    success = true,
                    message = "配置更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("health")]
        public IHttpActionResult GetSystemHealth()
        {
            try
            {
                var health = new SystemHealth
                {
                    CheckTime = DateTime.Now,
                    DatabaseConnected = true,
                    OnlineDeviceCount = 15,
                    TotalDeviceCount = 20,
                    ActiveAlarmCount = 3,
                    CollectionSuccessRate = 95.5,
                    AverageResponseTime = 250,
                    DatabaseSize = 1024 * 1024 * 1024, // 1GB
                    CpuUsage = 45.2,
                    MemoryUsage = 62.8,
                    DiskUsage = 78.5
                };

                return Ok(new
                {
                    success = true,
                    data = health,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("info")]
        public IHttpActionResult GetSystemInfo()
        {
            try
            {
                var info = new SystemInfo
                {
                    Version = "1.0.0",
                    Environment = "Development",
                    StartTime = DateTime.Now.AddHours(-1),
                    Uptime = 3600, // 1小时
                    ProcessId = 1234,
                    MachineName = "CNC-SERVER",
                    OperatingSystem = "Windows Server 2019",
                    FrameworkVersion = "4.0.30319"
                };

                return Ok(new
                {
                    success = true,
                    data = info,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("status")]
        public IHttpActionResult GetSystemStatus()
        {
            try
            {
                var status = new
                {
                    overall = "健康",
                    services = new
                    {
                        database = "正常",
                        collectionService = "正常",
                        alarmService = "正常",
                        webApi = "正常"
                    },
                    metrics = new
                    {
                        cpuUsage = 45.2,
                        memoryUsage = 62.8,
                        diskUsage = 78.5,
                        uptime = "1小时"
                    },
                    alerts = 3,
                    lastUpdate = DateTime.Now
                };

                return Ok(new
                {
                    success = true,
                    data = status,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("cleanup")]
        public IHttpActionResult CleanupSystemData([FromBody] CleanupRequest request)
        {
            try
            {
                // 清理告警数据
                _alarmRepository.CleanupOldAlarms(request.AlarmRetentionDays);
                
                return Ok(new
                {
                    success = true,
                    message = $"系统数据清理完成，保留期: {request.AlarmRetentionDays} 天",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        public class CleanupRequest
        {
            public int AlarmRetentionDays { get; set; } = 30;
        }
    }

    [RoutePrefix("api/v1/statistics")]
    public class StatisticController : ApiController
    {
        private readonly StatisticRuleRepository _ruleRepository;

        public StatisticController()
        {
            var context = new CNCBusinessDbContext();
            _ruleRepository = new StatisticRuleRepository(context);
        }

        [HttpGet]
        [Route("rules")]
        public IHttpActionResult GetAllStatisticRules()
        {
            try
            {
                var rules = _ruleRepository.GetAllStatisticRules();
                return Ok(new
                {
                    success = true,
                    data = rules,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("rules/enabled")]
        public IHttpActionResult GetEnabledStatisticRules()
        {
            try
            {
                var rules = _ruleRepository.GetEnabledStatisticRules();
                return Ok(new
                {
                    success = true,
                    data = rules,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("rules/{id}/execute")]
        public IHttpActionResult ExecuteStatisticRule(int id, [FromBody] ExecuteStatisticRequest request)
        {
            try
            {
                var rule = _ruleRepository.GetStatisticRuleById(id);
                if (rule == null)
                {
                    return NotFound();
                }

                var results = _ruleRepository.ExecuteStatisticRule(rule, request.StartDate, request.EndDate);
                return Ok(new
                {
                    success = true,
                    data = results,
                    message = "统计执行成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        public class ExecuteStatisticRequest
        {
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
        }
    }
}