using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

namespace MPStudio
{
    public class ItemTooltip : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerMoveHandler
    {
        public int luanguageId;

        [SerializeField] private RectTransform tooltipPanel;
        public Canvas canvas;
        [FormerlySerializedAs("wrect")] public RectTransform targetPanel;

        public Vector2 offset;

        private void Awake()
        {


        }

        private void Start()
        {
            tooltipPanel.gameObject.SetActive(false);
        }

        public string testStr()
        {
            var s =
                $"asddsfsdfdsfsdfsfsdffsfssffsffsfsffsfsffsfsdffsdsfsdfsdfsdfsffsfdfsdsdfdfsfdssd\nsdfsdfs\nfdssdfsdfdsf\ndfsdfsssdfsfsdfsdfsfsdfsdfsdfsdfsdfsffffdsf";
            return s;
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            tooltipPanel.gameObject.SetActive(true);
            //  print("enter");

        }

        public void OnPointerExit(PointerEventData eventData)
        {
            tooltipPanel.gameObject.SetActive(false);
            //  print("exit");

        }

        public void OnPointerMove(PointerEventData eventData)
        {
            UpdateTooltipPosition(eventData.position); //这是平面坐标
        }

        private void ShowTooltip()
        {
            //tooltipPanel.GetComponentInChildren<Text>(). text = "helo world";
            // 强制立即重建布局，确保ContentSizeFitter生效
            //  LayoutRebuilder.ForceRebuildLayoutImmediate(tooltipPanel)
            //  UpdateTooltipPosition();
        }

        private void UpdateTooltipPosition(Vector2 v2)
        {
            tooltipPanel.GetComponentInChildren<Text>().text = LanguageManager.Inst.GetMessage(luanguageId);
            Vector2 localPoint;
            // 将鼠标屏幕坐标转换为UI本地坐标
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
                    targetPanel,
                    v2,
                    null,
                    out localPoint))
            {
                // 应用偏移量
                localPoint += offset;
                //print(localPoint);

                // 设置工具提示位置
                tooltipPanel.localPosition = localPoint;
                return;

                // 确保工具提示不会超出屏幕
                Vector2 tooltipSize = tooltipPanel.sizeDelta;
                Vector2 canvasSize = canvas.GetComponent<RectTransform>().sizeDelta;

                // 检查右侧边界
                if (localPoint.x + tooltipSize.x > canvasSize.x * 0.5f)
                {
                    localPoint.x = canvasSize.x * 0.5f - tooltipSize.x;
                }

                // 检查顶部边界
                if (localPoint.y + tooltipSize.y > canvasSize.y * 0.5f)
                {
                    localPoint.y = canvasSize.y * 0.5f - tooltipSize.y;
                }
            }
        }

    }
}