using System;
using System.Collections.Generic;
using CncService.Interface;
using CncModels.Dto;
using CncModels.Dto.Machine;
using CncModels.Entity;
using CncModels.Constants;
using CncRepository.Interface;

namespace CncService.Impl
{
    /// <summary>
    /// 机床管理实现
    /// </summary>
    public class MachineService : IMachineService
    {
        private readonly IMachineRepository _machineRepository;
        private readonly ICollectAddressRepository _addressRepository;
        private readonly IWorkerMachineRepository _workerMachineRepository;
        private readonly IBrandRepository _brandRepository;

        public MachineService(
            IMachineRepository machineRepository,
            ICollectAddressRepository addressRepository,
            IWorkerMachineRepository workerMachineRepository,
            IBrandRepository brandRepository)
        {
            _machineRepository = machineRepository ?? throw new ArgumentNullException(nameof(machineRepository));
            _addressRepository = addressRepository ?? throw new ArgumentNullException(nameof(addressRepository));
            _workerMachineRepository = workerMachineRepository ?? throw new ArgumentNullException(nameof(workerMachineRepository));
            _brandRepository = brandRepository ?? throw new ArgumentNullException(nameof(brandRepository));
        }

        /// <inheritdoc/>
        public PagedResult<MachineListItem> GetList(MachineQuery query)
        {
            if (query == null) throw new BusinessException(ErrorCode.BadRequest, "查询参数不能为空");
            return _machineRepository.GetList(query);
        }

        /// <inheritdoc/>
        public MachineDetailResponse GetById(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            var detail = _machineRepository.GetDetailById(id);
            if (detail == null) throw new BusinessException(ErrorCode.NotFound, "机床未找到");
            return detail;
        }

        /// <inheritdoc/>
        public int Create(CreateMachineRequest request)
        {
            if (request == null) throw new BusinessException(ErrorCode.BadRequest, "请求参数不能为空");
            if (string.IsNullOrWhiteSpace(request.DeviceCode)) throw new BusinessException(ErrorCode.BadRequest, "设备编码不能为空");
            // 唯一性校验
            var existing = _machineRepository.GetByDeviceCode(request.DeviceCode);
            if (existing != null) throw new BusinessException(ErrorCode.Conflict, "设备编码已存在");

            var entity = new Machine
            {
                DeviceCode = request.DeviceCode,
                Name = request.Name,
                WorkshopId = request.WorkshopId,
                CollectAddressId = request.CollectAddressId,
                BrandId = request.BrandId,
                IpAddress = request.IpAddress,
                IsEnabled = 1,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            return _machineRepository.Create(entity);
        }

        /// <inheritdoc/>
        public bool Update(int id, UpdateMachineRequest request)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            if (request == null) throw new BusinessException(ErrorCode.BadRequest, "请求参数不能为空");
            var entity = _machineRepository.GetById(id);
            if (entity == null) throw new BusinessException(ErrorCode.NotFound, "机床未找到");

            entity.Name = request.Name ?? entity.Name;
            entity.WorkshopId = request.WorkshopId;
            entity.CollectAddressId = request.CollectAddressId;
            entity.BrandId = request.BrandId;
            entity.IpAddress = request.IpAddress ?? entity.IpAddress;
            entity.UpdatedAt = DateTime.Now;
            return _machineRepository.Update(entity);
        }

        /// <inheritdoc/>
        public bool Delete(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            // 解绑工人
            _workerMachineRepository.DeleteByMachineId(id);
            return _machineRepository.Delete(id);
        }

        /// <inheritdoc/>
        public int BatchDelete(List<int> ids)
        {
            if (ids == null || ids.Count == 0) throw new BusinessException(ErrorCode.BadRequest, "请选择要删除的机床");
            // 先解绑所有关联工人
            foreach (var id in ids)
            {
                _workerMachineRepository.DeleteByMachineId(id);
            }
            return _machineRepository.BatchDelete(ids);
        }

        /// <inheritdoc/>
        public bool ToggleEnabled(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            return _machineRepository.ToggleEnabled(id);
        }

        /// <inheritdoc/>
        public MachineStatusResponse GetStatus(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            var machine = _machineRepository.GetById(id);
            if (machine == null) throw new BusinessException(ErrorCode.NotFound, "机床未找到");
            // 从最新采集记录获取实时状态
            var latest = _machineRepository.GetLatestCollectRecord(id);
            return new MachineStatusResponse
            {
                ProgramName = machine.LastProgramName ?? latest?.ProgramName,
                PartCount = machine.LastPartCount,
                RunStatus = machine.LastRunStatus ?? latest?.RunStatus,
                OperationMode = machine.LastOperateMode,
                SpindleSpeedSet = null,
                FeedSpeedSet = null,
                SpindleSpeedActual = null,
                SpindleLoad = null
            };
        }

        /// <inheritdoc/>
        public List<MachineTodayProdItem> GetTodayProduction(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            var machine = _machineRepository.GetById(id);
            if (machine == null) throw new BusinessException(ErrorCode.NotFound, "机床未找到");
            return _machineRepository.GetTodayProduction(id);
        }

        /// <inheritdoc/>
        public List<MachineTrendItem> GetProductionTrend(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            var machine = _machineRepository.GetById(id);
            if (machine == null) throw new BusinessException(ErrorCode.NotFound, "机床未找到");
            return _machineRepository.GetProductionTrend(id);
        }

        /// <inheritdoc/>
        public List<MachineCollectRecordItem> GetCollectRecords(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的机床ID");
            var machine = _machineRepository.GetById(id);
            if (machine == null) throw new BusinessException(ErrorCode.NotFound, "机床未找到");
            return _machineRepository.GetRecentCollectRecords(id);
        }
    }
}
