using Aliyun.Api.LogService.Domain.Log;
using COMMON;
using DB_Server;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Models;
using Models.Data;
using Models.Models.LOGDB;
using Serilog;
using SERVER;
using SERVER.LIB;
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UtilsSharp;

namespace WebUI
{
    /// <summary>
    /// 启动类
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 程序入口
        /// </summary>
        /// <param name="args"></param>
        public static  void Main(string[] args)
        {
            
            var host = CreateHostBuilder(args).Build();
            CreateDbIfNotExists(host);
            host.Run();
            
        }
        /// <summary>
        /// 第一次运行该应用时，会创建数据库并使用测试数据加载该数据库。 每当数据模型发生更改时：
        /// 删除数据库。
        /// 更新 Seed 方法，并使用新数据库重新开始。
        /// </summary>
        /// <param name="host"></param>
        private static void CreateDbIfNotExists(IHost host)
        {
            // 建立阿里云的   同步数据
            Task.Run(() => {
                ASLS sLS = new ASLS();
                sLS.Init_();
                sLS.Init();

                //var logs = new LogInfo();
                //logs.Contents.Add("info", "11");
                //var logs_ = new LogInfo();
                //logs_.Contents.Add("renark", "22");
                //Debug.Write( sLS.write("rucs-eventlogging-db", logs, logs_).Result);
            });

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService<HotelServiceContext>();
                    context.Database.EnsureCreated();
                    var log = services.GetRequiredService<LOG_DBContext>();
                    log.Database.EnsureCreated();
                    DbInitializer.Initialize(context);

                    #region 修改mysql 的datetime  的毫秒  类型
                    if (ConfigEntity.Instance.DBTYPE == 2)
                    {
                        var db = new DbHelperSQL(DbHelperSQL.DBSel.BLV_RCU_DB);
                        var data = DataTableHelper.ToEntities<MysqlModel>(db.ExecuteTable(
                             $@"SELECT
                       table_name tablename,
                       column_name columnName,
                       data_type dataType 
                       FROM
                       information_schema.COLUMNS 
                       WHERE
                       table_schema = ( SELECT DATABASE ( ) ) 
                       and DATA_TYPE = 'datetime' 
                       ORDER BY
                       ordinal_position "
                             ));
                        foreach (var item in data)
                        {
                            db.ExecuteSql($"ALTER TABLE {item.tablename} MODIFY {item.columnName} datetime(3)");
                        }

                        var dblog = new DbHelperSQL(DbHelperSQL.DBSel.LogDB);
                        data = DataTableHelper.ToEntities<MysqlModel>(dblog.ExecuteTable(
                          $@"SELECT
                       table_name tablename,
                       column_name columnName,
                       data_type dataType 
                       FROM
                       information_schema.COLUMNS 
                       WHERE
                       table_schema = ( SELECT DATABASE ( ) ) 
                       and DATA_TYPE = 'datetime' 
                       ORDER BY
                       ordinal_position "
                          ));
                        foreach (var item in data)
                        {
                            dblog.ExecuteSql($"ALTER TABLE {item.tablename} MODIFY {item.columnName} datetime(3)");
                        }
                    }
                    #endregion
                    
                    SYNC_DATA.SYNC_DATA_ALL();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }
        /// <summary>
        /// 构建web项目
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
