
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace IRaCIS.Core.API
{
    public static class NewtonsoftJsonSetup
    {
        public static void AddNewtonsoftJsonSetup(this IMvcBuilder builder)
        {

            builder.AddNewtonsoftJson(options =>
             {
                 //options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
                 // 忽略循环引用
                 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                 //options.SerializerSettings.TypeNameHandling = TypeNameHandling.All;

                 //处理返回给前端  可空类型 给出默认值 比如in? 为null 设置 默认值0
                 options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver(); //new DefaultContractResolver();// new NullToEmptyStringResolver();
                                                                                                // 设置时间格式
                 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";

                 //options.SerializerSettings.Converters.Add(new JSONCustomDateConverter()) ;

                 //IsoDateTimeConverter
                 //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

             })
                .AddControllersAsServices()//动态webApi属性注入需要
               .ConfigureApiBehaviorOptions(o =>
                {
                    o.SuppressModelStateInvalidFilter = true; //自己写验证

                    ////这里是自定义验证结果和返回状态码  因为这里是在[ApiController]控制器层校验，动态webApi的不会校验 所以需要单独写一个Filter
                    //o.InvalidModelStateResponseFactory = (context) =>
                    //{
                    //    var error = context.ModelState .Keys
                    //                          .SelectMany(k => context.ModelState[k].Errors)
                    //                          .Select(e => e.ErrorMessage)
                    //                          .ToArray();

                    //return new JsonResult(ResponseOutput.NotOk("The inputs supplied to the API are invalid. " + JsonConvert.SerializeObject( error)));
                    //};

                });


            Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                //日期类型默认格式化处理
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

                return setting;
            });


        }
    }
}
