using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.ComponentModel;

namespace IRaCIS.Core.Domain.Share;

[Description("多环境 配置环境实体")]
public class ServiceVerifyConfigOption
{
    public bool QCRiskControl { get; set; }
    public bool OpenUserComplexPassword { get; set; }

    public bool OpenSignDocumentBeforeWork { get; set; }

    public bool OpenTrialRelationDelete { get; set; }

    public bool OpenLoginLimit { get; set; }

    public int LoginMaxFailCount { get; set; }

    public int LoginFailLockMinutes { get; set; }

    public int AutoLoginOutMinutes { get; set; }

    public bool OpenLoginMFA { get; set; }

    [Description("连续阅片时间 (min)")]
    public int ContinuousReadingTimeMin { get; set; }

    [Description("休息时间 (min)")]
    public int ReadingRestTimeMin { get; set; }
    [Description("是否需要修改密码")]
    public bool IsNeedChangePassWord { get; set; }

    [Description("修改密码的天数")]
    public int ChangePassWordDays { get; set; }

    public SysTemplateType TemplateType { get; set; }

    public string ThirdPdfUrl { get; set; }

    public int UserMFAVerifyMinutes { get; set; } = 1440;

}

public class SystemEmailSendConfig
{
    public int Port { get; set; }

    public string Host { get; set; } = string.Empty;

    public string Imap { get; set; } = string.Empty;

    public int ImapPort { get; set; } 
    public string FromEmail { get; set; } = string.Empty;

    public string FromName { get; set; } = string.Empty;

    public string AuthorizationCode { get; set; } = string.Empty;

    public string SiteUrl { get; set; } = string.Empty;


    public string PlatformName { get; set; } = string.Empty;
    public string PlatformNameCN { get; set; } = string.Empty;

    public string SystemShortName { get; set; } = string.Empty;

    public string OrganizationName { get; set; } = string.Empty;
    public string OrganizationNameCN { get; set; } = string.Empty;

    public string CompanyName { get; set; } = string.Empty;

    public string CompanyNameCN { get; set; } = string.Empty;

    public string CompanyShortName { get; set; } = string.Empty;

    public string CompanyShortNameCN { get; set; } = string.Empty;

    public bool IsEnv_US { get; set; }

    public string EmailRegexStr { get; set; }

    //public bool IsOpenErrorNoticeEmail { get; set; }


    //public List<string> ErrorNoticeEmailList { get; set; } = new List<string>();
}

public class SystemEmailSendConfigView
{
    public string SystemShortName { get; set; } = string.Empty;
    public string CompanyName { get; set; } = string.Empty;

    public string CompanyNameCN { get; set; } = string.Empty;

    public string CompanyShortName { get; set; } = string.Empty;

    public string CompanyShortNameCN { get; set; } = string.Empty;

    public string EmailRegexStr { get; set; }
}

public class SystemPacsConfig
{
    public int Port { get; set; }

    public string IP { get; set; } = string.Empty;
}
public class IRCEncreptOption
{
    public string Base64RSAPublicKey { get; set; }

    public string Base64RSAPrivateKey { get; set; }
    public bool IsResponseEncreptEnable { get; set; }

    public List<string> ApiPathList { get; set; }
}

/// <summary>
/// 请求缓存配置
/// </summary>
public class RequestDuplicationOptions
{
    /// <summary>
    /// 缓存时间（秒），默认5秒
    /// </summary>
    public int CacheTimeSeconds { get; set; } = 5;

    /// <summary>
    /// 重复请求检测时间窗口（毫秒），默认500毫秒
    /// </summary>
    public int DuplicationWindowMs { get; set; } = 500;

    /// <summary>
    /// 是否启用防重复请求
    /// </summary>
    public bool IsEnabled { get; set; } = true;

    /// <summary>
    /// 需要排除的路径（不进行重复检测）
    /// </summary>
    public List<string> ExcludePaths { get; set; } = new List<string>();
}

public static class IRCSystemInfo
{
    public static List<RequestInfo> RequestRecordList { get; set; } = new List<RequestInfo>();

    private static readonly object requestRecordLock = new object();

    public static bool TryAddRequestRecord(RequestInfo requestInfo, int cacheTimeSeconds, int duplicationWindowMs)
    {
        lock (requestRecordLock)
        {
            var now = DateTime.Now;
            RequestRecordList = RequestRecordList
                .Where(x => x.RequestTime >= now.AddSeconds(-cacheTimeSeconds))
                .ToList();

            var isDuplicate = RequestRecordList.Any(x =>
                x.RequestTime >= requestInfo.RequestTime.AddMilliseconds(-duplicationWindowMs) &&
                x.RequestKey == requestInfo.RequestKey);

            if (isDuplicate)
            {
                return false;
            }

            RequestRecordList.Add(requestInfo);
            return true;
        }
    }
}

public class RequestInfo
{
    public Guid UserRoleId { get; set; }

    public string RequestPath { get; set; } = string.Empty;

    public string ParameterHash { get; set; } = string.Empty;

    public DateTime RequestTime { get; set; }


    /// <summary>
    /// 请求的唯一标识
    /// </summary>
    public string RequestKey => $"{UserRoleId}_{RequestPath}_{ParameterHash}";
}

public class IRaCISBasicConfigOption
{
    public string DoctorCodePrefix { get; set; }
    public string UserCodePrefix { get; set; }
    public string QCChallengeCodePrefix { get; set; }
    public string DicomStudyCodePrefix { get; set; }
    public string TaskStudyCodePrefix { get; set; }
    public string NoneDicomStudyCodePrefix { get; set; }
    public int ImageShareExpireDays { get; set; }
    public string SystemSiteCodePrefix { get; set; }
    public string BlindTaskPrefix { get; set; }
    public string DefaultPassword { get; set; }
}

[Description("项目基础配置规则")]
public static class AppSettings
{

    public static IRaCISBasicConfigOption IRaCISBasicConfig { get; set; }

    static AppSettings()
    {
        var configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource
            {
                Path = "appsettings.json",
                ReloadOnChange = true
            })
            .Build();

        // 手动绑定配置
        var appSettings = new IRaCISBasicConfigOption();
        configuration.GetSection("IRaCISBasicConfig").Bind(appSettings);

        IRaCISBasicConfig = appSettings;
    }
    //获取实体编码字符串
    public static string GetCodeStr(int codeInt, string typeStr)
    {
        switch (typeStr)
        {
            case nameof(Doctor):
                return IRaCISBasicConfig.DoctorCodePrefix + codeInt.ToString("D4");

            case nameof(IdentityUser):
                return IRaCISBasicConfig.UserCodePrefix + codeInt.ToString("D4");

            case nameof(QCChallenge):
                return IRaCISBasicConfig.QCChallengeCodePrefix + codeInt.ToString("D5");

            case nameof(NoneDicomStudy):
                return IRaCISBasicConfig.NoneDicomStudyCodePrefix + codeInt.ToString("D5");

            case nameof(DicomStudy):
                return IRaCISBasicConfig.DicomStudyCodePrefix + codeInt.ToString("D5");

            case nameof(TaskStudy):
                return IRaCISBasicConfig.TaskStudyCodePrefix + codeInt.ToString("D5");

            case nameof(VisitTask):
                return "W" + codeInt.ToString("D5");

            case nameof(Site):
                return IRaCISBasicConfig.SystemSiteCodePrefix + codeInt.ToString("D4");

            default:
                return string.Empty;
        }

    }

}
