using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

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.AddCors(option => option.AddPolicy("cors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().SetIsOriginAllowed(_ => true)));
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.Add(typeof(GlobalExceptions));
            });
            services.AddSession(options =>
            {
                // 设置 Session 过期时间
                options.IdleTimeout = TimeSpan.FromHours(1);
                options.Cookie.HttpOnly = true;
            });
            services.Configure<FormOptions>(x =>
            {
                x.MultipartBodyLengthLimit = 50 * 1024 * 1024;//不到300M
            });

            string appkey = Configuration["Setting:AppKey"];
            string appid = Configuration["Setting:AppId"];
            string checkurl = Configuration["Setting:CheckUrl"];
            string serviceurl = Configuration["Setting:WebServiceUrl"];
            string schemeurl = Configuration["Setting:DbSchemeUrl"];
            MySystemLib.SystemPublicFuction.appkey = appkey;
            MySystemLib.SystemPublicFuction.appid = appid;
            MySystemLib.SystemPublicFuction.checkurl = checkurl;
            MySystemLib.SystemPublicFuction.appcheck = "success";
            string conn = Configuration["Setting:SqlConnStr"];
            Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
            System.Data.DataTable tablecollection = Library.CustomerSqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = 'KxsProfitServer'", conn);
            foreach (System.Data.DataRow subtable in tablecollection.Rows)
            {
                Dictionary<string, string> Columns = new Dictionary<string, string>();
                System.Data.DataTable columncollection = Library.CustomerSqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = 'KxsProfitServer' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'", conn);
                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);
            }
            MySystemLib.SystemPublicFuction.dbtables = tables;
        }

        // 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.UseExceptionHandler("/Home/Error");
                Library.ConfigurationManager.EnvironmentFlag = 1;
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
                Library.ConfigurationManager.EnvironmentFlag = 2;
            }
            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" }
                })
            });

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{Id?}");
            });
            
            //必须打开的
            StatService.Instance.StartEverDayV2(); //实时统计交易额
            StatService.Instance.StartOther(); //补充统计交易额
            StatService.Instance.StartPosActNum(); //实时统计激活数
            StatService.Instance.StartNewUserNum(); //实时统计新增创客数
            StatService.Instance.StatProfit(); //实时统计创客收益
            StatHelpProfitService.Instance.StartUserTrade();
            StatHelpProfitService.Instance.ResetMaxTradeAmount(); //每月重置助利宝最大交易总额
            OperateService.Instance.Start(); //统计运营中心发货量
            OperateService.Instance.StartPosActNum(); //统计运营中心激活量
            OperateService.Instance.StartPosCouponSaleNum(); //统计运营中心机具券销售量
            
            StatNewService.Instance.StartStat(); //实时统计交易额RDS
            StatNewService.Instance.StartMer(); //实时统计商户交易额到RDS
            StatNewService.Instance.StartAct(); //统计激活数到RDS

            AddRecordService.Instance.StartTradeRecord(); //RDS交易记录队列
            AddRecordService.Instance.StartUserAccountRecord(); //RDS收支明细队列

            StatNewService.Instance.CreateTable(); //创建RDS分表
            
            // ProfitService.Instance.AddRds(); //补RDS数据
            //必须打开的

        }
    }
}