using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Scripting;
using UnityEngine.UI;

[Preserve]
public class LogViewer : MonoBehaviour
{
    [Header("UI References")]
    public Text logText;
    public ScrollRect scrollRect;

    [Header("Settings")]
    public int maxLines = 1000;
    public bool autoScroll = true;
    public int lineHeight = 33;

    [Preserve]
    private Queue<string> logQueue = new Queue<string>();

    [Preserve]
    private bool isDirty = false;

    [Preserve]
    void OnEnable()
    {
        Application.logMessageReceived += HandleLog;
    }

    [Preserve]
    void OnDisable()
    {
        Application.logMessageReceived -= HandleLog;
    }

    [Preserve]
    void HandleLog(string logString, string stackTrace, LogType type)
    {
        string time = System.DateTime.Now.ToString("HH:mm:ss");
        string formattedLog = $"[{time}] {logString}";
        logQueue.Enqueue(formattedLog);
        isDirty = true;
    }

    [Preserve]
    void Update()
    {
        if (isDirty)
        {
            UpdateLogText();
            isDirty = false;
        }
    }


    [Preserve]
    void UpdateLogText()
    {
        if (logText == null || scrollRect == null)
        {
            Debug.LogWarning("LogViewer: 未绑定 logText 或 scrollRect");
            return;
        }

        // 限制最大行数
        while (logQueue.Count > maxLines)
        {
            logQueue.Dequeue();
        }

        // 拼接日志
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var log in logQueue)
        {
            sb.AppendLine(log);
        }

        logText.text = sb.ToString();

        // 动态设置尺寸
        RectTransform textRect = logText.GetComponent<RectTransform>();
        RectTransform contentRect = scrollRect.content;
        RectTransform viewportRect = scrollRect.viewport;

        if (textRect != null && contentRect != null && viewportRect != null)
        {
            // 设置 Text 和 Content 的宽度等于 Viewport 宽度
            float viewportWidth = viewportRect.rect.width;
            textRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, viewportWidth);
            contentRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, viewportWidth);

            // 计算文本内容的实际高度
            float textHeight = CalculateTextHeight(logText.text, logText, viewportWidth);

            // 设置 Content 的高度
            contentRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, textHeight);

            // 强制更新布局
            LayoutRebuilder.ForceRebuildLayoutImmediate(contentRect);
            Canvas.ForceUpdateCanvases();
        }

        // 自动滚动到底部
        if (autoScroll)
        {
            ScrollToBottomNow();
        }
    }

    // 计算文本内容的实际高度
    [Preserve]
    float CalculateTextHeight(string text, Text textComponent, float width)
    {
        if (string.IsNullOrEmpty(text))
            return 100;

        // 创建生成设置
        var settings = textComponent.GetGenerationSettings(new Vector2(width, 0));

        // 获取文本的首选高度
        float height = textComponent.cachedTextGenerator.GetPreferredHeight(text, settings);

        return height / textComponent.pixelsPerUnit;
    }

    [Preserve]
    void ScrollToBottomNow()
    {
        // 滚动到底部
        scrollRect.verticalNormalizedPosition = 0f;
    }

    [Preserve]
    public void ClearLogs()
    {
        logQueue.Clear();
        if (logText != null)
        {
            logText.text = "";
        }
    }
}