using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ZhonTai.Admin.Core.Dto; using ZhonTai.Admin.Services; using NPP.SmartSchedue.Api.Contracts.Services.Time; using NPP.SmartSchedue.Api.Contracts.Services.Time.Input; using NPP.SmartSchedue.Api.Contracts.Services.Time.Output; using NPP.SmartSchedue.Api.Repositories.Time; using NPP.SmartSchedue.Api.Contracts.Domain.Time; using ZhonTai.DynamicApi; using ZhonTai.DynamicApi.Attributes; using Mapster; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Logging; namespace NPP.SmartSchedue.Api.Services.Time; /// /// 班次规则服务 /// [DynamicApi(Area = "app")] public class ShiftRuleService : BaseService, IShiftRuleService, IDynamicApi { private readonly ShiftRuleRepository _shiftRuleRepository; private readonly ShiftRuleMappingRepository _shiftRuleMappingRepository; private readonly ILogger _logger; public ShiftRuleService( ShiftRuleRepository shiftRuleRepository, ShiftRuleMappingRepository shiftRuleMappingRepository, ILogger logger) { _shiftRuleRepository = shiftRuleRepository; _shiftRuleMappingRepository = shiftRuleMappingRepository; _logger = logger; } /// /// 根据ID获取班次规则详细信息 /// /// 规则ID /// 班次规则详细信息 public async Task GetAsync(long id) { var entity = await _shiftRuleRepository.GetAsync(id); if (entity == null) { return null; } return entity.Adapt(); } /// /// 获取班次规则分页列表 /// /// 查询条件 /// 分页结果 [HttpPost] public async Task> GetPageAsync(PageInput input) { try { return await ExecutePageQueryAsync(input); } catch (Exception ex) { _logger.LogError(ex, "班次规则分页查询异常: {Message}", ex.Message); throw; } } /// /// 返回规则列表数据 /// /// [HttpGet] public async Task> GetListAsync() { try { var list = await _shiftRuleRepository.Select.OrderBy(a => a.RuleType).ToListAsync(); return list; } catch (Exception ex) { _logger.LogError(ex, "班次规则分页查询异常: {Message}", ex.Message); throw; } } /// /// 执行分页查询 /// private async Task> ExecutePageQueryAsync(PageInput input) { var filter = input.Filter; var query = _shiftRuleRepository.Select .WhereIf(!string.IsNullOrWhiteSpace(filter?.RuleName), a => a.RuleName.Contains(filter.RuleName)) .WhereIf(!string.IsNullOrWhiteSpace(filter?.RuleType), a => a.RuleType == filter.RuleType) .WhereIf(filter?.IsEnabled.HasValue == true, a => a.IsEnabled == filter.IsEnabled.Value) .OrderBy(a => a.Id); var list = await query.Count(out var total).Page(input.CurrentPage, input.PageSize).ToListAsync(); var data = list.Adapt>(); return new PageOutput() { List = data, Total = total }; } /// /// 添加班次规则 /// /// 添加输入参数 /// 新创建的规则ID [HttpPost] public async Task AddAsync(ShiftRuleAddInput input) { try { // 验证规则名称是否已存在 var existingRule = await _shiftRuleRepository.Select .Where(r => r.RuleName == input.RuleName) .FirstAsync(); if (existingRule != null) { throw new Exception($"规则名称 '{input.RuleName}' 已存在"); } // 验证生效时间逻辑 if (input.EffectiveStartTime.HasValue && input.EffectiveEndTime.HasValue) { if (input.EffectiveStartTime >= input.EffectiveEndTime) { throw new Exception("生效开始时间必须早于生效结束时间"); } } var entity = input.Adapt(); var result = await _shiftRuleRepository.InsertAsync(entity); _logger.LogInformation($"成功创建班次规则: ID {result.Id}, 名称: {input.RuleName}"); return result.Id; } catch (Exception ex) { _logger.LogError(ex, $"创建班次规则失败: {ex.Message}"); throw; } } /// /// 更新班次规则 /// /// 更新输入参数 /// [HttpPut] public async Task UpdateAsync(ShiftRuleUpdateInput input) { try { var entity = await _shiftRuleRepository.GetAsync(input.Id); if (entity == null) { throw new Exception($"班次规则不存在: ID {input.Id}"); } // 验证规则名称是否与其他规则重复 var existingRule = await _shiftRuleRepository.Select .Where(r => r.RuleName == input.RuleName && r.Id != input.Id) .FirstAsync(); if (existingRule != null) { throw new Exception($"规则名称 '{input.RuleName}' 已存在"); } // 验证生效时间逻辑 if (input.EffectiveStartTime.HasValue && input.EffectiveEndTime.HasValue) { if (input.EffectiveStartTime >= input.EffectiveEndTime) { throw new Exception("生效开始时间必须早于生效结束时间"); } } // 更新实体属性 input.Adapt(entity); await _shiftRuleRepository.UpdateAsync(entity); _logger.LogInformation($"成功更新班次规则: ID {input.Id}, 名称: {input.RuleName}"); } catch (Exception ex) { _logger.LogError(ex, $"更新班次规则失败: ID {input.Id}, 错误: {ex.Message}"); throw; } } /// /// 删除班次规则 /// /// 规则ID /// [HttpDelete] public async Task DeleteAsync(long id) { try { var entity = await _shiftRuleRepository.GetAsync(id); if (entity == null) { throw new Exception($"班次规则不存在: ID {id}"); } // 检查是否有关联的映射关系 var hasMappings = await _shiftRuleMappingRepository.Select .Where(m => m.RuleId == id) .AnyAsync(); if (hasMappings) { throw new Exception($"班次规则 '{entity.RuleName}' 仍有关联的班次映射,无法删除"); } await _shiftRuleRepository.DeleteAsync(id); _logger.LogInformation($"成功删除班次规则: ID {id}, 名称: {entity.RuleName}"); } catch (Exception ex) { _logger.LogError(ex, $"删除班次规则失败: ID {id}, 错误: {ex.Message}"); throw; } } /// /// 软删除班次规则 /// /// 规则ID /// [HttpDelete] public async Task SoftDeleteAsync(long id) { try { var entity = await _shiftRuleRepository.GetAsync(id); if (entity == null) { throw new Exception($"班次规则不存在: ID {id}"); } await _shiftRuleRepository.SoftDeleteAsync(id); _logger.LogInformation($"成功软删除班次规则: ID {id}, 名称: {entity.RuleName}"); } catch (Exception ex) { _logger.LogError(ex, $"软删除班次规则失败: ID {id}, 错误: {ex.Message}"); throw; } } /// /// 批量软删除班次规则 /// /// 规则ID数组 /// [HttpDelete] public async Task BatchSoftDeleteAsync(long[] ids) { try { if (ids == null || ids.Length == 0) { throw new Exception("请选择要删除的班次规则"); } // 检查所有规则是否存在 var existingRules = await _shiftRuleRepository.Select .Where(r => ids.Contains(r.Id)) .ToListAsync(); if (existingRules.Count != ids.Length) { var existingIds = existingRules.Select(r => r.Id).ToArray(); var missingIds = ids.Except(existingIds).ToArray(); throw new Exception($"以下班次规则不存在: {string.Join(", ", missingIds)}"); } await _shiftRuleRepository.SoftDeleteAsync(ids); var ruleNames = string.Join(", ", existingRules.Select(r => r.RuleName)); _logger.LogInformation($"成功批量软删除班次规则: ID {string.Join(", ", ids)}, 名称: {ruleNames}"); } catch (Exception ex) { _logger.LogError(ex, $"批量软删除班次规则失败: ID {string.Join(", ", ids)}, 错误: {ex.Message}"); throw; } } /// /// 切换班次规则启用状态 /// /// 规则ID /// 是否启用 /// [HttpPut] public async Task ToggleStatusAsync(long id, bool isEnabled) { try { var entity = await _shiftRuleRepository.GetAsync(id); if (entity == null) { throw new Exception($"班次规则不存在: ID {id}"); } entity.IsEnabled = isEnabled; await _shiftRuleRepository.UpdateAsync(entity); var statusText = isEnabled ? "启用" : "禁用"; _logger.LogInformation($"成功{statusText}班次规则: ID {id}, 名称: {entity.RuleName}"); } catch (Exception ex) { _logger.LogError(ex, $"切换班次规则状态失败: ID {id}, 错误: {ex.Message}"); throw; } } /// /// 启用班次规则 /// /// 规则ID /// [HttpPut] public async Task EnableAsync(long id) { await ToggleStatusAsync(id, true); } /// /// 禁用班次规则 /// /// 规则ID /// [HttpPut] public async Task DisableAsync(long id) { await ToggleStatusAsync(id, false); } }