using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Net;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;
using System.Threading;
using System.Threading.Tasks;

namespace MisDataSaveDate
{
    public class InitServer
    {
        HttpSelfHostConfiguration config = null;
        HttpSelfHostServer server = null;
        public InitServer(string Url_WebApi)
        {
            // var Url_WebApi = System.Configuration.ConfigurationManager.AppSettings["Url_WebApi"];
            Init(Url_WebApi);
        }
        public void Init(string url)
        {
            config = new HttpSelfHostConfiguration(url);

            // 提高允许的请求体大小（默认较小，导致大图Base64 413）
            config.MaxReceivedMessageSize = 104857600; // 100 MB

            // 启用跨域
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            // 兜底处理 CORS（含预检请求）
            config.MessageHandlers.Add(new CorsPreflightHandler());
            // 启用特性路由
            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            // 自定义路由匹配到action
            config.Routes.MapHttpRoute(
                name: "API Default",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );



            server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();


        }
        /// <summary>
        /// 处理OPTIONS预检并为所有响应添加CORS头（自托管场景）
        /// </summary>
        public class CorsPreflightHandler : DelegatingHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                if (request.Method == HttpMethod.Options)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    AddCorsHeaders(resp);
                    return Task.FromResult(resp);
                }
                return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                {
                    var resp = t.Result;
                    AddCorsHeaders(resp);
                    return resp;
                }, cancellationToken);
            }
            private static void AddCorsHeaders(HttpResponseMessage resp)
            {
                if (!resp.Headers.Contains("Access-Control-Allow-Origin"))
                {
                    resp.Headers.Add("Access-Control-Allow-Origin", "*");
                }
                if (!resp.Headers.Contains("Access-Control-Allow-Methods"))
                {
                    resp.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                }
                if (!resp.Headers.Contains("Access-Control-Allow-Headers"))
                {
                    resp.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
                }
                if (!resp.Headers.Contains("Access-Control-Allow-Credentials"))
                {
                    resp.Headers.Add("Access-Control-Allow-Credentials", "true");
                }
            }
        }
        public class JsonContentNegotiator : IContentNegotiator
        {
            private readonly JsonMediaTypeFormatter _jsonFormatter;

            public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
            {
                _jsonFormatter = formatter;
            }
            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
            {
                var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
                return result;
            }
        }
    }
}
