using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Config;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository.service.Impl;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace SlnMesnac.Repository
{
    public static class SqlsugarSetup
    {
        /// <summary>
        /// 注册SqlSugar
        /// </summary>
        /// <param name="services"></param>
        public static void AddSqlSugarSetup(this IServiceCollection services)
        {
            services.AddSingleton<ISqlSugarClient>(x =>
            {
                var appConfig = x.GetService<AppConfig>();

                var connectConfigList = new List<ConnectionConfig>();
                if (appConfig.sqlConfig != null)
                {
                    foreach (var item in appConfig.sqlConfig)
                    {
                        #region 加载sqlite数据库地址
                         if(item.configId == "AUCMA_Local")
                        {
                            item.connStr = $"Data Source={System.Environment.CurrentDirectory}//db/hw.db";
                        }
                        #endregion
                        var config = new ConnectionConfig()
                        {
                            ConfigId = item.configId,
                            DbType = (DbType)item.dbType,
                            ConnectionString = item.connStr,
                            InitKeyType = InitKeyType.Attribute,
                            IsAutoCloseConnection = true,
                        };
                        connectConfigList.Add(config);
                    }
                }
                SqlSugarScope Db = new SqlSugarScope(connectConfigList, db =>
                {
                    db.Aop.OnLogExecuting = (sql, pars) => { };
                });

                return Db;
            });
        }

        /// <summary>
        /// 注册Repository、Service服务
        /// </summary>
        /// <param name="services"></param>
        public static void AddServices(this IServiceCollection services)
        {
            //services.AddSingleton<Repository<BaseUser>>();
            services.AddSingleton(typeof(Repository<>));
            services.AddSingleton<IBaseUserService, BaseUserServiceImpl>();
            services.AddSingleton<IBaseMaterialService, BaseMaterialServiceImpl>();
            services.AddSingleton<ILogoIdentifyService, LogoIdentifyImpl>();
            services.AddSingleton<ILogoConfigService, LogoConfigImpl>();
            services.AddSingleton<ILogoFormulaService, LogoFormulaImpl>();
        }
    }
}
