using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS.DAL.Db.AuthDb;

namespace WCS.DAL
{
    /// <summary>
    /// 权限数据库
    /// </summary>
    public static class AuthDbHelp
    {


        public static SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = $"Data Source={DbPath.AuthDbPath};",
            DbType = DbType.Sqlite,//[Sqlite]安装[System.Data.SQLite.Core];
            IsAutoCloseConnection = true
        }, db =>
        {
            db.Aop.OnError = ex =>
            {
                //Logs.Write($@"{nameof(AuthDbHelp)}{Environment.NewLine}SQL:{ex?.Sql}{Environment.NewLine}Parametres:{JsonConvert.SerializeObject(ex?.Parametres)}{Environment.NewLine}InnerException:{ex?.InnerException?.ToString()}{Environment.NewLine}Exception:{ex?.ToString()}{Environment.NewLine}", LogsType.DbErr);
            };
        });


        /// <summary>
        /// 初始化数据
        /// </summary>
        public static void InitDb()
        {
            //不存在创建数据库，存在不会创建
            db.DbMaintenance.CreateDatabase();
            //创建表根据实体类
            db.CodeFirst.InitTables(typeof(UserBase), typeof(RoleBase));
            //初始化数据
            if (!db.Queryable<UserBase>().Any())
            {
                var dt = db.GetDate();
                var userBases = new List<UserBase>()
                {
                    new UserBase ()
                    {
                        Id = 1,
                        LoginName = "admin",
                        Password = "admin123",
                        RoleIds = new List<int> () { 1 },
                        IsAdmin = true,
                        Time = dt,
                    },
                    new UserBase ()
                    {
                        Id = 2,
                        LoginName = "czy",
                        Password = "",
                        RoleIds = new List<int> () { 2 },
                        IsAdmin = false,
                        Time = dt,
                    },
                };
                var roleBases = new List<RoleBase>()
                {
                    new RoleBase ()
                    {
                        Id = 1,
                        Name = "管理员",
                        Auths = new List<int> () { },
                        IsAdmin = true,
                        Time = dt,
                    },
                    new RoleBase ()
                    {
                        Id = 2,
                        Name = "操作员",
                        Auths = new List<int> () { },
                        IsAdmin = false,
                        Time = dt,
                    },
                };

                db.Insertable(userBases).ExecuteCommand();
                db.Insertable(roleBases).ExecuteCommand();
            }
        }

    }
}
