using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using System.Data.SqlClient;
using Tiobon.Core.Common.DB.Dapper.Enums;

namespace Tiobon.Core.Common.DB.Dapper;

public static class AppSetting
{
    public static IConfiguration Configuration { get; private set; }

    public static string DbConnectionString { get; private set; }
    public static string DBType { get; private set; }


    private static ConnectionStrings _connection;


    public static void Init()
    {
        Configuration = new ConfigurationBuilder()
          .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
          .Build(); ;

        //var baseDirectory = AppContext.BaseDirectory;
        //var provider = services.BuildServiceProvider(); 


        ////设置修改或删除时需要设置为默认用户信息的字段
        //CreateMember = provider.GetRequiredService<IOptions<CreateMember>>().Value ?? new CreateMember();
        //ModifyMember = provider.GetRequiredService<IOptions<ModifyMember>>().Value ?? new ModifyMember();

        #region 初始化数据库
        MainDb.CurrentDbConnId = app("MainDB");

        var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);

        Const.DBType.Name = DataBaseType.SqlServer.ToString();
        DBType = DataBaseType.SqlServer.ToString();

        try
        {
            DbConnectionString = mainConnetctDb.Connection;
        }
        catch { }
        if (string.IsNullOrEmpty(DbConnectionString))
            throw new Exception("未配置好数据库默认连接");

        #region 检查服务是否可用 

        //bool mysql = Const.DBType.Name == DbCurrentType.MySql.ToString();
        //if (mysql)
        //{

        //}
        bool mssql = Const.DBType.Name == DbCurrentType.MsSql.ToString();

        if (mssql)
        {
            using var conn = new SqlConnection(_connection.DbConnectionString);
            while (true)
            {

                //if (Utility.IsPortOpen(conn.DataSource, 1433))
                //{
                //    Logger.WriteLog("[数据库] 服务状态正常");
                //    break;
                //}
                //else
                //{
                //    Logger.WriteLog("[数据库] 服务状态异常, 稍后重试");
                //    System.Threading.Thread.Sleep(5000);
                //}

                //conn.Open();
                //if (conn.State == ConnectionState.Open)
                //{
                //    conn.Close();
                //    Logger.WriteLog("[数据库] 服务状态正常");
                //    break;
                //}
                //else
                //{
                //    Logger.WriteLog("[数据库] 服务状态异常, 等待 5 秒后重试");
                //    System.Threading.Thread.Sleep(5000);
                //}
            }
        }
        #endregion

        #endregion


    }
    // 多个节点name格式 ：["key:key1"]
    public static string GetSettingString(string key)
    {
        return Configuration[key];
    }
    // 多个节点,通过.GetSection("key")["key1"]获取
    public static IConfigurationSection GetSection(string key)
    {
        return Configuration.GetSection(key);
    }

    /// <summary>
    /// 封装要操作的字符
    /// </summary>
    /// <param name="sections">节点配置</param>
    /// <returns></returns>
    public static string app(params string[] sections)
    {
        try
        {

            if (sections.Any())
            {
                return Configuration[string.Join(":", sections)];
            }
        }
        catch (Exception) { }

        return "";
    }

    /// <summary>
    /// 递归获取配置信息数组
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sections"></param>
    /// <returns></returns>
    public static List<T> app<T>(params string[] sections)
    {
        List<T> list = new List<T>();
        // 引用 Microsoft.Extensions.Configuration.Binder 包
        Configuration.Bind(string.Join(":", sections), list);
        return list;
    }
}


#region 数据库链接
/// <summary>
/// 数据库链接
/// </summary>
public class ConnectionStrings
{
    /// <summary>
    /// 数据库类型
    /// </summary>
    public string DBType { get; set; }

    /// <summary>
    /// 数据库链接字符串
    /// </summary>
    public string DbConnectionString { get; set; }
}
#endregion

