using System;
using System.Collections.Generic;
using System.ServiceModel;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Server.Kestrel.Core;

namespace MySystem
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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.AddControllersWithViews();
            services.AddRouting(options =>
            {
                options.LowercaseUrls = true;
            });
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.Configure<Setting>(Configuration.GetSection("Setting"));
            // services.AddCors(option => option.AddPolicy("cors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().SetIsOriginAllowed(_ => true)));
            services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true).Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.Add(typeof(GlobalExceptions));
            });
            //配置模版视图路径
            services.Configure<RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new TemplateViewLocationExpander());
            });
            services.AddSession(options =>
            {
                // 设置 Session 过期时间
                options.IdleTimeout = TimeSpan.FromDays(1);
                options.Cookie.HttpOnly = true;
            });
            services.Configure<FormOptions>(x =>
            {
                x.MultipartBodyLengthLimit = 50 * 1024 * 1024;//不到300M
            });
            //生成密钥
            var symmetricKeyAsBase64 = Configuration["Setting:JwtSecret"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
            //认证参数
            services.AddAuthentication("Bearer").AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,//是否验证签名,不验证的画可以篡改数据，不安全
                    IssuerSigningKey = signingKey,//解密的密钥
                    ValidateIssuer = true,//是否验证发行人，就是验证载荷中的Iss是否对应ValidIssuer参数
                    // ValidIssuer = Configuration["Setting:JwtIss"],//发行人
                    IssuerValidator = (m, n, z) =>
                    {
                        return n.Issuer;
                    },
                    ValidateAudience = true,//是否验证订阅人，就是验证载荷中的Aud是否对应ValidAudience参数
                    // ValidAudience = Configuration["Setting:JwtAud"],//订阅人
                    AudienceValidator = (m, n, z) =>
                    {
                        string check = RedisDbconn.Instance.Get<string>("utoken:" + n.Issuer);
                        return m != null && m.FirstOrDefault().Equals(check);
                    },
                    ValidateLifetime = true,//是否验证过期时间，过期了就拒绝访问
                    ClockSkew = TimeSpan.Zero,//这个是缓冲过期时间，也就是说，即使我们配置了过期时间，这里也要考虑进去，过期时间+缓冲，默认好像是7分钟，你可以直接设置为0
                    RequireExpirationTime = true,
                };
            });
            MySystemLib.SystemPublicFuction.appcheck = "success";

            RedisDbconn.csredis = new CSRedis.CSRedisClient(Configuration["Setting:RedisConnStr"]);
            // TendisDbconn.csredis = new CSRedis.CSRedisClient(Configuration["Setting:TendisConnStr"]);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            string Env = "Develop";
            if (env.IsDevelopment())
            {
                Env = "Develop";
                app.UseDeveloperExceptionPage();
            }
            else 
            {
                Env = "Production";
                app.UseHsts();
            }
            Library.function.WritePage("/", "WebRootPath.txt", env.WebRootPath);
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
                {
                      { ".apk", "application/vnd.android.package-archive" },
                      { ".xlsx", "application/vnd.android.package-archive" }
                })
            });

            app.UseCors("cors");
            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();
            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{Id?}");
            });
            
            initMainServer(Env);
            initBsServer();
            initCashServer();
            initSpServer();
            initOperateServer();

            if(Env == "Develop")
            {
            }
            if(Env == "Production")
            {
                ResetUserTradeService.Instance.Start();
                ResetMerchantTradeService.Instance.Start();
                SycnProfitServiceV3.Instance.Start();
                SycnHelpProfitService.Instance.Start();
                ExcelHelper.Instance.Start();
                OpExcelHelper.Instance.Start();
                SycnUserMachineCountHelper.Instance.Start(); //重置创客机具数量

                TestHelper.Instance.Start(); //生成兑换券
            }
        }








        //初始化数据结构
        private void initMainServer(string Env)
        {
            string dbName = "KxsMainServer";
            if(Env == "Production")
            {
                dbName = "KxsProfitServer";
            }
            Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
            Library.OtherMySqlConn.connstr = Configuration["Setting:SqlConnStr"];
            System.Data.DataTable tablecollection = Library.OtherMySqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = '" + dbName + "'");
            foreach (System.Data.DataRow subtable in tablecollection.Rows)
            {
                Dictionary<string, string> Columns = new Dictionary<string, string>();
                System.Data.DataTable columncollection = Library.OtherMySqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = '" + dbName + "' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'");
                foreach (System.Data.DataRow column in columncollection.Rows)
                {
                    string datatype = column["DATA_TYPE"].ToString();
                    if (datatype == "decimal")
                    {
                        datatype = "numeric";
                    }
                    Columns.Add(column["COLUMN_NAME"].ToString(), datatype);
                }
                tables.Add(subtable["TABLE_NAME"].ToString(), Columns);
            }
            Library.OtherMySqlConn.connstr = "";
            PublicFunction.MainTables = tables;
        }
        private void initBsServer()
        {
            Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
            Library.OtherMySqlConn.connstr = Configuration["Setting:BsSqlConnStr"];
            System.Data.DataTable tablecollection = Library.OtherMySqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = 'KxsBsServer'");
            foreach (System.Data.DataRow subtable in tablecollection.Rows)
            {
                Dictionary<string, string> Columns = new Dictionary<string, string>();
                System.Data.DataTable columncollection = Library.OtherMySqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = 'KxsBsServer' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'");
                foreach (System.Data.DataRow column in columncollection.Rows)
                {
                    string datatype = column["DATA_TYPE"].ToString();
                    if (datatype == "decimal")
                    {
                        datatype = "numeric";
                    }
                    Columns.Add(column["COLUMN_NAME"].ToString(), datatype);
                }
                tables.Add(subtable["TABLE_NAME"].ToString(), Columns);
            }
            Library.OtherMySqlConn.connstr = "";
            PublicFunction.BsTables = tables;
        }
        private void initCashServer()
        {
            Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
            Library.OtherMySqlConn.connstr = Configuration["Setting:CashSqlConnStr"];
            System.Data.DataTable tablecollection = Library.OtherMySqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = 'KxsCashServer'");
            foreach (System.Data.DataRow subtable in tablecollection.Rows)
            {
                Dictionary<string, string> Columns = new Dictionary<string, string>();
                System.Data.DataTable columncollection = Library.OtherMySqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = 'KxsCashServer' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'");
                foreach (System.Data.DataRow column in columncollection.Rows)
                {
                    string datatype = column["DATA_TYPE"].ToString();
                    if (datatype == "decimal")
                    {
                        datatype = "numeric";
                    }
                    Columns.Add(column["COLUMN_NAME"].ToString(), datatype);
                }
                tables.Add(subtable["TABLE_NAME"].ToString(), Columns);
            }
            Library.OtherMySqlConn.connstr = "";
            PublicFunction.CashTables = tables;
        }

        private void initSpServer()
        {
            Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
            Library.OtherMySqlConn.connstr = Configuration["Setting:SpSqlConnStr"];
            System.Data.DataTable tablecollection = Library.OtherMySqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = 'KxsSpServer'");
            foreach (System.Data.DataRow subtable in tablecollection.Rows)
            {
                Dictionary<string, string> Columns = new Dictionary<string, string>();
                System.Data.DataTable columncollection = Library.OtherMySqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = 'KxsSpServer' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'");
                foreach (System.Data.DataRow column in columncollection.Rows)
                {
                    string datatype = column["DATA_TYPE"].ToString();
                    if (datatype == "decimal")
                    {
                        datatype = "numeric";
                    }
                    Columns.Add(column["COLUMN_NAME"].ToString(), datatype);
                }
                tables.Add(subtable["TABLE_NAME"].ToString(), Columns);
            }
            Library.OtherMySqlConn.connstr = "";
            PublicFunction.SpTables = tables;
        }

        //初始化运营中心数据结构
        private void initOperateServer()
        {
            Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
            Library.OtherMySqlConn.connstr = Configuration["Setting:OpSqlConnStr"];
            System.Data.DataTable tablecollection = Library.OtherMySqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = 'KxsOpServer'");
            foreach (System.Data.DataRow subtable in tablecollection.Rows)
            {
                Dictionary<string, string> Columns = new Dictionary<string, string>();
                System.Data.DataTable columncollection = Library.OtherMySqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = 'KxsOpServer' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'");
                foreach (System.Data.DataRow column in columncollection.Rows)
                {
                    string datatype = column["DATA_TYPE"].ToString();
                    if (datatype == "decimal")
                    {
                        datatype = "numeric";
                    }
                    Columns.Add(column["COLUMN_NAME"].ToString(), datatype);
                }
                tables.Add(subtable["TABLE_NAME"].ToString(), Columns);
            }
            Library.OtherMySqlConn.connstr = "";
            PublicFunction.OpTables = tables;
        }
    }
}