using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.DBA.DBModle;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using LJLib.SQLEX;
using LJLib.TextLog;
using LJLib.Tools.Encry;
using Newtonsoft.Json.Linq;

namespace JLHHJSvr.Excutor
{
    internal sealed class AdminTestFunctionExcutor : ExcutorBase<AdminTestFunctionRequest, AdminTestFunctionResponse>
    {
        string path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"), "filterlog.log");
        string path2 = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"), "filterlog_result2.log");
        protected override void ExcuteInternal(AdminTestFunctionRequest request, object state2, AdminTestFunctionResponse rslt)
        {
            //FilterLogs("8:00", "16:00");


            psw_bczh3 pswhelper = new psw_bczh3();
            var psw = pswhelper.GetEntrypt(request.requestStr, 1, "123457851239866");
            rslt.resultStr = psw;

            //new RequestLogger();

            //string path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"), "filterlog.log");
            //string path2 = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"), "filterlog_result.log");
            //#region
            //try
            //{
            //    var filteredLogs = new List<string>();
            //    int matchCount = 0;
            //    var currentBlock = new StringBuilder(1024);
            //    bool isTargetRequest = false;
            //    bool hasTargetMattressId = false;

            //    foreach (string line in File.ReadLines(path))
            //    {
            //        if (line.StartsWith("===================================================================="))
            //        {
            //            // 检查当前块是否匹配
            //            if (isTargetRequest && hasTargetMattressId)
            //            {
            //                filteredLogs.Add(currentBlock.ToString());
            //                matchCount++;
            //            }

            //            // 重置状态，开始新块
            //            currentBlock.Clear();
            //            isTargetRequest = false;
            //            hasTargetMattressId = false;
            //        }

            //        currentBlock.AppendLine(line);

            //        // 快速检测关键信息
            //        if (line.Contains("SaveMattressInterfaceRequest请求报文："))
            //        {
            //            isTargetRequest = true;
            //        }

            //        if (isTargetRequest && line.Contains("\"mattressid\":21665686"))
            //        {
            //            hasTargetMattressId = true;
            //        }
            //    }

            //    // 检查最后一个块
            //    if (isTargetRequest && hasTargetMattressId)
            //    {
            //        filteredLogs.Add(currentBlock.ToString());
            //        matchCount++;
            //    }

            //    File.WriteAllText(path2, string.Join("\n\n", filteredLogs));
            //    Console.WriteLine($"筛选完成！共找到 {matchCount} 条符合条件的日志");
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine($"错误: {ex.Message}");
            //}
            //#endregion
        }


        private void FilterLogs(string startTimeInput, string endTimeInput)
        {
            try
            {
                TimeSpan startTime = TimeSpan.Parse(startTimeInput);
                TimeSpan endTime = TimeSpan.Parse(endTimeInput);

                var filteredLogs = new List<string>();
                int matchCount = 0;
                var currentBlock = new StringBuilder(1024);
                bool isTargetRequest = false;
                bool hasTargetMattressId = false;
                DateTime? currentTime = null;

                foreach (string line in File.ReadLines(path))
                {
                    if (line.StartsWith("===================================================================="))
                    {
                        // 检查当前块是否在指定时间范围内且包含目标mattressid
                        if (currentTime.HasValue && IsInTimeRange(currentTime.Value, startTime, endTime) &&
                            isTargetRequest && hasTargetMattressId)
                        {
                            filteredLogs.Add(currentBlock.ToString());
                            matchCount++;
                        }

                        // 重置状态
                        currentBlock.Clear();
                        isTargetRequest = false;
                        hasTargetMattressId = false;
                        currentTime = null;
                    }

                    currentBlock.AppendLine(line);

                    // 解析时间
                    if (line.StartsWith("时间:") && currentTime == null)
                    {
                        string timeStr = line.Substring(3).Trim();
                        if (DateTime.TryParse(timeStr, out DateTime parsedTime))
                        {
                            currentTime = parsedTime;
                        }
                    }

                    // 检测关键信息
                    if (line.Contains("RefreshMattressInterfaceQdRequest请求报文：") || line.Contains("SaveMattressInterfaceRequest请求报文："))
                    {
                        isTargetRequest = true;
                    }

                    if (line.Contains("\"mattressid\":21669844"))
                    {
                        hasTargetMattressId = true;
                    }
                }

                // 处理最后一个块
                if (currentTime.HasValue && IsInTimeRange(currentTime.Value, startTime, endTime) &&
                    isTargetRequest && hasTargetMattressId)
                {
                    filteredLogs.Add(currentBlock.ToString());
                    matchCount++;
                }

                File.WriteAllText(path2, string.Join("\n\n", filteredLogs));
                Console.WriteLine($"筛选完成！共找到 {matchCount} 条 {startTime}-{endTime} 时间段的日志");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }
        private static bool IsInTimeRange(DateTime time, TimeSpan start, TimeSpan end)
        {
            TimeSpan currentTime = time.TimeOfDay;
            return currentTime >= start && currentTime <= end;
        }
    }
}
