using System.Threading.Tasks;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Services;
using NPP.SmartSchedue.Api.Contracts.Services.Personnel;
using NPP.SmartSchedue.Api.Contracts.Services.Personnel.Input;
using NPP.SmartSchedue.Api.Contracts.Services.Personnel.Output;
using NPP.SmartSchedue.Api.Repositories.Personnel;
using NPP.SmartSchedue.Api.Contracts.Domain.Personnel;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;

namespace NPP.SmartSchedue.Api.Services.Personnel;

/// <summary>
/// 资质服务
/// </summary>
[DynamicApi(Area = "app")]
public class QualificationService : BaseService, IQualificationService, IDynamicApi
{
    private readonly QualificationRepository _qualificationRepository;
    
    /// <summary>
    /// 【线程安全修复】信号量对象，用于避免 FreeSql RepositoryDbContext 并发键冲突
    /// </summary>
    private static readonly SemaphoreSlim _dbAccessSemaphore = new(5, 5); // 允许最多5个并发数据库访问

    public QualificationService(QualificationRepository qualificationRepository)
    {
        _qualificationRepository = qualificationRepository;
    }

    /// <summary>
    /// 查询
    /// 【线程安全修复】使用信号量控制并发访问，避免 FreeSql RepositoryDbContext 键冲突
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<QualificationGetOutput> GetAsync(long id)
    {
        await _dbAccessSemaphore.WaitAsync();
        try
        {
            var output = await _qualificationRepository.Select
                .WhereDynamic(id)
                .ToOneAsync<QualificationGetOutput>();

            return output;
        }
        finally
        {
            _dbAccessSemaphore.Release();
        }
    }

    /// <summary>
    /// 查询分页
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<PageOutput<QualificationGetPageOutput>> GetPageAsync(PageInput<QualificationGetPageInput> input)
    {
        var list = await _qualificationRepository.Select
            .WhereIf(!string.IsNullOrEmpty(input.Filter?.Name), a => a.Name.Contains(input.Filter.Name))
            .Count(out var total)
            .OrderByDescending(a => a.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<QualificationGetPageOutput>();

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

        return data;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<long> AddAsync(QualificationAddInput input)
    {
        var entity = Mapper.Map<QualificationEntity>(input);
        var result = await _qualificationRepository.InsertAsync(entity);
        return result.Id;
    }

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

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

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

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