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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using DG.Tweening;
 
/// <summary>
/// UI管理器 - 负责管理所有UI界面的显示、隐藏和层级
/// </summary>
public class UIManager : ManagerBase<UIManager>
{
    #region 常量和枚举
    
    // 基础排序顺序
    private const int BASE_SORTING_ORDER = 10;
    
    #endregion
 
    #region 字段和属性
    
    // UI根节点
    private Transform uiRoot;
    
    // 各层级的Transform
    private Transform staticTrans;
    private Transform bottomTrans;
    private Transform midTrans;
    private Transform systemTrans;
    private Transform loadingTrans;
 
    // UI字典,存储所有已加载的UI,键为UI名称,值为UI实例
    private Dictionary<string, List<UIBase>> uiDict = new Dictionary<string, List<UIBase>>();
    
    // 存储关闭但未销毁的UI,键为UI名称,值为UI实例
    private Dictionary<string, List<UIBase>> closedUIDict = new Dictionary<string, List<UIBase>>();
 
    // UI栈,用于管理UI的显示顺序
    private Stack<UIBase> uiStack = new Stack<UIBase>();
    
    // 当前最高的排序顺序
    private int currentHighestSortingOrder = 0;
    
    // 当前回合数,用于记录UI的使用情况
    private int currentRound = 0;
    
    // 缓存层级对应的排序顺序
    private Dictionary<UILayer, int> layerSortingOrderCache = new Dictionary<UILayer, int>();
    
    // 缓存层级对应的Transform
    private Dictionary<UILayer, Transform> layerTransformCache = new Dictionary<UILayer, Transform>();
    
    // UI实例计数器,用于为同类型UI生成唯一标识
    private Dictionary<string, int> uiInstanceCounter = new Dictionary<string, int>();
    
    // 上次检查时间
    private float lastCheckTime = 0f;
    // 检查间隔(秒)
    private const float CHECK_INTERVAL = 5f;
    
    public Action<UIBase> OnOpenWindow;
 
    public Action<UIBase> OnCloseWindow;
 
    #endregion
 
    #region 初始化
 
    /// <summary>
    /// 初始化UI管理器
    /// </summary>
    public override void Init()
    {
        base.Init();
 
        // 初始化UI根节点
        InitUIRoot();
 
        // 初始化缓存
        layerSortingOrderCache.Clear();
        layerTransformCache.Clear();
        uiInstanceCounter.Clear();
 
        DOTween.SetTweensCapacity(500, 50);
        Debug.Log("UI管理器初始化完成");
        
    }
    
    /// <summary>
    /// 初始化UI根节点
    /// </summary>
    private void InitUIRoot()
    {
        // 查找UI根节点
        GameObject root = GameObject.Find("UIRoot");
        
        // 如果场景中没有UI根节点,则创建一个
        if (root == null)
        {
            root = GameObject.Instantiate(BuiltInLoader.LoadPrefab("UIRoot"));
            root.name = "UIRoot";
            if (root == null)
            {
                Debug.LogError("无法找到UI根节点");
                return;
            }
 
            // 添加DontDestroyOnLoad组件,确保UI根节点在场景切换时不被销毁
            GameObject.DontDestroyOnLoad(root);
        }
 
        uiRoot = root.transform;
        uiRoot.position = Vector3.zero;
 
        staticTrans = uiRoot.Find("Static");
        bottomTrans = uiRoot.Find("Bottom");
        midTrans = uiRoot.Find("Middle");
        loadingTrans = uiRoot.Find("Loading");
        systemTrans = uiRoot.Find("System");
 
        layerTransformCache.Clear();
        layerTransformCache.Add(UILayer.Static, staticTrans);
        layerTransformCache.Add(UILayer.Bottom, bottomTrans);
        layerTransformCache.Add(UILayer.Mid, midTrans);
        layerTransformCache.Add(UILayer.System, systemTrans);
        layerTransformCache.Add(UILayer.Loading, loadingTrans);
    }
    
    #endregion
 
    #region 辅助方法
    
    // 获取UI层级对应的基础排序顺序
    private int GetBaseSortingOrderForLayer(UILayer layer)
    {
        // 尝试从缓存中获取排序顺序
        if (layerSortingOrderCache.TryGetValue(layer, out int order))
            return order;
            
        // 如果缓存中没有,使用原来的方法计算并缓存结果
        int result;
        switch (layer)
        {
            case UILayer.Static:
                result = BASE_SORTING_ORDER;
                break;
            case UILayer.Bottom:
                result = BASE_SORTING_ORDER * 100;
                break;
            case UILayer.Mid:
                result = BASE_SORTING_ORDER * 1000;
                break;
            case UILayer.System:
                result = BASE_SORTING_ORDER * 10000;
                break;
            case UILayer.Loading:
                result = BASE_SORTING_ORDER * 100000;
                break;
            default:
                result = BASE_SORTING_ORDER * 10;
                break;
        }
        
        // 将结果存入缓存
        layerSortingOrderCache[layer] = result;
        return result;
    }
 
    // 获取层级对应的Transform
    private Transform GetTransForLayer(UILayer layer)
    {
        // 尝试从缓存中获取Transform
        if (layerTransformCache.TryGetValue(layer, out Transform trans))
            return trans;
            
        // 如果缓存中没有,使用原来的方法获取并缓存结果
        Transform result;
        switch (layer)
        {
            case UILayer.Static:
                result = staticTrans;
                break;
            case UILayer.Bottom:
                result = bottomTrans;
                break;
            case UILayer.Mid:
                result = midTrans;
                break;
            case UILayer.System:
                result = systemTrans;
                break;
            case UILayer.Loading:
                result = loadingTrans;
                break;
            default:
                result = bottomTrans;
                break;
        }
        
        // 将结果存入缓存
        layerTransformCache[layer] = result;
        return result;
    }
    
    // 获取UI实例,如果不存在则返回null
    public T GetUI<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return null;
        }
 
        // 尝试从字典中获取UI实例列表
        if (uiDict.TryGetValue(uiName, out List<UIBase> uiList) && uiList.Count > 0)
        {
            // 返回第一个实例
            return uiList[0] as T;
        }
 
        // 如果不存在,返回null
        return null;
    }
 
    public List<T> GetUIList<T>() where T : UIBase
    {
        List<T> uiList = new List<T>();
 
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return uiList;
        }
 
        // 尝试从字典中获取UI实例列表
        List<UIBase> tempList = null;
        uiDict.TryGetValue(uiName, out tempList);
 
        if (tempList != null)
        {
            for (int i = 0; i < tempList.Count; i++)
            {
                UIBase ui = tempList[i];
                if (null != ui)
                {
                    uiList.Add(ui as T);
                }
            }
        }
 
        return uiList;
    }
 
    public bool IsOpenedInList<T>() where T : UIBase
    {
        List<T> uiList = GetUIList<T>();
 
        foreach (T ui in uiList)
        {
            if (ui.IsActive())
            {
                return true;
            }
        }
 
        return false;
    }
 
    public bool IsOpened<T>() where T : UIBase
    {
        T ui = GetUI<T>();
 
        if (null != ui)
        {
            return ui.IsActive();
        }
 
        return false;
    }
    
    // 获取指定类型的所有UI实例
    public List<T> GetAllUI<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return new List<T>();
        }
 
        // 尝试从字典中获取UI实例列表
        if (uiDict.TryGetValue(uiName, out List<UIBase> uiList) && uiList.Count > 0)
        {
            // 将列表中的所有实例转换为指定类型并返回
            return uiList.Cast<T>().ToList();
        }
 
        // 如果不存在,返回空列表
        return new List<T>();
    }
    
    // 更新父级UI的回合数
    private void UpdateParentUIRounds(UIBase ui)
    {
        // 如果UI为空或不支持父子关系,直接返回
        if (ui == null || !ui.supportParentChildRelation)
            return;
            
        // 获取父级UI
        UIBase parentUI = ui.parentUI;
        // 遍历所有父级UI,更新回合数
        while (parentUI != null)
        {
            // 更新父级UI的最后使用回合数
            parentUI.lastUsedRound = currentRound;
            // 继续向上查找父级UI
            parentUI = parentUI.parentUI;
        }
    }
    
    // 递归收集所有子UI
    private void CollectChildrenUI(UIBase ui, List<UIBase> result)
    {
        // 如果UI为空或没有子UI或不支持父子关系,直接返回
        if (ui == null || !ui.supportParentChildRelation || ui.childrenUI == null || ui.childrenUI.Count == 0)
            return;
        
        // 遍历所有子UI
        foreach (var childUI in ui.childrenUI)
        {
            // 如果结果列表中不包含当前子UI,则添加
            if (!result.Contains(childUI))
            {
                // 添加到结果列表
                result.Add(childUI);
                // 递归收集子UI的子UI
                CollectChildrenUI(childUI, result);
            }
        }
    }
    
    /// <summary>
    /// 检查并关闭长时间未使用的UI
    /// </summary>
    public void CheckAndCloseIdleUI()
    {
        // 如果没有UI,直接返回
        if (uiDict.Count == 0 && closedUIDict.Count == 0)
            return;
            
        // 创建需要关闭的UI列表
        List<UIBase> uiToClose = new List<UIBase>();
        
        // 遍历所有活跃UI
        foreach (var uiList in uiDict.Values)
        {
            foreach (var ui in uiList)
            {
                // 如果UI是持久化的,跳过
                if (ui.isPersistent)
                    continue;
                    
                if (ui.IsActive())
                    continue;
 
                // 计算UI空闲的回合数
                int idleRounds = currentRound - ui.lastUsedRound;
                
                // 如果空闲回合数超过最大空闲回合数,添加到关闭列表
                if (idleRounds > ui.maxIdleRounds)
                {
                    uiToClose.Add(ui);
                }
            }
        }
        
        // 遍历所有关闭的UI
        List<string> emptyKeys = new List<string>();
        foreach (var kvp in closedUIDict)
        {
            string uiName = kvp.Key;
            List<UIBase> uiList = kvp.Value;
            List<UIBase> uiToRemove = new List<UIBase>();
            
            foreach (var ui in uiList)
            {
                // 计算UI空闲的回合数
                int idleRounds = currentRound - ui.lastUsedRound;
                
                // 如果空闲回合数超过最大空闲回合数,添加到关闭列表
                if (idleRounds > ui.maxIdleRounds)
                {
                    uiToClose.Add(ui);
                    uiToRemove.Add(ui);
                }
            }
            
            // 从关闭列表中移除需要销毁的UI
            foreach (var ui in uiToRemove)
            {
                uiList.Remove(ui);
            }
            
            // 如果列表为空,记录需要从字典中移除的键
            if (uiList.Count == 0)
            {
                emptyKeys.Add(uiName);
            }
        }
        
        // 从字典中移除空列表
        foreach (var key in emptyKeys)
        {
            closedUIDict.Remove(key);
        }
        
        // 销毁所有需要关闭的UI
        foreach (var ui in uiToClose)
        {
            // 记录日志
            Debug.Log($"销毁长时间未使用的UI: {ui.uiName}, 空闲回合数: {currentRound - ui.lastUsedRound}");
            // 销毁UI对象
            GameObject.Destroy(ui.gameObject);
        }
    }
    
    // // 生成UI实例的唯一标识
    // private string GenerateUIInstanceID(string uiName)
    // {
    //     // 如果计数器中不存在该UI类型,初始化为0
    //     if (!uiInstanceCounter.ContainsKey(uiName))
    //     {
    //         uiInstanceCounter[uiName] = 0;
    //     }
        
    //     // 递增计数器
    //     uiInstanceCounter[uiName]++;
        
    //     // 返回带有计数的唯一标识
    //     return $"{uiName}_{uiInstanceCounter[uiName]}";
    // }
    
    #endregion
 
    #region UI资源管理
 
    private UIBase LoadUIResource(string uiName)
    {
        // 从资源管理器加载UI预制体
        GameObject prefab = ResManager.Instance.LoadAsset<GameObject>("UI", uiName);
 
        // 检查预制体是否加载成功
        if (prefab == null)
        {
            // 记录错误日志
            Debug.LogError($"加载UI预制体失败: {uiName}");
            return null;
        }
 
        // 实例化UI对象
        GameObject uiObject = GameObject.Instantiate(prefab);
        // 设置对象名称
        uiObject.name = uiName;
 
        // 通过uiName映射Type
        Type uiType = Type.GetType(uiName);
        if (uiType == null)
        {
            Debug.LogError($"找不到UI类型: {uiName}");
            return null;
        }
 
        // 获取UI基类组件
        UIBase uiBase = uiObject.GetComponent(uiType) as UIBase;
 
        // 检查UI基类组件是否存在
        if (uiBase == null)
        {
            // 记录错误日志
            Debug.LogError($"UI预制体 {uiName} 没有 UIBase 组件或类型不匹配");
            return null;
        }
 
        // 设置UI名称
        uiBase.uiName = uiName;
 
        // 设置父节点为UI根节点
        Transform parentTrans = GetTransForLayer(uiBase.uiLayer);
 
        uiObject.transform.SetParent(parentTrans, false);
 
        // 设置排序顺序
        int baseSortingOrder = GetBaseSortingOrderForLayer(uiBase.uiLayer);
        uiBase.SetSortingOrder(baseSortingOrder);
 
        return uiBase;
    }
 
    // 加载UI预制体
    private T LoadUIResource<T>(string uiName) where T : UIBase
    {
        return LoadUIResource(uiName) as T;
    }
    
    #endregion
 
    #region UI排序管理
    
    // 更新UI排序顺序
    private void UpdateUISortingOrder()
    {
        // 重置当前最高排序顺序
        currentHighestSortingOrder = 0;
        
        // 遍历UI栈,设置排序顺序
        UIBase[] uiArray = new UIBase[uiStack.Count];
        uiStack.CopyTo(uiArray, 0);
        
        // 先按照UILayer进行排序,然后再按照栈顺序排序
        Array.Sort(uiArray, (a, b) => {
            // 比较UI层级
            int layerCompare = a.uiLayer.CompareTo(b.uiLayer);
            if (layerCompare != 0)
                return layerCompare;
                
            // 同层级内,按照栈中的顺序排序
            return Array.IndexOf(uiArray, b).CompareTo(Array.IndexOf(uiArray, a));
        });
        
        // 遍历排序后的UI数组,设置排序顺序
        foreach (var ui in uiArray)
        {
            // 获取基础排序顺序
            int baseSortingOrder = GetBaseSortingOrderForLayer(ui.uiLayer);
            // 计算当前UI的排序顺序
            int sortingOrder = baseSortingOrder + currentHighestSortingOrder;
            // 设置UI的排序顺序
            ui.SetSortingOrder(sortingOrder);
            // 更新当前最高排序顺序
            currentHighestSortingOrder += 10;
 
            // Debug.Log(ui.uiName + " order is " + sortingOrder + " " + currentHighestSortingOrder);
        }
    }
    
    #endregion
 
    #region UI操作
 
 
 
    private UIBase GetLastSupportParentChildRelationUI()
    {
        List<UIBase> tempList = new List<UIBase>();
 
        UIBase target = null;
 
        while (target == null && uiStack.Count > 0)
        {
            UIBase uiBase = uiStack.Pop();
 
            if (uiBase != null && uiBase.supportParentChildRelation && !uiBase.isMainUI)
            {
                target = uiBase;
            }
 
            tempList.Add(uiBase);
        }
 
        for (int i = tempList.Count - 1; i >= 0; i--)
        {
            uiStack.Push(tempList[i]);
        }
 
        return target;
    }
 
    public UIBase OpenWindow(string uiName)
    {
        // 优先从closedUIDict中获取
        UIBase parentUI = null;
 
        UIBase returnValue = null;
 
        Debug.Log("OpenWindow " + uiName);
 
        List<UIBase> closedUIList = new List<UIBase>();
 
        if (closedUIDict.TryGetValue(uiName, out closedUIList) && closedUIList.Count > 0)
        {
            Debug.Log("OpenWindow getFromClosedDict " + uiName);
 
            returnValue = closedUIList[0] as UIBase;
            closedUIList.RemoveAt(0);
            
            if (closedUIList.Count == 0)
            {
                closedUIDict.Remove(uiName);
            }
        }
        else
        {
            Debug.Log("OpenWindow getNewLoad " + uiName);
            returnValue = LoadUIResource(uiName);
            if (returnValue == null)
            {
                // 记录错误日志
                Debug.LogError($"打开UI失败: {uiName}");
                return null;
            }
        }
        
        returnValue.gameObject.SetActive(true);
        
        // 自动设置父级UI(如果未指定且支持父子关系)
        if (returnValue.supportParentChildRelation && uiStack.Count > 0)
        {
            // 获取栈顶UI
            parentUI = GetLastSupportParentChildRelationUI();
        }
        
        // 设置父级UI
        if (parentUI != null)
        {
            // 设置父子关系
            returnValue.parentUI = parentUI;
            if (parentUI.childrenUI == null)
            {
                // 初始化父级UI的子UI列表
                parentUI.childrenUI = new List<UIBase>();
            }
            // 添加到父级UI的子UI列表
            parentUI.childrenUI.Add(returnValue);
        }
        
        // 更新回合数
        currentRound++;
        // 设置UI的最后使用回合数
        returnValue.lastUsedRound = currentRound;
        // 更新父级UI的回合数
        UpdateParentUIRounds(returnValue);
        
        // 将UI添加到字典中
        if (!uiDict.ContainsKey(uiName))
        {
            // 如果字典中不存在该类型的UI,创建新列表
            uiDict[uiName] = new List<UIBase>();
        }
        // 添加到UI列表
        uiDict[uiName].Add(returnValue);
        
        // 将UI添加到栈中
        uiStack.Push(returnValue);
        
        // 更新UI排序顺序
        UpdateUISortingOrder();
        
        // 打开UI
        returnValue.HandleOpen();
 
        OnOpenWindow?.Invoke(returnValue);
        
        // 检查并关闭长时间未使用的UI
        CheckAndCloseIdleUI();
        
        return returnValue;
    }
 
    /// <summary>
    /// 打开UI
    /// </summary>
    public T OpenWindow<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        return OpenWindow(uiName) as T;
    }
    
    /// <summary>
    /// 关闭UI
    /// </summary>
    public void CloseWindow<T>(bool destroy = false) where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        
        CloseWindow(uiName, destroy);
        
    }
 
    public void CloseWindow(string uiName, bool destroy = false)
    {
        // 检查UI是否存在
        if (!uiDict.ContainsKey(uiName) || uiDict[uiName].Count == 0)
        {
            // 记录警告日志
            Debug.LogWarning($"尝试关闭不存在的UI: {uiName}");
            return;
        }
        
        // 获取第一个UI实例
        UIBase ui = uiDict[uiName][0];
        
        // 关闭UI
        CloseWindow(ui, destroy);
    }
    
    /// <summary>
    /// 关闭指定的UI实例
    /// </summary>
    public void CloseWindow(UIBase ui, bool destroy = false)
    {
        // 检查UI是否为空
        if (ui == null)
        {
            // 记录警告日志
            Debug.LogWarning("尝试关闭空UI");
            return;
        }
 
        if (!ui.IsActive())
        {
            return;
        }
        
        // 获取UI类型名称
        string uiName = ui.uiName;
 
        Debug.Log("CloseWindow " + uiName + " destroy : " + destroy.ToString());
 
        // 收集所有子UI
        List<UIBase> childrenUI = new List<UIBase>();
        if (ui.supportParentChildRelation)
        {
            CollectChildrenUI(ui, childrenUI);
        }
        
        // 先关闭所有子UI
        foreach (var childUI in childrenUI)
        {
            // 关闭子UI
            CloseWindow(childUI, destroy);
        }
        
        // 从栈中移除UI
        Stack<UIBase> tempStack = new Stack<UIBase>();
        while (uiStack.Count > 0)
        {
            // 弹出栈顶UI
            UIBase tempUI = uiStack.Pop();
            // 如果不是要关闭的UI,则保存到临时栈中
            if (tempUI != ui)
            {
                tempStack.Push(tempUI);
            }
        }
        
        // 将临时栈中的UI重新压入栈中
        while (tempStack.Count > 0)
        {
            uiStack.Push(tempStack.Pop());
        }
        
        // 从字典中移除UI
        if (uiDict.ContainsKey(uiName))
        {
            // 从UI列表中移除
            uiDict[uiName].Remove(ui);
            // 如果列表为空,从字典中移除该类型
            if (uiDict[uiName].Count == 0)
            {
                uiDict.Remove(uiName);
            }
        }
        
        // 从父级UI的子UI列表中移除
        if (ui.supportParentChildRelation && ui.parentUI != null && ui.parentUI.childrenUI != null)
        {
            // 从父级UI的子UI列表中移除
            ui.parentUI.childrenUI.Remove(ui);
        }
        
        // 关闭UI
        ui.HandleClose();
        OnCloseWindow?.Invoke(ui);
        
        if (destroy)
        {
            // 销毁UI对象
            GameObject.Destroy(ui.gameObject);
        }
        else
        {
            // 添加到closedUIDict
            if (!closedUIDict.ContainsKey(uiName))
            {
                closedUIDict[uiName] = new List<UIBase>();
            }
            closedUIDict[uiName].Add(ui);
            
            Debug.Log("CloseWindow " + uiName + " destroy : " + destroy.ToString() + " push to closedUIDict");
 
            // 隐藏UI (交给handle close内部自己去做)
            // ui.gameObject.SetActive(false);
        }
        
        // 更新UI排序顺序
        UpdateUISortingOrder();
    }
    
    /// <summary>
    /// 关闭指定类型的所有UI实例
    /// </summary>
    public void CloseAllWindows<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        
        // 检查UI是否存在
        if (!uiDict.ContainsKey(uiName) || uiDict[uiName].Count == 0)
        {
            // 记录警告日志
            Debug.LogWarning($"尝试关闭不存在的UI: {uiName}");
            return;
        }
        
        // 创建UI实例列表的副本,因为在关闭过程中会修改原列表
        List<UIBase> uiListCopy = new List<UIBase>(uiDict[uiName]);
        
        // 关闭所有UI实例
        foreach (var ui in uiListCopy)
        {
            // 关闭UI实例
            CloseWindow(ui, false);
        }
    }
 
    public void ReturnMainUI()
    {
        List<UIBase> allUI = new List<UIBase>(uiStack);
 
        for (int i = 0; i < allUI.Count; i++)
        {
            UIBase uiBase = allUI[i];
            if (!uiBase.isMainUI && uiBase.uiLayer < UILayer.System)
            {
                CloseWindow(uiBase);
            }
        }
    }
    
    /// <summary>
    /// 关闭所有UI
    /// </summary>
    public void DestroyAllUI()
    {
        // 创建UI栈的副本,因为在关闭过程中会修改原栈
        UIBase[] uiArray = new UIBase[uiStack.Count];
        uiStack.CopyTo(uiArray, 0);
        
        // 关闭所有UI
        foreach (var ui in uiArray)
        {
            // 关闭UI
            CloseWindow(ui, true);
        }
        
        foreach (var uiList in closedUIDict.Values)
        {
            foreach (var ui in uiList)
            {
                GameObject.Destroy(ui.gameObject);
            }
        }
 
        // 清空UI字典和栈
        uiDict.Clear();
        uiStack.Clear();
        closedUIDict.Clear();
    }
    
    /// <summary>
    /// 刷新UI
    /// </summary>
    public void RefreshUI<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        
        // 检查UI是否存在
        if (!uiDict.ContainsKey(uiName) || uiDict[uiName].Count == 0)
        {
            // 记录警告日志
            Debug.LogWarning($"尝试刷新不存在的UI: {uiName}");
            return;
        }
        
        // 刷新所有该类型的UI实例
        foreach (var ui in uiDict[uiName])
        {
            // 刷新UI
            ui.Refresh();
        }
    }
    
    /// <summary>
    /// 刷新所有UI
    /// </summary>
    public void RefreshAllUI()
    {
        // 遍历所有UI类型
        foreach (var uiList in uiDict.Values)
        {
            // 遍历该类型的所有UI实例
            foreach (var ui in uiList)
            {
                // 刷新UI
                ui.Refresh();
            }
        }
    }
    
    private void Update()
    {
        // 如果距离上次检查的时间超过了检查间隔
        if (Time.time - lastCheckTime > CHECK_INTERVAL)
        {
            // 更新上次检查时间
            lastCheckTime = Time.time;
            // 检查并关闭长时间未使用的UI
            CheckAndCloseIdleUI();
        }
    }
    
    #endregion
 
    #region 释放资源
    
    /// <summary>
    /// 释放资源
    /// </summary>
    public override void Release()
    {
        // 关闭所有UI
        DestroyAllUI();
        
        // 清空缓存
        layerSortingOrderCache.Clear();
        layerTransformCache.Clear();
        uiInstanceCounter.Clear();
        
        Debug.Log("UI管理器资源释放完成");
    }
    
    #endregion
}