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 MySystem.PublicClass.GraphQL;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.Linq;

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.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.Add(typeof(GlobalExceptions));
            });
            services.AddSession(options =>
            {
                // 设置 Session 过期时间
                options.IdleTimeout = TimeSpan.FromHours(1);
                options.Cookie.HttpOnly = true;
            });
            services.AddSingleton<IRepository, Repository>();
            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,
                };
            });


            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";
            RedisDbconn.csredis = new CSRedis.CSRedisClient(Configuration["Setting:RedisConnStr"]);
        }

        // 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.ConfigurationManager.EnvironmentFlag = 1;
            Library.function.WritePage("/", "WebRootPath.txt", env.WebRootPath);
            // app.UseStatusCodePagesWithReExecute("/public/errpage/pc/{0}.html");

            // RequestDelegate handler = async context =>
            // {
            //     var response = context.Response;
            //     if (response.StatusCode < 500)
            //     {
            //         response.("/public/errpage/pc/{0}.html");
            //     }
            // };
            // app.UseStatusCodePages(builder => builder.Run(handler));
            app.UseStaticFiles();
            // app.UseStaticFiles(new StaticFileOptions
            // {
            //     FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory + "/static"),
            //     RequestPath = "/static"
            // });
            // app.UseStaticFiles(new StaticFileOptions
            // {
            //     FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory + "/" + Configuration["Setting:Database"]),
            //     RequestPath = "/" + Configuration["Setting:Database"]
            // });
            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?}");
            });

            InitMain();

            //必须打开的
            if(Library.ConfigurationManager.EnvironmentFlag == 1)
            {
                // LeaderCompPrizeHelper.Instance.Ready("202311"); //领导人达标奖
                // BalancePayBackService.Instance.Start(); //余额支付队列
                // PosCouponPrizeService.Instance.dosomething(318531);
                // LeaderApplyCouponsHelper.Instance.dosomething(5450);
                OperateAddService.Instance.dosomething(34);
                // BalancePayBackService.Instance.sloveAlipayCallBack("318529");
            }
            if(Library.ConfigurationManager.EnvironmentFlag == 2)
            {
                SycnSpBindService.Instance.Start(); //同步SP绑定数据
                SycnSpBindService.Instance.StartSim(); //同步SP广电卡绑定数据
                SycnSpMerchantService.Instance.Start(); //同步SP商户数据
                SycnSpActiveService.Instance.Start(); //同步SP激活数据
                SycnSpTradeService.Instance.Start(); //同步SP交易数据
                SycnSpChangeBindService.Instance.Start(); //同步SP换绑数据
                SycnSpUnBindService.Instance.Start(); //同步SP解绑数据
                SycnSpMerchantRecordService.Instance.Start(); //同步SP商户记录数据

                StatService.Instance.StartActiveReward(); //实时处理激活奖励
                StatService.Instance.StartActiveReward1(); //实时处理0押激活奖励
                StatService.Instance.StartActiveReward2(); //实时处理盒易付0押激活奖励
                StatService.Instance.StartSimActive(); //实时广电卡激活奖励
                StatService.Instance.StartOpenReward(); //实时获取开机奖励
                LeaderPrizeService.Instance.Start(); //大盟主奖励发奖
                OperatePrizeService.Instance.Start(); //运营中心奖励发奖
                ActRewardService.Instance.Start(); //发放激活奖励
                HelpProfitPreMerchantHelper.Instance.Start(); //助利宝每天增加指定数量商机
                AddActService.Instance.Start(); //划拨后检查机具激活状态，并自动补录
                PrePosRingService.Instance.Start(); //预发未申请提醒
                PrePosWithholdService.Instance.Start(); //预发机过期未申请提交到预扣款
                PrePosWithholdService.Instance.StartPre(); //预发机申请成功，处理预扣款
                SycnMerchantTradeService.Instance.Start(); //同步商户交易额

                MessageCenterService.Instance.Start(); // 消息队列
                LeaderTimeoutSendMessageService.Instance.Start(); //盟主过期消息提醒

                AlipayPayBack2Service.Instance.Start(); //支付宝回调处理
                PosCouponPrizeService.Instance.Start(); //购券奖励队列
                OperateAddService.Instance.Start(); //购买运营中心队列
                BalancePayBackService.Instance.Start(); //余额支付队列
                ReservePayBackService.Instance.Start(); //储备金支付队列
                OrderRefundService.Instance.Start(); //商城订单退款

                StatService.Instance.Start(); //每日重置交易额
                StoreApplyHelper.Instance.Start(); // 每月1号重置仓库额度
                DepositReturnStatService.Instance.Start(); //每月1号统计达标商户（退押需要的）
                DepositReturnStatService.Instance.StartEverTime(); //统计单个商户达标数据（退押需要的）
                AutoOpOrderService.Instance.StartOrderCancel(); //自动取消超时订单（15分钟）
                OperateStockService.Instance.Start(); //运营中心库存实时更新
                ResetSmallStoreHelper.Instance.Start(); //每月重置小分仓额度
                ResetSmallStoreHelper.Instance.Listen(); //监听每月1号重置小分仓额度
                OperateService.Instance.Start(); //运营中心每天统计一次发货量、库存
                TimeOutPosChargeService.Instance.StartDoChargeAmount(); //实时监听待扣款记录，并扣费
                InstallmentDeductionService.Instance.Start(); //分期扣款(每月20号执行)
                LeaderAmountMonthChangeQueue.Instance.Start(); //每月一号记录上月盟主储蓄金和可提现余额
                LeaderCompPrizeHelper.Instance.Start(); //领导人达标奖
                ResetPosFirstFlagAndIsExecuteService.Instance.Start(); //每月1号计算商户首台机具标记

                ChangePosTimer.Instance.Start(); //售后换新执行机具数据转移
                RecommendActStatService.Instance.Start(); //推荐王奖励数据统计
                StoreApplyHelper.Instance.StartEverTime(); //分仓临时额度变更
                PreStoreApplyHelper.Instance.StartEverTime(); //小分仓临时额度变更
                OperateAmountService.Instance.Start(); //运营中心额度变更
                LeaderApplyCouponsHelper.Instance.Start(); //盟主储蓄金申请机具券打标记
                DepositReturnService.Instance.Start(); //退押金到支付宝余额
                StoreApplyHelper.Instance.ResetStoreReserve(); //重置分仓额度
                AddPosCouponPrizeHelper.Instance.Start(); //补机具券奖励

                // TestHelper.Instance.Start();
            }





            //必须打开的

            // UserMonthFeeHelper.Instance.Start(); //每月创客服务费
            // UserMonthFeeHelper.Instance.Start2(); //临时扣创客服务费
            // TimeOutPosSendMessageService.Instance.Start(); //过期机具提醒
            // TimeOutPosChargeService.Instance.Start(); //过期机具计算扣费，并添加到待扣款记录
            // TimeOutPosChargeService.Instance.ListenChargeAmount(); //实时等待过期机具扣款指令，并扣费


            // StatService.Instance.StartPosActNum(); //实时统计激活数
            // StatService.Instance.StartNewUserNum(); //实时统计新增创客数
            // StatService.Instance.StatProfit(); //实时统计创客收益
            // StatServiceTmp.Instance.Start();
            // StatService.Instance.StartEverDay("");
            // StatService.Instance.StartEverDayV2();
            // RedPackageHelper.Instance.Start();
            // ProfitHelperV2.Instance.StatProfit(); //统计分润
            // StatService.Instance.StartEverDay2();
            // TestHelper.Instance.Start();
            // TestService.Instance.Start();
            // StatService.Instance.StartEverDay();


            // 备用，暂时不放开的
            // StatStoreDataService.Instance.Start();
            // RabbitMQClient.Instance.StartReceive("SycnTableData");
            // PayHelper.Instance.Start();
            // OrderHelper.Instance.Start();
            // OrderRefundHelper.Instance.Start();
            // ProductCommentHelper.Instance.Start();
            // TimedTaskHelper.Instance.Start();
            // TaskFlowHelper.Instance.Start();
        }

        private void InitMain()
        {
            string conn = Configuration["Setting:SqlConnStr"];
            string dbName = "KxsMainServer";
            // if(Library.ConfigurationManager.EnvironmentFlag == 2)
            // {
            //     dbName = "KxsProfitServer";
            // }
            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 = '" + dbName + "'", 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 = '" + dbName + "' 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;
        }
    }
}