MomentItem.cs 15.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.Video;

/**
 * 功能描述: 单条朋友圈+动态初始化 
 * @author wangQc
 * @date 2025/6/4 09:20
 */
public class MomentItem : MonoBehaviour
{
    public Image avatarImage;
    public TextMeshProUGUI usernameText;
    public TextMeshProUGUI contentText;

    
    public Transform imageGrid; // 父对象,用于图片缩略图排列
    public GameObject imagePrefab; // 小图预制体
    public Image bigImageInit; //大图初始化

    public Transform videoGrid; // 父对象
    public GameObject videoPrefab; // 视频预制体
    
    public TextMeshProUGUI from;
    public TextMeshProUGUI time;
    public Image likeIconImage;

    public Transform likeGrid; // 父对象,用于点赞emjoi排列
    public GameObject likePrefab; // 点赞emjoi预制体

    public TextMeshProUGUI likesText;
    public TextMeshProUGUI likedEmoji;
    
    private string originLikesText;

    public TextMeshProUGUI commentsText;
    
    public GameObject totalPanel;
    
    //吉祥物图片
    public Image mascot;
    
    public RectTransform checkRectTransform; // 你要检测的 UI 元素
    private RectTransform scrollViewRectTransform;
    private ScrollRect scrollRect;


    private float timer = 0f;
    
    void Awake()
    { 
        scrollViewRectTransform = checkRectTransform.parent.parent.parent.parent.parent.parent.parent as RectTransform;
        scrollRect = scrollViewRectTransform.GetComponent<ScrollRect>();
    }
    


    void FixedUpdate()
    {
        timer += Time.deltaTime;
        if (timer < 1f)
        {
            return;
        }
        
        timer = 0f;
        if (scrollRect.velocity.sqrMagnitude > 0.01f)
        {
            bool isOver = IsUIOverlapping(checkRectTransform, scrollViewRectTransform);
            if (!isOver)
            {
                likesText.text = originLikesText;
                likeIconImage.gameObject.SetActive(true);
                likedEmoji.gameObject.SetActive(false);
        
            }
        }
    }
    

    
    public bool IsUIOverlapping(RectTransform rectA, RectTransform rectB)
    {
        Vector3[] cornersA = new Vector3[4];
        Vector3[] cornersB = new Vector3[4];

        rectA.GetWorldCorners(cornersA);
        rectB.GetWorldCorners(cornersB);

        // 打印 A 的四个角(左下、左上、右上、右下)
        // Debug.Log($"A corners:\n" +
        //           $"左下: {cornersA[0]}\n" +
        //           $"左上:    {cornersA[1]}\n" +
        //           $"右上:   {cornersA[2]}\n" +
        //           $"右下:{cornersA[3]}");
        //
        // Debug.Log($"B corners:\n" +
        //           $"左下: {cornersB[0]}\n" +
        //           $"左上:    {cornersB[1]}\n" +
        //           $"右上:   {cornersB[2]}\n" +
        //           $"右下:{cornersB[3]}");
        
        return geRect(cornersA).Overlaps(geRect(cornersB));
    }

    public Rect geRect(Vector3[] corners)
    {
        // 获取最小和最大点
        Vector3 min = corners[0];
        Vector3 max = corners[0];

        for (int i = 1; i < 4; i++)
        {
            min = Vector3.Min(min, corners[i]);
            max = Vector3.Max(max, corners[i]);
        }

        // 构建 Rect(在世界坐标系下)
        return  new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

    }



    public int Setup(Moment moment,List<Like> likeList,string logo,int momentCount)
    {
        //计算单条朋友圈所占高度
        //每行字50
        int line = 50;
        //图片、视频400
        int mediaImage = 580;
        int mediaVideo = 580;
        int momentHeight = 0;
        usernameText.text = moment.username;
        momentHeight+= line;
        
        contentText.text = moment.text;
        //计算文本的行数,每行30个字
        int textLine = (int)Math.Ceiling((double)moment.text.Length / 30);
        momentHeight+= textLine*line;
        
        from.text = moment.from;
        time.text = moment.time;

        momentHeight+= line;

        //单条朋友圈面板点击事件
        Button totalPanelBtn = totalPanel.GetComponent<Button>();
        totalPanelBtn.onClick.AddListener(() =>
        {
            likeGrid.gameObject.SetActive(false);
        });
        
        
        StartCoroutine(ImageLoader.LoadImage(moment.avatarUrl, avatarImage));
        
        //引导点赞动画
        likeIconImage.transform.DOScale(0.8f, 2f).SetLoops(-1, LoopType.Yoyo).SetEase(Ease.InOutSine);

        Button likeIconBtn = likeIconImage.GetComponent<Button>();
        likeIconBtn.onClick.AddListener(() =>
        {
            likeGrid.gameObject.SetActive(true);
        });
        
        
        Button likedEmojiBtn = likedEmoji.GetComponent<Button>();
        likedEmojiBtn.onClick.AddListener(() =>
        {
            //显示点赞Icon
            likeIconImage.gameObject.SetActive(true);
            
            likedEmoji.gameObject.SetActive(false);
            likedEmoji.text = "";
            likeGrid.gameObject.SetActive(true);
        });


        // 清空之前的图片
        foreach (Transform child in imageGrid)
            Destroy(child.gameObject);

        UpdateGridLayout(moment.imageUrls.Count);

        foreach (string url in moment.imageUrls)
        {
            imageGrid.gameObject.SetActive(true);
            videoGrid.gameObject.SetActive(false);
            

            GameObject imgObj = Instantiate(imagePrefab, imageGrid);
            //如果只有一张,则点击大图显示右侧
            if (moment.imageUrls.Count == 1)
            {
                //红点
                RectTransform redPointRect = imgObj.transform.GetChild(0).GetComponent<RectTransform>();
                // 设置局部坐标(anchoredPosition 是相对父节点锚点的偏移)
                redPointRect.anchoredPosition = new Vector2(-7f, -420);
                
                //查看大图中文
                Transform showBig = imgObj.transform.GetChild(1);
                //1.修改文字颜色 #3C4963         //加粗文字
                showBig.GetComponent<TextMeshProUGUI>().color = new Color32(60, 73, 99, 255);
                showBig.GetComponent<TextMeshProUGUI>().fontStyle = FontStyles.Bold;
                
                //2.修改文字位置
                showBig.GetComponent<RectTransform>().anchoredPosition = new Vector2(168, -416);

            }

            Image img = imgObj.GetComponent<Image>();
            //缩略图和大图不一样,第1次LoadImage只为了预下载大图片
            StartCoroutine(ImageLoader.LoadImage(AddSuffixBeforeExtension(url,"-s"), img));
            
            StartCoroutine(ImageLoader.LoadImage(url, bigImageInit));
            bigImageInit.sprite = null;
            
            Transform child = imgObj.transform.GetChild(0);
            child.DOScale(1.5f, 2f).SetLoops(-1, LoopType.Yoyo).SetEase(Ease.InOutSine);
            
            Button btn = imgObj.GetComponent<Button>();
            btn.onClick.AddListener(() => ImageViewerManager.Instance.ShowImage(url,moment.text,logo,moment.time));
        }
        
        GridLayoutGroup gridLayout = imageGrid.GetComponent<GridLayoutGroup>();

        var row = (int)Math.Ceiling((double)moment.imageUrls.Count / gridLayout.constraintCount);
        //一行两张图片,计算有几行
        momentHeight+=  row * (int)gridLayout.cellSize.y;

        
        
        foreach (Transform child in videoGrid)
            Destroy(child.gameObject);
        //判断是否有视频
        if (!string.IsNullOrWhiteSpace(moment.video))
        {
            //有视频就没有图
            imageGrid.gameObject.SetActive(false);
            videoGrid.gameObject.SetActive(true);
            // 1. 实例化
            GameObject obj = Instantiate(videoPrefab, videoGrid);

            Transform child = obj.transform.GetChild(2);
            child.DOScale(1.3f, 2f).SetLoops(-1, LoopType.Yoyo).SetEase(Ease.InOutSine);

            
            // 2. 获取组件
            RawImage rawImage = obj.GetComponentInChildren<RawImage>();
            VideoPlayer videoPlayer = obj.GetComponentInChildren<VideoPlayer>();

            // 3. 创建新的 RenderTexture(每个视频独立)
            RenderTexture renderTex = new RenderTexture(1920, 1080, 0);
            renderTex.Create();

            // 4. 绑定到 RawImage 和 VideoPlayer
            videoPlayer.targetTexture = renderTex;
            rawImage.texture = renderTex;

            // 5. 设置视频源
            videoPlayer.source = VideoSource.Url;
            videoPlayer.url = moment.video;
            
            // 播放一下
            videoPlayer.Play();
            videoPlayer.Pause();
            
            Button btn = obj.GetComponent<Button>();
            btn.onClick.AddListener(() => VideoViewerManager.Instance.ShowVideo(moment));
            
            momentHeight+=  mediaVideo;
        }


        //如果有吉祥物图片
        if (!string.IsNullOrWhiteSpace(moment.mascot))
        {
            Color color = mascot.color;
            color.a = 1f;
            mascot.color = color;
            StartCoroutine(ImageLoader.LoadImage(moment.mascot, mascot));
            //吉祥物y轴坐标
            mascot.GetComponent<RectTransform>().localPosition = new Vector2(200, 240-120*row);

        }

        


        //点赞图片以及文字初始化
        foreach (Transform child in likeGrid)
            Destroy(child.gameObject);
        foreach (Like like in likeList)
        {
            GameObject likeEmojiObj = Instantiate(likePrefab, likeGrid);
            var evaluateTextMeshPro = likeEmojiObj.GetComponent<TextMeshProUGUI>();
            evaluateTextMeshPro.text = like.icon;
            
            Button likeEmojiBtn = likeEmojiObj.GetComponent<Button>();
            likeEmojiBtn.onClick.AddListener(() =>
            {
                Debug.Log(like.bullet);
                //埋点+显示当前点赞人数
                var buryPointInfos = new BuryPointManager.BuryPointInfos();
                buryPointInfos.eventId = "button_click";
                var buryPointClickParam = new BuryPointManager.BuryPointClickParam
                {
                    page = "FriendCircle",
                };
                buryPointClickParam.buttonId = $"moment_{momentCount}_{like.name}";
                buryPointClickParam.buttonText = $"第{momentCount}条朋友圈点赞,点赞icon:{like.name}";
                buryPointInfos.remark = $"{moment.text}";
                buryPointInfos.@params = buryPointClickParam;
                BuryPointManager.Instance.BuryPoint(buryPointInfos, (res) =>
                {
                    BuryPointManager.RequestInfos<long> requestInfos = JsonUtility.FromJson<BuryPointManager.RequestInfos<long>>(res);
                    // Debug.Log("埋点请求成功:"+res);
                    //发送弹幕(竖屏)
                    totalPanel.GetComponent<DanmakuManager>().AddDanmakuBatch(new List<string>
                    {
                        like.bullet,
                        like.icon + " " + like.icon + " " + like.icon,
                        $"第{requestInfos.data}位"
                    },0.4f,2);

                }, (err) =>
                {
                    Debug.Log("埋点请求报错:"+err);
                });
                
                //隐藏点赞Icon
                likeIconImage.gameObject.SetActive(false);
                //显示已经点赞的emoji标签
                likedEmoji.text = like.icon;

                likedEmoji.gameObject.SetActive(true);

                likeGrid.gameObject.SetActive(false);
                
                //增加点赞名字
                var names = likesText.text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(n => n.Trim())
                    .ToList(); // ✅ 转成 List<string>
                string target = "一个不愿透露姓名的游客";
                if (!names.Contains(target))
                {
                    names.Add(target);
                }
                likesText.text = string.Join(", ", names);
            });
        }
        
        momentHeight+= line;

        likesText.text = string.Join(", ", moment.likeNameList);
        originLikesText = likesText.text;
        
        commentsText.text = "";
        LoadComments(moment.comments);
        momentHeight+= moment.comments.Count*line;

        return momentHeight+500;
    }
    

    public void LoadComments(List<CommentData> comments)
    {
        string nameHex = "3C4963"; // 名称和冒号颜色
        StringBuilder sb = new StringBuilder();

        foreach (var comment in comments)
        {
            string commentLine;
            if (!string.IsNullOrEmpty(comment.replier))
            {
                // 有回复者
                commentLine = $"<b><color=#{nameHex}>{comment.commenter}</color></b> 回复 <b><color=#{nameHex}>{comment.replier}</color></b><color=#{nameHex}>:</color>{comment.content}";
            }
            else
            {
                // 普通评论
                commentLine = $"<b><color=#{nameHex}>{comment.commenter}</color></b><color=#{nameHex}>:</color> {comment.content}";
            }

            sb.AppendLine(commentLine); // 添加换行
        }

        commentsText.text = sb.ToString();
    }
    
    
    public void UpdateGridLayout(int imageCount)
    {
        float size2Column = 580f;
        float size3Column = 386f;
    
        GridLayoutGroup gridLayout = imageGrid.GetComponent<GridLayoutGroup>();

        if (gridLayout == null)
        {
            Debug.LogWarning("imageGrid 没有 GridLayoutGroup 组件");
            return;
        }

        float cellSize = 0f;
        int constraintCount = 3;

        if (imageCount <= 0)
        {
            gridLayout.constraintCount = 3;
            return;
        }

        if (imageCount == 1)
        {
            // 单张图的排版一般单独做,不走 Grid
            // 你可以特殊处理单张图,返回直接退出
            Debug.Log("单张图,通常单独排版");
            return;
        }
        else if (imageCount == 2)
        {
            constraintCount = 2;
            cellSize = size2Column;
        }
        else if (imageCount == 4)
        {
            constraintCount = 2;
            cellSize = size2Column;
        }
        else
        {
            constraintCount = 3;
            cellSize = size3Column;
        }

        // 应用设置
        gridLayout.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
        gridLayout.constraintCount = constraintCount;
        gridLayout.cellSize = new Vector2(cellSize, cellSize);
        

        Debug.Log($"更新 GridLayout:图片数量={imageCount},列数={constraintCount},cellSize={cellSize}");
    }
    
    
    public string AddSuffixBeforeExtension(string url, string suffix)
    {
        int lastDotIndex = url.LastIndexOf('.');
        if (lastDotIndex == -1) return url; // 没有扩展名

        string prefix = url.Substring(0, lastDotIndex);
        string extension = url.Substring(lastDotIndex); // 包含点

        return $"{prefix}{suffix}{extension}";
    }


}