using Autofac;
using GZY.Quartz.MUI.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MS.Component.Aop;
using MS.Component.Jwt;
using MS.DbContexts;
using MS.Models.Automapper;
using MS.Services;
using MS.UnitOfWork;
using MS.WebApi.Filters;
using MS.WebApi.stockdbModels;
using MS.WebApi.waynedbModels;
using MS.WebCore;
using MS.WebCore.MultiLanguages;
using Npgsql.EntityFrameworkCore.PostgreSQL;

namespace MS.WebApi
{
    public class Startup
    {
        //public Startup(IConfiguration configuration)
        //{
        //    Configuration = configuration;
        //}
        public ILifetimeScope AutofacContainer { get; private set; }

        public Startup(IWebHostEnvironment env)
        {
            // In ASP.NET Core 3.0 `env` will be an IWebHostingEnvironment, not IHostingEnvironment.
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }
        //添加autofac的DI配置容器
        public void ConfigureContainer(ContainerBuilder builder)
        {
            //注册IBaseService和IRoleService接口及对应的实现类
            //builder.RegisterType<BaseService>().As<IBaseService>().InstancePerLifetimeScope();
            //builder.RegisterType<RoleService>().As<IRoleService>().InstancePerLifetimeScope();

            //注册aop拦截器 
            //将业务层程序集名称传了进去，给业务层接口和实现做了注册，也给业务层各方法开启了代理
            builder.AddAopService(ServiceExtensions.GetAssemblyName());
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //添加多语言本地化支持
            services.AddMultiLanguages();

            services.AddCors(options =>
            {
                //options.AddPolicy("AllowSpecificOrigin",
                //    builder => builder.WithOrigins("http://tkhs.net.cn:8091")//http://ipos.biz:8091
                //                      .AllowAnyHeader()
                //                      .AllowAnyMethod()
                //                      .AllowCredentials()

                //                      );
                //    //options.AddPolicy("AllowAllOrigins", 
                //    //    builder => builder.SetIsOriginAllowed(_ => true)
                //    //.AllowAnyHeader()
                //    //.AllowAnyMethod()
                //    //.AllowCredentials()
                //    //);
            });

            services.AddQuartzUI();
            services
                .AddControllers(options =>
                {
                    //  options.Filters.Add<ApiResultFilter>();
                    options.Filters.Add<ApiExceptionFilter>();
                })
                .AddDataAnnotationsLocalization(options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                    factory.Create(typeof(SharedResource));//给注解添加本地化资源提供器Localizerprovider
                });

            //注册跨域策略
            //services.AddCorsPolicy(Configuration);
            //注册webcore服务（网站主要配置）
            services.AddWebCoreService(Configuration);

            //注册工作单元（同时注册了DBContext）
            services.AddUnitOfWorkService<MSDbContext>(options => { options.UseNpgsql(Configuration.GetSection("ConectionStrings:MSDbContext").Value); });
            services.AddUnitOfWorkService<AccountingContext>(options => { options.UseNpgsql(Configuration.GetSection("ConectionStrings:AccountingService").Value); });
            services.AddUnitOfWorkService<SQLiteContext>(options => { options.UseSqlite("Data Source=D:\\smartfueltool\\smartfueltool.db"); });
            services.AddUnitOfWorkService<AuthContext>(options => { options.UseNpgsql(Configuration.GetSection("ConectionStrings:AuthServiceDatabase").Value); });
            services.AddDbContext<stockdbContext>(options =>
     options.UseMySql(Configuration.GetSection("ConectionStrings:StockdbDatabase").Value));
            services.AddDbContext<waynedbContext>(options =>
  options.UseMySql(Configuration.GetSection("ConectionStrings:WaynedbDatabase").Value));
            //注册automapper服务
            services.AddAutomapperService();

            //注册jwt服务
            services.AddJwtService(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseQuartz(); //定时任务
            app.UseMultiLanguage(Configuration);//添加多语言本地化支持

            app.UseRouting();

            app.UseCors(WebCoreExtensions.MyAllowSpecificOrigins);//添加跨域

            app.UseAuthentication();//添加认证中间件

            app.UseAuthorization();
            app.UseCors("AllowSpecificOrigin");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
