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

namespace CNCSystem.Api.Controllers
{
    [RoutePrefix("api/v1/devices")]
    public class DeviceController : ApiController
    {
        private readonly DeviceRepository _deviceRepository;
        private readonly DeviceStatusRepository _statusRepository;

        public DeviceController()
        {
            var context = new CNCBusinessDbContext();
            _deviceRepository = new DeviceRepository(context);
            _statusRepository = new DeviceStatusRepository(context);
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllDevices()
        {
            try
            {
                var devices = _deviceRepository.GetAllDevices();
                return Ok(new
                {
                    success = true,
                    data = devices.Select(d => new
                    {
                        d.Id,
                        d.DeviceCode,
                        d.DeviceName,
                        d.IPAddress,
                        d.IsOnline,
                        d.IsAvailable,
                        d.LastCollectionTime,
                        d.CreatedAt,
                        d.UpdatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public IHttpActionResult GetDevice(int id)
        {
            try
            {
                var device = _deviceRepository.GetDeviceById(id);
                if (device == null)
                {
                    return NotFound();
                }

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

        [HttpPost]
        [Route("")]
        public IHttpActionResult CreateDevice(CNCDevice device)
        {
            try
            {
                // 验证设备编号唯一性
                var existingDevice = _deviceRepository.GetDeviceByCode(device.DeviceCode);
                if (existingDevice != null)
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "设备编号已存在",
                        timestamp = DateTime.Now
                    });
                }

                var createdDevice = _deviceRepository.CreateDevice(device);
                return Ok(new
                {
                    success = true,
                    data = createdDevice,
                    message = "创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPut]
        [Route("{id}")]
        public IHttpActionResult UpdateDevice(int id, CNCDevice device)
        {
            try
            {
                var existingDevice = _deviceRepository.GetDeviceById(id);
                if (existingDevice == null)
                {
                    return NotFound();
                }

                device.Id = id;
                var updatedDevice = _deviceRepository.UpdateDevice(device);
                return Ok(new
                {
                    success = true,
                    data = updatedDevice,
                    message = "更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public IHttpActionResult DeleteDevice(int id)
        {
            try
            {
                var device = _deviceRepository.GetDeviceById(id);
                if (device == null)
                {
                    return NotFound();
                }

                _deviceRepository.DeleteDevice(id);
                return Ok(new
                {
                    success = true,
                    message = "删除成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}/status")]
        public IHttpActionResult GetDeviceStatus(int id)
        {
            try
            {
                var device = _deviceRepository.GetDeviceById(id);
                if (device == null)
                {
                    return NotFound();
                }

                var status = _statusRepository.GetLatestDeviceStatus(id);
                return Ok(new
                {
                    success = true,
                    data = new
                    {
                        device.Id,
                        device.DeviceCode,
                        device.DeviceName,
                        device.IsOnline,
                        device.IsAvailable,
                        status = status?.Status ?? "未知",
                        isRunning = status?.IsRunning ?? false,
                        ncProgram = status?.NCProgram,
                        cumulativeCount = status?.CumulativeCount ?? 0,
                        operatingMode = status?.OperatingMode,
                        recordTime = status?.RecordTime,
                        lastCollectionTime = device.LastCollectionTime
                    },
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}/status-history")]
        public IHttpActionResult GetDeviceStatusHistory(int id, DateTime? startTime = null, DateTime? endTime = null)
        {
            try
            {
                var statuses = _statusRepository.GetDeviceStatuses(id, startTime, endTime);
                return Ok(new
                {
                    success = true,
                    data = statuses.Select(s => new
                    {
                        s.Id,
                        s.DeviceId,
                        s.Status,
                        s.IsRunning,
                        s.NCProgram,
                        s.CumulativeCount,
                        s.OperatingMode,
                        s.RecordTime
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

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

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

        [HttpPost]
        [Route("{id}/toggle-status")]
        public IHttpActionResult ToggleDeviceStatus(int id, [FromBody] bool isAvailable)
        {
            try
            {
                var device = _deviceRepository.GetDeviceById(id);
                if (device == null)
                {
                    return NotFound();
                }

                device.IsAvailable = isAvailable;
                var updatedDevice = _deviceRepository.UpdateDevice(device);
                return Ok(new
                {
                    success = true,
                    data = updatedDevice,
                    message = $"设备状态已更新为{(isAvailable ? "可用" : "不可用")}",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("{id}/collect")]
        public IHttpActionResult TriggerCollection(int id)
        {
            try
            {
                var device = _deviceRepository.GetDeviceById(id);
                if (device == null)
                {
                    return NotFound();
                }

                // 这里应该触发数据采集逻辑
                // 简化实现，返回成功响应
                return Ok(new
                {
                    success = true,
                    message = "采集任务已触发",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}