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;

/// <summary>
/// 班次规则服务
/// </summary>
[DynamicApi(Area = "app")]
public class ShiftRuleService : BaseService, IShiftRuleService, IDynamicApi
{
    private readonly ShiftRuleRepository _shiftRuleRepository;
    private readonly ShiftRuleMappingRepository _shiftRuleMappingRepository;
    private readonly ILogger<ShiftRuleService> _logger;

    public ShiftRuleService(
        ShiftRuleRepository shiftRuleRepository,
        ShiftRuleMappingRepository shiftRuleMappingRepository,
        ILogger<ShiftRuleService> logger)
    {
        _shiftRuleRepository = shiftRuleRepository;
        _shiftRuleMappingRepository = shiftRuleMappingRepository;
        _logger = logger;
    }

    /// <summary>
    /// 根据ID获取班次规则详细信息
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <returns>班次规则详细信息</returns>
    public async Task<ShiftRuleGetOutput> GetAsync(long id)
    {
        var entity = await _shiftRuleRepository.GetAsync(id);
        if (entity == null)
        {
            return null;
        }

        return entity.Adapt<ShiftRuleGetOutput>();
    }

    /// <summary>
    /// 获取班次规则分页列表
    /// </summary>
    /// <param name="input">查询条件</param>
    /// <returns>分页结果</returns>
    [HttpPost]
    public async Task<PageOutput<ShiftRuleGetPageOutput>> GetPageAsync(PageInput<ShiftRuleGetPageInput> input)
    {
        try
        {
            return await ExecutePageQueryAsync(input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "班次规则分页查询异常: {Message}", ex.Message);
            throw;
        }
    }
    
    /// <summary>
    /// 返回规则列表数据
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<List<ShiftRuleGetPageOutput>> GetListAsync()
    {
        try
        {
            var list = await _shiftRuleRepository.Select.OrderBy(a => a.RuleType).ToListAsync<ShiftRuleGetPageOutput>();
            return list;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "班次规则分页查询异常: {Message}", ex.Message);
            throw;
        }
    }

    /// <summary>
    /// 执行分页查询
    /// </summary>
    private async Task<PageOutput<ShiftRuleGetPageOutput>> ExecutePageQueryAsync(PageInput<ShiftRuleGetPageInput> 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<List<ShiftRuleGetPageOutput>>();
        
        return new PageOutput<ShiftRuleGetPageOutput>()
        {
            List = data,
            Total = total
        };
    }


    /// <summary>
    /// 添加班次规则
    /// </summary>
    /// <param name="input">添加输入参数</param>
    /// <returns>新创建的规则ID</returns>
    [HttpPost]
    public async Task<long> 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<ShiftRuleEntity>();
            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;
        }
    }

    /// <summary>
    /// 更新班次规则
    /// </summary>
    /// <param name="input">更新输入参数</param>
    /// <returns></returns>
    [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;
        }
    }

    /// <summary>
    /// 删除班次规则
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <returns></returns>
    [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;
        }
    }

    /// <summary>
    /// 软删除班次规则
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <returns></returns>
    [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;
        }
    }

    /// <summary>
    /// 批量软删除班次规则
    /// </summary>
    /// <param name="ids">规则ID数组</param>
    /// <returns></returns>
    [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;
        }
    }

    /// <summary>
    /// 切换班次规则启用状态
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <param name="isEnabled">是否启用</param>
    /// <returns></returns>
    [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;
        }
    }

    /// <summary>
    /// 启用班次规则
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <returns></returns>
    [HttpPut]
    public async Task EnableAsync(long id)
    {
        await ToggleStatusAsync(id, true);
    }

    /// <summary>
    /// 禁用班次规则
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <returns></returns>
    [HttpPut]
    public async Task DisableAsync(long id)
    {
        await ToggleStatusAsync(id, false);
    }

} 