using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace FactorySystemCommon
{
    /// <summary>
    /// 获取AppSettings帮助类
    /// </summary>
    public class AppSettingsHelper
    {
        private static Dictionary<string, string> AppSettingList = new Dictionary<string, string>();

        /// <summary>
        /// 获取配置文件值
        /// </summary>
        public static string GetAppSettingVal(string setName)
        {
            if (!AppSettingList.TryGetValue(setName, out string appVal))
            {
                appVal = ConfigurationManager.AppSettings.Get(setName);
                try
                {
                    if (AppSettingList.ContainsKey(setName)) AppSettingList[setName] = appVal;
                    else AppSettingList.Add(setName, appVal);
                }
                catch (System.Exception) { }
            }
            return appVal;
        }

        /// <summary>
        /// 获取数据库实例
        /// </summary>
        public static SqlSugarClient GetSqlSugar(string setName = "ConnectionString")
        {
            SqlSugarClient tempDb = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = GetAppSettingVal(setName),
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true
            });
            //日志输出
            tempDb.Aop.OnLogExecuting = (sql, p) =>
            {
                string parMsg = string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value));
                string dugMsg = string.Format("请求Sql语句：{1}{0}请求参数：{2}", Environment.NewLine, sql, parMsg);
                ExceptionHelper.WriteMessage(dugMsg, 2);
            };
            return tempDb;
        }
    }
}
