using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 废弃,没用
/// </summary>
public class TimeZoneAdjustmentMiddleware
{
    private readonly RequestDelegate _next;

    public TimeZoneAdjustmentMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (string.IsNullOrEmpty(context.Request.ContentType))
        {
            // 请求没有内容体,可能是一个没有请求体的请求,比如 GET 请求
            await _next(context);
            return;
        }
        

        var timeZoneId = "Asia/Shanghai"; // 客户端默认时区

        var timeZoneIdHeaderValue = context.Request.Headers["TimeZoneId"];

        if (!string.IsNullOrEmpty(timeZoneIdHeaderValue))
        {
            timeZoneId = timeZoneIdHeaderValue;
        }

        var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);



        // 处理 JSON 请求体中的时间字段
        if (context.Request.ContentType.StartsWith("application/json"))
        {
            var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();

            // 使用 JSON.NET 或 System.Text.Json 解析 JSON 请求体
            // 假设请求体中有一个名为 "dateTime" 的时间字段
            dynamic jsonData = JsonConvert.DeserializeObject(requestBody);

            if (jsonData.dateTime != null)
            {
                if (DateTime.TryParse((string)jsonData.dateTime, out DateTime dateTime))
                {
                    // 将 JSON 请求体中的时间字段转换为服务器时区的时间
                    var serverTime = TimeZoneInfo.ConvertTime(dateTime, timeZone);
                    jsonData.dateTime = serverTime;
                }
            }

            // 将修改后的 JSON 请求体重新写入请求流中
            var jsonBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jsonData));
            context.Request.Body = new MemoryStream(jsonBytes);
            context.Request.ContentLength = jsonBytes.Length;
        }


        // 处理 URL 表单参数
        var modifiedQuery = new Dictionary<string, StringValues>();

        foreach (var key in context.Request.Query.Keys)
        {
            if (DateTime.TryParse(context.Request.Query[key], out DateTime dateTime))
            {
                // 将 URL 表单参数中的时间转换为服务器时区的时间
                var serverTime = TimeZoneInfo.ConvertTime(dateTime, timeZone);
                modifiedQuery[key] = new StringValues(serverTime.ToString());
            }
            else
            {
                modifiedQuery[key] = context.Request.Query[key];
            }
        }

        context.Request.Query = new QueryCollection(modifiedQuery);

        // 处理Form请求体中的参数
        if (context.Request.HasFormContentType)
        {
            var modifiedForm = new Dictionary<string, StringValues>();

            foreach (var key in context.Request.Form.Keys)
            {
                if (DateTime.TryParse(context.Request.Form[key], out DateTime dateTime))
                {
                    // 将请求体中的时间转换为服务器时区的时间
                    var serverTime = TimeZoneInfo.ConvertTime(dateTime, timeZone);
                    modifiedForm[key] = new StringValues(serverTime.ToString());
                }
                else
                {
                    modifiedForm[key] = context.Request.Form[key];
                }
            }

            var newFormCollection = new FormCollection(modifiedForm);

            // 将新的表单集合设置回请求对象
            context.Request.Form = newFormCollection;
        }

        await _next(context);
    }

}