using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
using Yi.Framework.AiHub.Application.Contracts.IServices;
using Yi.Framework.AiHub.Domain.Entities.Model;
using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.AiHub.Domain.Shared.Extensions;
using Yi.Framework.SqlSugarCore.Abstractions;

namespace Yi.Framework.AiHub.Application.Services.Chat;

/// <summary>
/// 模型服务
/// </summary>
public class ModelService : ApplicationService, IModelService
{
    private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
    private readonly ModelManager _modelManager;

    public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository, ModelManager modelManager)
    {
        _modelRepository = modelRepository;
        _modelManager = modelManager;
    }

    /// <summary>
    /// 获取模型库列表（公开接口，无需登录）
    /// </summary>
    public async Task<PagedResultDto<ModelLibraryDto>> GetListAsync(ModelLibraryGetListInput input)
    {
        RefAsync<int> total = 0;

        // 查询所有未删除且已启用的模型，使用WhereIF动态添加筛选条件
        var modelIds = (await _modelRepository._DbQueryable
            .Where(x => x.IsEnabled)
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
                x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
            .WhereIF(input.ProviderNames is not null, x =>
                input.ProviderNames.Contains(x.ProviderName))
            .WhereIF(input.ModelTypes is not null, x =>
                input.ModelTypes.Contains(x.ModelType))
            .WhereIF(input.ModelApiTypes is not null, x =>
                input.ModelApiTypes.Contains(x.ModelApiType))
            .WhereIF(input.IsPremiumOnly == true, x => x.IsPremium)
            .GroupBy(x => x.ModelId)
            .Select(x => x.ModelId)
            .ToPageListAsync(input.SkipCount, input.MaxResultCount, total));

        var entities = await _modelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
            .Where(x => x.IsEnabled)
            .OrderBy(x => x.OrderNum)
            .OrderBy(x => x.Name).ToListAsync();

        var output=  entities.GroupBy(x => x.ModelId).Select(x => new ModelLibraryDto
        {
            ModelId = x.First().ModelId,
            Name = x.First().Name,
            Description = x.First().Description,
            ModelType = x.First().ModelType,
            ModelApiTypes = x.Select(y => new ModelApiTypeOutput { ModelApiType = y.ModelApiType }).ToList(),
            MultiplierShow = x.First().MultiplierShow,
            ProviderName = x.First().ProviderName,
            IconUrl = x.First().IconUrl,
            IsPremium = x.First().IsPremium,
            OrderNum = x.First().OrderNum
        }).ToList();
        
        return new PagedResultDto<ModelLibraryDto>(total, output);
    }

    /// <summary>
    /// 获取供应商列表（公开接口，无需登录）
    /// </summary>
    public async Task<List<string>> GetProviderListAsync()
    {
        var providers = await _modelRepository._DbQueryable
            .Where(x => x.IsEnabled)
            .Where(x => !string.IsNullOrEmpty(x.ProviderName))
            .GroupBy(x => x.ProviderName)
            .Select(x => x.ProviderName)
            .ToListAsync();

        return providers!;
    }

    /// <summary>
    /// 获取模型类型选项列表（公开接口，无需登录）
    /// </summary>
    public Task<List<ModelTypeOption>> GetModelTypeOptionsAsync()
    {
        var options = Enum.GetValues<ModelTypeEnum>()
            .Select(e => new ModelTypeOption
            {
                Label = e.GetDescription(),
                Value = (int)e
            })
            .ToList();

        return Task.FromResult(options);
    }

    /// <summary>
    /// 获取API类型选项列表（公开接口，无需登录）
    /// </summary>
    public Task<List<ModelApiTypeOption>> GetApiTypeOptionsAsync()
    {
        var options = Enum.GetValues<ModelApiTypeEnum>()
            .Select(e => new ModelApiTypeOption
            {
                Label = e.GetDescription(),
                Value = (int)e
            })
            .ToList();

        return Task.FromResult(options);
    }

    /// <summary>
    /// 清除尊享模型ID缓存
    /// </summary>
    [HttpPost("model/clear-premium-cache")]
    public async Task ClearPremiumModelCacheAsync()
    {
        await _modelManager.ClearPremiumModelIdsCacheAsync();
    }
}