using System;
using System.Collections.Generic;
using System.Linq;
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;

namespace NPP.SmartSchedue.Api.Services.Time;

/// <summary>
/// 生产班次服务
/// </summary>
[DynamicApi(Area = "app")]
public class ShiftService : BaseService, IShiftService, IDynamicApi
{
    private readonly ShiftRepository _shiftRepository;
    private readonly ShiftRuleRepository _shiftRuleRepository;
    private readonly ShiftRuleMappingRepository _shiftRuleMappingRepository;

    public ShiftService(ShiftRepository shiftRepository,  ShiftRuleRepository shiftRuleRepository, ShiftRuleMappingRepository shiftRuleMappingRepository)
    {
        _shiftRepository = shiftRepository;
        _shiftRuleRepository = shiftRuleRepository;
        _shiftRuleMappingRepository = shiftRuleMappingRepository;
    }

    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<ShiftGetOutput> GetAsync(long id)
    {
        var output = await _shiftRepository.Select
            .WhereDynamic(id)
            .ToOneAsync<ShiftGetOutput>();

        return output;
    }

    /// <summary>
    /// 查询分页
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<PageOutput<ShiftGetPageOutput>> GetPageAsync(PageInput<ShiftGetPageInput> input)
    {
        var list = await _shiftRepository.Select
            .WhereIf(!string.IsNullOrEmpty(input.Filter?.Name), a => a.Name.Contains(input.Filter.Name))
            .WhereIf(input.Filter?.IsEnabled.HasValue == true, a => a.IsEnabled == input.Filter.IsEnabled.Value)
            .Count(out var total)
            .OrderBy(a => a.ShiftNumber)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<ShiftGetPageOutput>();

        var data = new PageOutput<ShiftGetPageOutput>()
        {
            List = list,
            Total = total
        };

        return data;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<long> AddAsync(ShiftAddInput input)
    {
        var entity = Mapper.Map<ShiftEntity>(input);
        var result = await _shiftRepository.InsertAsync(entity);
        
        // 查询所有启用的Shift Rule
        var shiftRules = await _shiftRuleRepository.Select
            .Where(r => r.IsEnabled)
            .ToListAsync();
        
        // 自动添加当前班次的Shift Rule Mapping
        if (shiftRules.Any())
        {
            var mappings = shiftRules.Select(rule => new ShiftRuleMappingEntity
            {
                ShiftId = result.Id,
                RuleId = rule.Id,
                IsEnabled = true,
                ExecutionPriority = rule.DefaultPriority,
                OverrideParameters = rule.RuleParameters,
                MappingDescription = $"自动创建：{rule.RuleName}"
            }).ToList();
            
            await _shiftRuleMappingRepository.InsertAsync(mappings);
        }
        
        return result.Id;
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task UpdateAsync(ShiftUpdateInput input)
    {
        var entity = await _shiftRepository.GetAsync(input.Id);
        Mapper.Map(input, entity);
        await _shiftRepository.UpdateAsync(entity);
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task DeleteAsync(long id)
    {
        await _shiftRepository.DeleteAsync(id);
    }

    /// <summary>
    /// 软删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task SoftDeleteAsync(long id)
    {
        await _shiftRepository.SoftDeleteAsync(id);
    }

    /// <summary>
    /// 批量软删除
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task BatchSoftDeleteAsync(long[] ids)
    {
        await _shiftRepository.SoftDeleteAsync(ids);
    }

    /// <summary>
    /// 启用班次
    /// </summary>
    /// <param name="id">班次ID</param>
    /// <returns></returns>
    public async Task EnableAsync(long id)
    {
        var entity = await _shiftRepository.GetAsync(id);
        if (entity != null)
        {
            entity.IsEnabled = true;
            await _shiftRepository.UpdateAsync(entity);
        }
    }

    /// <summary>
    /// 禁用班次
    /// </summary>
    /// <param name="id">班次ID</param>
    /// <returns></returns>
    public async Task DisableAsync(long id)
    {
        var entity = await _shiftRepository.GetAsync(id);
        if (entity != null)
        {
            entity.IsEnabled = false;
            await _shiftRepository.UpdateAsync(entity);
        }
    }

    /// <summary>
    /// 切换班次状态
    /// </summary>
    /// <param name="id">班次ID</param>
    /// <param name="isEnabled">是否启用</param>
    /// <returns></returns>
    public async Task ToggleStatusAsync(long id, bool isEnabled)
    {
        var entity = await _shiftRepository.GetAsync(id);
        if (entity != null)
        {
            entity.IsEnabled = isEnabled;
            await _shiftRepository.UpdateAsync(entity);
        }
    }

    /// <summary>
    /// 获取班次相关的规则列表
    /// 深度业务思考：通过班次规则映射表获取该班次适用的所有规则
    /// 必须同时满足：映射表IsEnabled=true 且 规则本身IsEnabled=true
    /// </summary>
    /// <param name="shiftId">班次ID</param>
    /// <returns>班次规则列表</returns>
    public async Task<List<ShiftRuleEntity>> GetShiftRulesAsync(long shiftId)
    {
        try
        {
            // 先获取该班次关联且启用的规则映射
            var enabledMappings = await _shiftRuleMappingRepository.Select
                .Where(srm => srm.ShiftId == shiftId && srm.IsEnabled)
                .OrderBy(srm => srm.ExecutionPriority)
                .ToListAsync();

            if (!enabledMappings.Any())
            {
                return new List<ShiftRuleEntity>();
            }

            // 获取映射中的规则ID列表
            var ruleIds = enabledMappings.Select(m => m.RuleId).ToList();

            // 查询对应的规则详情，同时检查规则本身也必须启用
            var shiftRules = await _shiftRuleRepository.Select
                .Where(sr => ruleIds.Contains(sr.Id) && sr.IsEnabled) // 规则本身也必须启用
                .ToListAsync();

            // 按映射表的优先级重新排序返回结果
            var orderedRules = new List<ShiftRuleEntity>();
            foreach (var mapping in enabledMappings)
            {
                var rule = shiftRules.FirstOrDefault(sr => sr.Id == mapping.RuleId);
                if (rule != null)
                {
                    orderedRules.Add(rule);
                }
            }

            return orderedRules;
        }
        catch (Exception ex)
        {
            // 记录异常但不抛出，返回空列表以保证系统稳定性
            return new List<ShiftRuleEntity>();
        }
    }
} 