using CrazyStudio.Core.Common.Eitities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XPrintServer.DataModel;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Business.Extensions
{
    public static class DbConfigExtension
    {
        private static ConnectionConfig? _connectionConfig = null;
        //public static void SetSnowIdInfo(this IServiceCollection services, ConfigurationManager configuration)
        //{
        //    var snowIdInfos = configuration.GetSection("SnowId").Get<SnowIdInfos>()!;
        //    //程序启时动执行一次就行
        //    SnowFlakeSingle.WorkId = snowIdInfos.WorkerId; //从配置文件读取一定要每台服务器或者每个容器不一样
        //    SnowFlakeSingle.DatacenterId = snowIdInfos.DatacenterId; //从配置文件读取
        //}

        public static ConnectionConfig GetSqlSugarConfig(this IServiceCollection services, ConfigurationManager configuration)
        {
            if (_connectionConfig == null)
            {
                _connectionConfig = new ConnectionConfig()
                {
                    ConnectionString = configuration.GetConnectionString("DBConnStr"),
                    DbType = Enum.Parse<DbType>(configuration.GetConnectionString("DbType")!),
                    InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                    IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        EntityNameService = (type, entity) =>
                        {
                            entity.IsDisabledDelete = true;//禁止删除列
                        }
                    }
                };
                services.AddSingleton(_connectionConfig);
            }
            return _connectionConfig;
        }



        //public static void DBSyncModels(this IServiceCollection services, ConfigurationManager configuration)
        //{
        //    var repo = new SqlSugarRepository<User>(GetSqlSugarConfig(services, configuration));
        //    string dict = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../CGamesServer.DataModel", "Models");
        //    repo.Context.DbFirst.IsCreateAttribute().IsCreateDefaultValue().StringNullable().FormatClassName(it => repo.ConvertTF(it)).CreateClassFile(dict, "XPrintServer.DataModel.Models");
        //}

        public static void DBSyncTables(this IServiceCollection services, ConfigurationManager configuration)
        {
            var isSyncDb = configuration.GetSection("IsSyncDb").Get<bool>()!;
            if (isSyncDb)
            {
                var repo = new SqlSugarRepository<User>(GetSqlSugarConfig(services, configuration));
                var sqlClient = repo.AsSugarClient();
                //建库：如果不存在创建数据库存在不会重复创建 createdb
                //sqlClient.DbMaintenance.CreateDatabase(); // 注意 ：Oracle和个别国产库需不支持该方法，需要手动建库 

                //不写这行代码 你也可以用插入建表，插入用法看文档下面
                var splitTables = sqlClient.CodeFirst
                    .SplitTables();//标识分表

                splitTables.InitTables([typeof(ActionLog), typeof(BackstageUser), typeof(Menu), typeof(Model), typeof(ModelPart), typeof(Role), 
                    typeof(User), typeof(UserMenuInRole), typeof(Order), typeof(OrderInfo)]); //程序启动时加这一行,如果一张表没有会初始化一张
            }
        }
    }
}
