using SqlSugar;
using System;
using System.IO;

namespace ORM
{
    public class DatabaseConfig
    {
        /// <summary>
        /// 数据库连接类型
        /// </summary>
        public static DbType DbConnectionType => DbType.Sqlite;

        /// <summary>
        /// SQLite 数据库文件路径
        /// </summary>
        public static string DbConnectionString { get; private set; }

        /// <summary>
        /// 数据租户Id
        /// </summary>
        public static int TenantId { get; private set; }

        /// <summary>
        /// 雪花算法DatacenterId，值范围：0至31
        /// </summary>
        public static int SnowFlakeDatacenterId { get; private set; }

        /// <summary>
        /// 雪花算法WorkID，值范围：0至31
        /// </summary>
        public static int SnowFlakeWorkId { get; private set; }

        static DatabaseConfig()
        {
            // 获取程序运行目录
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            // 确保 SQLDB 文件夹存在
            string folder = Path.Combine(baseDir, "SQLDB");
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);

            // 拼接数据库文件路径
            string dbPath = Path.Combine(folder, "SQL.db");

            // 设置连接字符串
            DbConnectionString = $"Data Source={dbPath};Version=3;";
        }

        /// <summary>
        /// 设置数据库连接字符串（可手动覆盖）
        /// </summary>
        public static void SetDbConnection(string strConnection)
        {
            if (string.IsNullOrEmpty(strConnection))
            {
                throw new Exception("数据库连接字符串为空");
            }
            DbConnectionString = strConnection;
        }

        /// <summary>
        /// 设置数据租户Id
        /// </summary>
        public static void SetTenant(int nTenantId)
        {
            if (nTenantId <= 10000)
            {
                throw new Exception("数据租户Id值需大于10000");
            }
            TenantId = nTenantId;
            SetSnowFlake((nTenantId - 10000) % 1024);
        }

        /// <summary>
        /// 将指定数字转换为雪花算法DatacenterId和WorkID
        /// </summary>
        private static void SetSnowFlake(int nSnowFlakeId)
        {
            if (nSnowFlakeId > 1023 || nSnowFlakeId < 0)
            {
                throw new Exception("雪花算法机器码值范围0至1023");
            }
            SnowFlakeDatacenterId = nSnowFlakeId >> 5;
            SnowFlakeWorkId = nSnowFlakeId & 31;
        }
        public static void CreateDatabaseAndCheckConnection(bool createDatabase = false, bool checkConnection = false)
        {
            //数据库不存在则创建数据库
            if (createDatabase)
            {
                SqlSugarContext.DbContext.DbMaintenance.CreateDatabase();
            }
            // 检查数据库连接
            if (checkConnection && !SqlSugarContext.DbContext.Ado.IsValidConnection())
            {
                throw new Exception("连接数据库失败");
            }
        }
    }
}
