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

namespace CNCSystem.Api.Controllers
{
    [RoutePrefix("api/v1/production")]
    public class ProductionController : ApiController
    {
        private readonly ProductionRepository _productionRepository;

        public ProductionController()
        {
            var context = new CNCBusinessDbContext();
            _productionRepository = new ProductionRepository(context);
        }

        [HttpGet]
        [Route("records")]
        public IHttpActionResult GetProductionRecords(int? deviceId = null, DateTime? startDate = null, 
            DateTime? endDate = null, string ncProgram = null)
        {
            try
            {
                var records = _productionRepository.GetProductionRecords(deviceId, startDate, endDate, ncProgram);
                return Ok(new
                {
                    success = true,
                    data = records.Select(r => new
                    {
                        r.Id,
                        r.DeviceId,
                        r.NCProgram,
                        r.ProductionDate,
                        r.Quantity,
                        r.QualityRate,
                        r.StartTime,
                        r.EndTime,
                        r.OperatorId,
                        r.CreatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("records/{id}")]
        public IHttpActionResult GetProductionRecord(int id)
        {
            try
            {
                var record = _productionRepository.GetProductionRecord(id);
                if (record == null)
                {
                    return NotFound();
                }

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

        [HttpGet]
        [Route("statistics")]
        public IHttpActionResult GetProductionStatistics(DateTime date, int? deviceId = null, string ncProgram = null)
        {
            try
            {
                var statistics = _productionRepository.GetProductionStatistics(date, deviceId, ncProgram);
                return Ok(new
                {
                    success = true,
                    data = statistics,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("program-summary")]
        public IHttpActionResult GetProgramProductionSummary(int deviceId, DateTime date)
        {
            try
            {
                var summaries = _productionRepository.GetProgramProductionSummary(deviceId, date);
                return Ok(new
                {
                    success = true,
                    data = summaries.Select(s => new
                    {
                        s.Id,
                        s.DeviceId,
                        s.NCProgram,
                        s.ProductionDate,
                        s.TotalQuantity,
                        s.ValidQuantity,
                        s.InvalidQuantity,
                        s.QualityRate
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

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

        [HttpGet]
        [Route("today-summary")]
        public IHttpActionResult GetTodayProductionSummary()
        {
            try
            {
                var today = DateTime.Today;
                var summaries = _productionRepository.GetProgramProductionSummary(0, today);
                
                // 如果没有数据，生成汇总数据
                if (!summaries.Any())
                {
                    var records = _productionRepository.GetProductionRecords(null, today, today, null);
                    summaries = records.GroupBy(r => new { r.DeviceId, r.NCProgram })
                        .Select(g => new ProgramProductionSummary
                        {
                            DeviceId = g.Key.DeviceId,
                            NCProgram = g.Key.NCProgram,
                            ProductionDate = today,
                            TotalQuantity = g.Sum(r => r.Quantity),
                            ValidQuantity = g.Sum(r => r.Quantity),
                            InvalidQuantity = 0,
                            QualityRate = 100
                        }).ToList();
                }

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

        [HttpGet]
        [Route("dashboard")]
        public IHttpActionResult GetProductionDashboard()
        {
            try
            {
                var today = DateTime.Today;
                var yesterday = today.AddDays(-1);

                // 获取今日数据
                var todayRecords = _productionRepository.GetProductionRecords(null, today, today, null);
                var todayTotal = todayRecords.Sum(r => r.Quantity);

                // 获取昨日数据
                var yesterdayRecords = _productionRepository.GetProductionRecords(null, yesterday, yesterday, null);
                var yesterdayTotal = yesterdayRecords.Sum(r => r.Quantity);

                // 获取实时数据
                var realtimeData = _productionRepository.GetProductionRealtimeData();
                var onlineDeviceCount = realtimeData.Count(d => d.IsRunning);
                var totalDeviceCount = realtimeData.Count;

                // 计算增长率
                var growthRate = yesterdayTotal > 0 ? 
                    Math.Round((double)(todayTotal - yesterdayTotal) / yesterdayTotal * 100, 2) : 0;

                // 获取设备状态分布
                var deviceStatus = realtimeData.GroupBy(d => d.Status)
                    .ToDictionary(g => g.Key, g => g.Count());

                var dashboardData = new
                {
                    todayProduction = todayTotal,
                    yesterdayProduction = yesterdayTotal,
                    growthRate = growthRate,
                    onlineDeviceCount = onlineDeviceCount,
                    totalDeviceCount = totalDeviceCount,
                    deviceStatus = deviceStatus,
                    topPrograms = todayRecords
                        .GroupBy(r => r.NCProgram)
                        .OrderByDescending(g => g.Sum(r => r.Quantity))
                        .Take(5)
                        .Select(g => new
                        {
                            program = g.Key,
                            quantity = g.Sum(r => r.Quantity),
                            count = g.Count()
                        })
                };

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

        [HttpGet]
        [Route("trend")]
        public IHttpActionResult GetProductionTrend(int deviceId = 0, int days = 7)
        {
            try
            {
                var endDate = DateTime.Today;
                var startDate = endDate.AddDays(-days + 1);

                var records = _productionRepository.GetProductionRecords(
                    deviceId == 0 ? (int?)null : deviceId, 
                    startDate, 
                    endDate, 
                    null);

                var trendData = records
                    .GroupBy(r => r.ProductionDate)
                    .OrderBy(g => g.Key)
                    .Select(g => new
                    {
                        date = g.Key.ToString("yyyy-MM-dd"),
                        quantity = g.Sum(r => r.Quantity),
                        programs = g.GroupBy(r => r.NCProgram)
                            .Select(p => new
                            {
                                program = p.Key,
                                count = p.Sum(r => r.Quantity)
                            })
                    })
                    .ToList();

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

        [HttpGet]
        [Route("quality")]
        public IHttpActionResult GetQualityStatistics(DateTime date, int? deviceId = null)
        {
            try
            {
                var records = _productionRepository.GetProductionRecords(deviceId, date, date, null);
                
                var qualityStats = new
                {
                    date = date.ToString("yyyy-MM-dd"),
                    totalQuantity = records.Sum(r => r.Quantity),
                    averageQualityRate = records.Any() ? 
                        Math.Round(records.Average(r => r.QualityRate), 2) : 100,
                    deviceStats = records
                        .GroupBy(r => r.DeviceId)
                        .Select(g => new
                        {
                            deviceId = g.Key,
                            deviceName = "设备" + g.Key, // 简化实现
                            quantity = g.Sum(r => r.Quantity),
                            qualityRate = Math.Round(g.Average(r => r.QualityRate), 2)
                        })
                };

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

        [HttpPost]
        [Route("cleanup")]
        public IHttpActionResult CleanupOldProductionRecords([FromBody] int retentionDays)
        {
            try
            {
                _productionRepository.CleanupOldProductionRecords(retentionDays);
                return Ok(new
                {
                    success = true,
                    message = $"已清理 {retentionDays} 天前的生产记录",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}