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

namespace CncService.Impl
{
    /// <summary>
    /// 车间管理实现
    /// </summary>
    public class WorkshopService : IWorkshopService
    {
        private readonly IWorkshopRepository _workshopRepository;

        public WorkshopService(IWorkshopRepository workshopRepository)
        {
            _workshopRepository = workshopRepository ?? throw new ArgumentNullException(nameof(workshopRepository));
        }

        /// <inheritdoc/>
        public List<WorkshopListItem> GetList(string keyword)
        {
            var paged = _workshopRepository.GetList(keyword ?? string.Empty);
            // WorkshopRepository.GetList返回PagedResult<Workshop>，转换为WorkshopListItem
            return paged.Items.Select(w => new WorkshopListItem
            {
                Id = w.Id,
                Name = w.Name,
                SortOrder = w.SortOrder,
                IsEnabled = w.IsEnabled == 1,
                MachineCount = _workshopRepository.GetMachineCount(w.Id)
            }).ToList();
        }

        /// <inheritdoc/>
        public Workshop GetById(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的车间ID");
            var w = _workshopRepository.GetById(id);
            if (w == null) throw new BusinessException(ErrorCode.NotFound, "车间未找到");
            return w;
        }

        /// <inheritdoc/>
        public int Create(CreateWorkshopRequest request)
        {
            if (request == null) throw new BusinessException(ErrorCode.BadRequest, "请求参数不能为空");
            if (string.IsNullOrWhiteSpace(request.Name)) throw new BusinessException(ErrorCode.BadRequest, "车间名称不能为空");
            // 唯一性检查
            var existing = _workshopRepository.GetList(request.Name);
            if (existing.Items.Any(w => string.Equals(w.Name, request.Name, StringComparison.OrdinalIgnoreCase)))
                throw new BusinessException(ErrorCode.Conflict, "车间名称已存在");

            var entity = new Workshop
            {
                Name = request.Name,
                SortOrder = request.SortOrder,
                IsEnabled = 1,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            return _workshopRepository.Create(entity);
        }

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

            entity.Name = request.Name ?? entity.Name;
            entity.SortOrder = request.SortOrder;
            entity.UpdatedAt = DateTime.Now;
            return _workshopRepository.Update(entity);
        }

        /// <inheritdoc/>
        public bool Delete(int id)
        {
            if (id <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的车间ID");
            int machineCount = _workshopRepository.GetMachineCount(id);
            if (machineCount > 0) throw new BusinessException(ErrorCode.DataReferenced, "车间下有机床，无法删除");
            return _workshopRepository.Delete(id);
        }

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

        /// <inheritdoc/>
        public int GetMachineCount(int workshopId)
        {
            if (workshopId <= 0) throw new BusinessException(ErrorCode.BadRequest, "无效的车间ID");
            return _workshopRepository.GetMachineCount(workshopId);
        }
    }
}
